hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
88a8131c18709cf479f4b8f8ebc2304a1447e6b4
diff --git a/client/lib/analytics/mc.js b/client/lib/analytics/mc.js index <HASH>..<HASH> 100644 --- a/client/lib/analytics/mc.js +++ b/client/lib/analytics/mc.js @@ -45,7 +45,7 @@ export function bumpStat( group, name ) { mcDebug( 'Bumping stat %s:%s', group, name ); } - if ( config( 'mc_analytics_enabled' ) ) { + if ( 'undefined' !== typeof window && config( 'mc_analytics_enabled' ) ) { const uriComponent = buildQuerystring( group, name ); new window.Image().src = document.location.protocol + @@ -64,7 +64,7 @@ export function bumpStatWithPageView( group, name ) { mcDebug( 'Bumping page view %s:%s', group, name ); } - if ( config( 'mc_analytics_enabled' ) ) { + if ( 'undefined' !== typeof window && config( 'mc_analytics_enabled' ) ) { const uriComponent = buildQuerystringNoPrefix( group, name ); new window.Image().src = document.location.protocol +
Prevent `bumpStat` from triggering exception in node (#<I>)
Automattic_wp-calypso
train
3c790d002c000750469f66703d16e8287ae33849
diff --git a/yaas-product.js b/yaas-product.js index <HASH>..<HASH> 100644 --- a/yaas-product.js +++ b/yaas-product.js @@ -2,22 +2,22 @@ var pathProductBase = '/hybris/product/v2/{{projectId}}/products'; -var Product = function(rh) { +var Product = function (rh) { this.requestHelper = rh; - this.getProduct = function(productId, fields, variants) { - var queryParameters = (fields ? {fields: fields} : {}); - var path = pathProductBase + '/' + productId; - if (variants) { - path += '/variants'; - } + this.getProduct = function (productId, fields, variants) { + var queryParameters = (fields ? { fields: fields } : {}); + var path = pathProductBase + '/' + productId; + if (variants) { + path += '/variants'; + } return this.requestHelper.get(path, queryParameters); }; function checkParameters(queryParameters) { var qp = {}; qp.q = queryParameters.q; - + if (qp.sort) { qp.sort = queryParameters.sort; } @@ -30,12 +30,12 @@ var Product = function(rh) { if (qp.effectiveDate) { qp.effectiveDate = queryParameters.effectiveDate; } - + return qp; } - this.getProducts = function(queryParameters) { - + this.getProducts = function (queryParameters) { + var qp = checkParameters(queryParameters); var q = []; @@ -52,9 +52,23 @@ var Product = function(rh) { return this.requestHelper.get(pathProductBase, qp); }; - this.updateProduct = function(product) { + this.updateProduct = function (product) { return this.requestHelper.put(pathProductBase + '/' + product.id, 'application/json', product); - }; + }; + + this.createProduct = function (product) { + return this.requestHelper.post(pathProductBase, 'application/json', product); + }; + + this.createMediaForProduct = function (productId, mediaMetadata) { + return this.requestHelper.post(pathProductBase + '/' + productId + '/media', + 'application/json', mediaMetadata); + } + + this.commit = function (productId, mediaId) { + return this.requestHelper.post(pathProductBase + '/' + productId + '/media/' + mediaId + '/commit'); + } + }; module.exports = Product;
added createProduct, createMediaForProduct and commit (for media)
SAP_yaas-nodejs-client-sdk
train
1e09432c45054d0bef7a0fd4d2158d4e14f8f657
diff --git a/examples/background_task.py b/examples/background_task.py index <HASH>..<HASH> 100644 --- a/examples/background_task.py +++ b/examples/background_task.py @@ -15,7 +15,7 @@ class MyClient(discord.Client): print('------') async def my_background_task(self): - await self.wait_until_ready() + await self.wait_for('ready') counter = 0 channel = self.get_channel(1234567) # channel ID goes here while not self.is_closed: diff --git a/examples/guessing_game.py b/examples/guessing_game.py index <HASH>..<HASH> 100644 --- a/examples/guessing_game.py +++ b/examples/guessing_game.py @@ -1,5 +1,6 @@ import discord import random +import asyncio class MyClient(discord.Client): async def on_ready(self): @@ -15,13 +16,16 @@ class MyClient(discord.Client): if message.content.startswith('$guess'): await message.channel.send('Guess a number between 1 and 10.') - check = lambda m: m.content.isdigit() - guess = await self.wait_for_message(author=message.author, check=check, timeout=5.0) + + def is_correct(m): + return m.author == message.author and m.content.isdigit() answer = random.randint(1, 10) - if guess is not None: - await message.channel.send('Sorry, you took too long it was {}.'.format(answer)) - return + + try: + guess = await self.wait_for('message', check=is_correct, timeout=5.0) + except asyncio.TimeoutError: + return await message.channel.send('Sorry, you took too long it was {}.'.format(answer)) if int(guess.content) == answer: await message.channel.send('You are right!')
Update examples to use the new generic wait_for.
Rapptz_discord.py
train
ce24d28ba307bd8382b905d12a6cb2e28d24f47b
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ "require-dev": { "phpunit/phpunit": "^9.0", "squizlabs/php_codesniffer": "^3.0", - "estahn/phpunit-json-assertions": "^3" + "justinrainbow/json-schema": "^5.2" }, "suggest": { "ext-curl": "*" diff --git a/tests/RaygunClientTest.php b/tests/RaygunClientTest.php index <HASH>..<HASH> 100644 --- a/tests/RaygunClientTest.php +++ b/tests/RaygunClientTest.php @@ -2,6 +2,7 @@ namespace Raygun4php\Tests; +use JsonSchema\Validator; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Raygun4php\RaygunClient; @@ -9,12 +10,9 @@ use Raygun4php\RaygunMessage; use Raygun4php\RaygunRequestMessage; use Raygun4php\Interfaces\TransportInterface; use Raygun4php\Tests\Stubs\TransportGetMessageStub; -use EnricoStahn\JsonAssert\Assert as JsonAssert; class RaygunClientTest extends TestCase { - use JsonAssert; - /** * @var RaygunClient */ @@ -205,6 +203,10 @@ class RaygunClientTest extends TestCase $client->SendException(new \Exception('test')); $raygunMessage = $transportStub->getMessage(); - $this->assertJsonMatchesSchemaString($this->jsonSchema, json_decode($raygunMessage->toJson())); + $data = json_decode($raygunMessage->toJson()); + + $schemaValidator = new Validator(); + $schemaValidator->validate($data, $this->jsonSchema); + $this->assertTrue($schemaValidator->isValid()); } } diff --git a/tests/RaygunMessageTest.php b/tests/RaygunMessageTest.php index <HASH>..<HASH> 100644 --- a/tests/RaygunMessageTest.php +++ b/tests/RaygunMessageTest.php @@ -3,14 +3,12 @@ namespace Raygun4php\Tests; use Exception; +use JsonSchema\Validator; use PHPUnit\Framework\TestCase; use Raygun4php\RaygunMessage; -use EnricoStahn\JsonAssert\Assert as JsonAssert; class RaygunMessageTest extends TestCase { - use JsonAssert; - /** * json schema used to validate message json. * @@ -65,6 +63,10 @@ class RaygunMessageTest extends TestCase $msg->build(new Exception('Test')); $msgJson = $msg->toJson(); - $this->assertJsonMatchesSchemaString($this->jsonSchema, json_decode($msgJson)); + $data = json_decode($msgJson); + + $schemaValidator = new Validator(); + $schemaValidator->validate($data, $this->jsonSchema); + $this->assertTrue($schemaValidator->isValid()); } }
Replace estahn/phpunit-json-assertions with justinrainbow/json-schema for test assertions
MindscapeHQ_raygun4php
train
68b3ec60828eb7c8d54fb6361b026ce778ef0a8d
diff --git a/migrations/m161109_112016_rename_user_table.php b/migrations/m161109_112016_rename_user_table.php index <HASH>..<HASH> 100644 --- a/migrations/m161109_112016_rename_user_table.php +++ b/migrations/m161109_112016_rename_user_table.php @@ -6,22 +6,15 @@ class m161109_112016_rename_user_table extends Migration { public function up() { - $this->renameTable('{{%User}}', '{{%user}}'); + if (Yii::$app->db->schema->getTableSchema('user') === null) { + $this->renameTable('{{%User}}', '{{%user}}'); + } } public function down() { - $this->renameTable('{{%user}}', '{{%User}}'); + if (Yii::$app->db->schema->getTableSchema('User') === null) { + $this->renameTable('{{%user}}', '{{%User}}'); + } } - - /* - // Use safeUp/safeDown to run migration code within a transaction - public function safeUp() - { - } - - public function safeDown() - { - } - */ -} +} \ No newline at end of file
fix issue 'table already exists' for windows
yii2mod_yii2-user
train
e573f422ffea53131f3ff09a1f0a735dae1e24dc
diff --git a/test/adapters/active_record_test.rb b/test/adapters/active_record_test.rb index <HASH>..<HASH> 100644 --- a/test/adapters/active_record_test.rb +++ b/test/adapters/active_record_test.rb @@ -42,4 +42,24 @@ class ActiveRecordTest < MiniTest::Test ActiveRecord::Base.connection.execute("DROP table IF EXISTS `flipper_features`") ActiveRecord::Base.connection.execute("DROP table IF EXISTS `flipper_gates`") end + + def test_models_honor_table_name_prefixes_and_suffixes + ActiveRecord::Base.table_name_prefix = :foo_ + ActiveRecord::Base.table_name_suffix = :_bar + + Flipper::Adapters::ActiveRecord.send(:remove_const, :Feature) + Flipper::Adapters::ActiveRecord.send(:remove_const, :Gate) + load("flipper/adapters/active_record.rb") + + assert_equal "foo_flipper_features_bar", Flipper::Adapters::ActiveRecord::Feature.table_name + assert_equal "foo_flipper_gates_bar", Flipper::Adapters::ActiveRecord::Gate.table_name + + ensure + ActiveRecord::Base.table_name_prefix = "" + ActiveRecord::Base.table_name_suffix = "" + + Flipper::Adapters::ActiveRecord.send(:remove_const, :Feature) + Flipper::Adapters::ActiveRecord.send(:remove_const, :Gate) + load("flipper/adapters/active_record.rb") + end end
add a test to make sure the table name prefix and suffix are honored
jnunemaker_flipper
train
e600b532b5a8eddf36b2d5464c327aea09862dab
diff --git a/src/main/java/io/reactivex/rxjava3/exceptions/CompositeException.java b/src/main/java/io/reactivex/rxjava3/exceptions/CompositeException.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/reactivex/rxjava3/exceptions/CompositeException.java +++ b/src/main/java/io/reactivex/rxjava3/exceptions/CompositeException.java @@ -199,40 +199,41 @@ public final class CompositeException extends RuntimeException { * Special handling for printing out a {@code CompositeException}. * Loops through all inner exceptions and prints them out. * - * @param s + * @param output * stream to print to */ - private void printStackTrace(PrintStreamOrWriter s) { - StringBuilder b = new StringBuilder(128); - b.append(this).append('\n'); + private void printStackTrace(PrintStreamOrWriter output) { + output.append(this).append("\n"); for (StackTraceElement myStackElement : getStackTrace()) { - b.append("\tat ").append(myStackElement).append('\n'); + output.append("\tat ").append(myStackElement).append("\n"); } int i = 1; for (Throwable ex : exceptions) { - b.append(" ComposedException ").append(i).append(" :\n"); - appendStackTrace(b, ex, "\t"); + output.append(" ComposedException ").append(i).append(" :\n"); + appendStackTrace(output, ex, "\t"); i++; } - s.println(b.toString()); + output.append("\n"); } - private void appendStackTrace(StringBuilder b, Throwable ex, String prefix) { - b.append(prefix).append(ex).append('\n'); + private void appendStackTrace(PrintStreamOrWriter output, Throwable ex, String prefix) { + output.append(prefix).append(ex).append('\n'); for (StackTraceElement stackElement : ex.getStackTrace()) { - b.append("\t\tat ").append(stackElement).append('\n'); + output.append("\t\tat ").append(stackElement).append('\n'); } if (ex.getCause() != null) { - b.append("\tCaused by: "); - appendStackTrace(b, ex.getCause(), ""); + output.append("\tCaused by: "); + appendStackTrace(output, ex.getCause(), ""); } } abstract static class PrintStreamOrWriter { - /** Prints the specified string as a line on this StreamOrWriter. - * @param o string to print + /** + * Prints the object's string representation via the underlying PrintStream or PrintWriter. + * @param o the object to print + * @return this */ - abstract void println(Object o); + abstract PrintStreamOrWriter append(Object o); } /** @@ -246,11 +247,15 @@ public final class CompositeException extends RuntimeException { } @Override - void println(Object o) { - printStream.println(o); + WrappedPrintStream append(Object o) { + printStream.print(o); + return this; } } + /** + * Same abstraction and implementation as in JDK to allow PrintStream and PrintWriter to share implementation. + */ static final class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; @@ -259,8 +264,9 @@ public final class CompositeException extends RuntimeException { } @Override - void println(Object o) { - printWriter.println(o); + WrappedPrintWriter append(Object o) { + printWriter.print(o); + return this; } }
3.x: CompositeException.printStackTrace to write directly into PS/PW (#<I>)
ReactiveX_RxJava
train
9dc0e86f2a51f96facb242631ae93c962ae0dfdd
diff --git a/lib/lwm2m-common.js b/lib/lwm2m-common.js index <HASH>..<HASH> 100644 --- a/lib/lwm2m-common.js +++ b/lib/lwm2m-common.js @@ -1685,7 +1685,6 @@ export class LwM2MObjectStore { if (!backup) { return Promise.resolve(); } - clearTimeout(backup.cleaner); delete this.backupObjects[objectId]; return this.delete(`^/${objectId}/.*$`).catch((err) => {
Strip the cleaner property as backup objects should be retained while the current flow is alive
CANDY-LINE_node-red-contrib-lwm2m
train
55c0084007fd51e4a5157b50ab65a10cf9f700ae
diff --git a/safe/gui/widgets/dock.py b/safe/gui/widgets/dock.py index <HASH>..<HASH> 100644 --- a/safe/gui/widgets/dock.py +++ b/safe/gui/widgets/dock.py @@ -741,7 +741,8 @@ class Dock(QtGui.QDockWidget, FORM_CLASS): self.active_impact_function = functions self.impact_function_parameters = None if hasattr(self.active_impact_function, 'parameters'): - self.impact_function_parameters = self.active_impact_function.parameters + self.impact_function_parameters = \ + self.active_impact_function.parameters self.set_function_options_status() else: self.impact_function_parameters = None @@ -973,8 +974,7 @@ class Dock(QtGui.QDockWidget, FORM_CLASS): self.draw_rubber_bands() def get_functions(self): - """Obtain a list of impact functions from the impact calculator. - """ + """Obtain a list of impact functions from the IF manager.""" # remember what the current function is original_function = self.cboFunction.currentText() self.cboFunction.clear() @@ -1011,13 +1011,15 @@ class Dock(QtGui.QDockWidget, FORM_CLASS): # Find out which functions can be used with these layers try: - functions = self.impact_function_manager.filter_by_keywords( + impact_functions = self.impact_function_manager.filter_by_keywords( hazard_keywords, exposure_keywords) # Populate the hazard combo with the available functions - for function in functions: - function_name = function.__name__ + for impact_function in impact_functions: + function_id = self.impact_function_manager.get_function_id( + impact_function) function_title = \ - self.impact_function_manager.get_function_title(function) + self.impact_function_manager.get_function_title( + impact_function) # Provide function title and ID to function combo: # function_title is the text displayed in the combo @@ -1025,7 +1027,7 @@ class Dock(QtGui.QDockWidget, FORM_CLASS): add_ordered_combo_item( self.cboFunction, function_title, - data=function_name) + data=function_id) except Exception, e: raise e diff --git a/safe/impact_functions/core.py b/safe/impact_functions/core.py index <HASH>..<HASH> 100644 --- a/safe/impact_functions/core.py +++ b/safe/impact_functions/core.py @@ -9,10 +9,8 @@ using it. import logging from math import ceil -import numpy from collections import OrderedDict -from safe.gis.polygon import inside_polygon from safe.utilities.i18n import tr from safe.defaults import default_minimum_needs from safe.impact_functions.impact_function_manager import ImpactFunctionManager diff --git a/safe/impact_functions/impact_function_manager.py b/safe/impact_functions/impact_function_manager.py index <HASH>..<HASH> 100644 --- a/safe/impact_functions/impact_function_manager.py +++ b/safe/impact_functions/impact_function_manager.py @@ -114,6 +114,18 @@ class ImpactFunctionManager(object): return self.registry.filter_by_metadata(metadata_key, metadata_value) @staticmethod + def get_function_id(impact_function): + """Get the ID of the impact function. + + :param impact_function: Class of an impact function + :type impact_function: safe.impact_functions.base.ImpactFunction + + :returns: The ID of the impact function specified in its metadata. + :rtype: str + """ + return impact_function.metadata().as_dict().get('id', None) + + @staticmethod def get_function_title(impact_function): """Get title of the impact function. @@ -136,10 +148,9 @@ class ImpactFunctionManager(object): @staticmethod def get_function_type(impact_function): - """Return the impact function type uses to differentiate which type of - layers would be passed to the impact functions + """Return the impact function type. - :param impact_function: An instance of the impact function + :param impact_function: The impact function. :type impact_function: safe.impact_functions.base.ImpactFunction """ return impact_function.function_type() diff --git a/safe/impact_functions/registry.py b/safe/impact_functions/registry.py index <HASH>..<HASH> 100644 --- a/safe/impact_functions/registry.py +++ b/safe/impact_functions/registry.py @@ -73,7 +73,7 @@ class Registry(object): @classmethod def get(cls, name): - """Return an instance of an impact function given its class name. + """Return an instance of impact function given its class name. :param name: the name of IF class :type name: str @@ -87,7 +87,7 @@ class Registry(object): def get_class(cls, name): """Return the class of an impact function given its class name. - :param name: the name of IF class + :param name: The class name of the IF. :type name: str :return: impact function class diff --git a/safe/utilities/impact_calculator.py b/safe/utilities/impact_calculator.py index <HASH>..<HASH> 100644 --- a/safe/utilities/impact_calculator.py +++ b/safe/utilities/impact_calculator.py @@ -72,9 +72,8 @@ class ImpactCalculator(QObject): :raises: InsufficientParametersError if self._function is not set, InvalidParameterError if style of self._function is not in ('old-style', 'qgis2.0') - Any exceptions raised by other libraries will be propogated. + Any exceptions raised by other libraries will be propagated. """ - if self._function_id is None or self._function_id == '': message = self.tr('Error: Impact Function not set.') raise InsufficientParametersError(message) diff --git a/safe/utilities/utilities.py b/safe/utilities/utilities.py index <HASH>..<HASH> 100644 --- a/safe/utilities/utilities.py +++ b/safe/utilities/utilities.py @@ -40,7 +40,6 @@ from safe.messaging import styles, Message from safe.messaging.error_message import ErrorMessage from safe.utilities.unicode import get_unicode from safe.utilities.i18n import tr -from safe.impact_functions.impact_function_manager import ImpactFunctionManager INFO_STYLE = styles.INFO_STYLE
Use ID of the IF instead of its class name to register it on the combo in the dock.
inasafe_inasafe
train
794b5de749fceea906222917e90bbc19e131ecc3
diff --git a/archive/changes_test.go b/archive/changes_test.go index <HASH>..<HASH> 100644 --- a/archive/changes_test.go +++ b/archive/changes_test.go @@ -138,7 +138,7 @@ func mutateSampleDir(t *testing.T, root string) { } // Rewrite a file - if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileN\n"), 0777); err != nil { + if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777); err != nil { t.Fatal(err) } @@ -146,12 +146,12 @@ func mutateSampleDir(t *testing.T, root string) { if err := os.RemoveAll(path.Join(root, "file3")); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileM\n"), 0404); err != nil { + if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404); err != nil { t.Fatal(err) } // Touch file - if err := os.Chtimes(path.Join(root, "file4"), time.Now(), time.Now()); err != nil { + if err := os.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } @@ -195,7 +195,7 @@ func mutateSampleDir(t *testing.T, root string) { } // Touch dir - if err := os.Chtimes(path.Join(root, "dir3"), time.Now(), time.Now()); err != nil { + if err := os.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } }
Don't assume the file system has sub-second precision timestamp For example, FreeBSD doesn't have that (see <URL>
containers_storage
train
4daae9a8c7009017184d4d7646d8206aee86522b
diff --git a/h2o-admissibleml/src/main/java/hex/Infogram/Infogram.java b/h2o-admissibleml/src/main/java/hex/Infogram/Infogram.java index <HASH>..<HASH> 100644 --- a/h2o-admissibleml/src/main/java/hex/Infogram/Infogram.java +++ b/h2o-admissibleml/src/main/java/hex/Infogram/Infogram.java @@ -307,8 +307,8 @@ public class Infogram extends ModelBuilder<hex.Infogram.InfogramModel, hex.Infog try { boolean validPresent = _parms.valid() != null; prepareModelTrainingFrame(); // generate training frame with predictors and sensitive features (if specified) - _model = new hex.Infogram.InfogramModel(dest(), _parms, new hex.Infogram.InfogramModel.InfogramModelOutput(Infogram.this)); - _model.delete_and_lock(_job); + InfogramModel model = new hex.Infogram.InfogramModel(dest(), _parms, new hex.Infogram.InfogramModel.InfogramModelOutput(Infogram.this)); + _model = model.delete_and_lock(_job); _model._output._start_time = System.currentTimeMillis(); _cmiRaw = new double[_numModels]; if (_parms.valid() != null) @@ -349,10 +349,11 @@ public class Infogram extends ModelBuilder<hex.Infogram.InfogramModel, hex.Infog keepFrameKeys(keep, _cmiRelKeyValid); if (_cmiRelKeyCV != null) keepFrameKeys(keep, _cmiRelKeyCV); + // final model update + _model.update(_job._key); + _model.unlock(_job); } Scope.exit(keep.toArray(new Key[keep.size()])); - _model.update(_job._key); - _model.unlock(_job); } }
Fix model locking/update in Infogram _model should be set by delete_and_lock, only then we know it is in DKV, we need to make sure _model is not null otherwise we can suppress an error exception.
h2oai_h2o-3
train
c8f62ea4b6193a175add12e1795c18dad500c38e
diff --git a/sos/plugins/ceph.py b/sos/plugins/ceph.py index <HASH>..<HASH> 100644 --- a/sos/plugins/ceph.py +++ b/sos/plugins/ceph.py @@ -59,11 +59,12 @@ class Ceph(Plugin, RedHatPlugin, UbuntuPlugin): "ceph report" ]) - self.add_forbidden_path("/etc/ceph/*keyring") - self.add_forbidden_path("/var/lib/ceph/*keyring") - self.add_forbidden_path("/var/lib/ceph/*/*keyring") - self.add_forbidden_path("/var/lib/ceph/*/*/*keyring") + self.add_forbidden_path("/etc/ceph/*keyring*") + self.add_forbidden_path("/var/lib/ceph/*keyring*") + self.add_forbidden_path("/var/lib/ceph/*/*keyring*") + self.add_forbidden_path("/var/lib/ceph/*/*/*keyring*") self.add_forbidden_path("/var/lib/ceph/osd/*") self.add_forbidden_path("/var/lib/ceph/osd/mon/*") + self.add_forbidden_path("/etc/ceph/*bindpass*") # vim: set et ts=4 sw=4 :
[ceph] skip collecting of all keyring and bindpass files Do not collect any keyring files - expand the add_forbidden_path regular expressions accordingly to cover there filenames like: /var/lib/ceph/tmp/keyring.mon.magna<I> Do not either collect any /etc/ceph/*bindpass* that can store LDAP bind passwords. Resolves: #<I>
sosreport_sos
train
635dd984ab74bdaf54064a2effd5c59ea46d04fc
diff --git a/censys/search/v2/api.py b/censys/search/v2/api.py index <HASH>..<HASH> 100644 --- a/censys/search/v2/api.py +++ b/censys/search/v2/api.py @@ -148,13 +148,12 @@ class CensysSearchAPIv2(CensysAPIBase): if self.page > self.pages: raise StopIteration - args = { - "q": self.query, - "per_page": per_page or self.per_page or 100, - "cursor": self.nextCursor or self.cursor, + payload = self.api.raw_search( + query=self.query, + per_page=per_page or self.per_page or 100, + cursor=self.nextCursor or self.cursor, **self.extra_args, - } - payload = self.api._get(self.api.search_path, args) + ) self.page += 1 result = payload["result"] self.nextCursor = result["links"]["next"] @@ -194,10 +193,12 @@ class CensysSearchAPIv2(CensysAPIBase): document_key = INDEX_TO_KEY.get(self.api.INDEX_NAME, "ip") with ThreadPoolExecutor(max_workers) as executor: - threads = { - executor.submit(self.api.view, hit[document_key]): hit[document_key] - for hit in self.__call__() - } + threads = {} + for hit in self.__call__(): + hit_key = hit[document_key] + if "name" in hit: + hit_key += "+" + hit["name"] + threads[executor.submit(self.api.view, hit_key)] = hit_key for task in as_completed(threads): document_id = threads[task] @@ -233,6 +234,35 @@ class CensysSearchAPIv2(CensysAPIBase): """ return self.Query(self, query, per_page, cursor, pages, **kwargs) + def raw_search( + self, + query: str, + per_page: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs: Any, + ) -> dict: + """Search current index. + + Searches the given index for all records that match the given query. + This method does no automatic pagination or post processing. + + Args: + query (str): The query to be executed. + per_page (int): Optional; The number of results to be returned for each page. Defaults to 100. + cursor (int): Optional; The cursor of the desired result set. + **kwargs (Any): Optional; Additional arguments to be passed to the query. + + Returns: + dict: The raw result set. + """ + args = { + "q": query, + "per_page": per_page or 100, + "cursor": cursor, + **kwargs, + } + return self._get(self.search_path, args) + def view( self, document_id: str, diff --git a/tests/search/v2/test_hosts.py b/tests/search/v2/test_hosts.py index <HASH>..<HASH> 100644 --- a/tests/search/v2/test_hosts.py +++ b/tests/search/v2/test_hosts.py @@ -413,6 +413,39 @@ class TestHosts(CensysTestCase): results = query.view_all() assert results == expected + def test_search_view_all_virtual_hosts(self): + test_per_page = 50 + search_json = SEARCH_HOSTS_JSON.copy() + hits = [{"ip": "1.1.1.1", "name": "one.one.one.one"}, {"ip": "1.0.0.1"}] + search_json["result"]["hits"] = hits + search_json["result"]["total"] = len(hits) + search_json["result"]["links"]["next"] = "" + self.responses.add( + responses.GET, + f"{V2_URL}/hosts/search?q=service.service_name: HTTP&per_page={test_per_page}", + status=200, + json=search_json, + ) + + expected = {} + for hit in hits: + view_json = VIEW_HOST_JSON.copy() + view_json["result"]["ip"] = hit["ip"] + document_key = hit["ip"] + if "name" in hit: + document_key += "+" + hit["name"] + self.responses.add( + responses.GET, + f"{V2_URL}/hosts/{document_key}", + status=200, + json=view_json, + ) + expected[document_key] = view_json["result"].copy() + + query = self.api.search("service.service_name: HTTP", per_page=test_per_page) + results = query.view_all() + assert results == expected + def test_search_view_all_error(self): test_per_page = 50 ips = ["1.1.1.1", "1.1.1.2", "1.1.1.3"]
chore(api): Allow view_all with virtual hosts
censys_censys-python
train
d9e290863611a8247cee2f656c1dea8f8e966524
diff --git a/user/index.php b/user/index.php index <HASH>..<HASH> 100644 --- a/user/index.php +++ b/user/index.php @@ -489,9 +489,9 @@ } echo $OUTPUT->heading($heading, 3); } else { - if ($course->id != SITEID && has_capability('moodle/role:assign', $context)) { - $editlink = ' <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id.'">'; - $editlink .= '<img src="'.$OUTPUT->pix_url('i/edit') . '" class="icon" alt="" /></a>'; + if ($course->id != SITEID && has_capability('moodle/course:enrolreview', $context)) { + $editlink = $OUTPUT->action_icon(new moodle_url('/enrol/users.php', array('id' => $course->id)), + new pix_icon('i/edit', get_string('edit'))); } else { $editlink = ''; }
NOMDL edit icon at the course participants page now links to the enrolments page instead of role assignment page Also note the controlling capability has changed to the one used at the linked page.
moodle_moodle
train
c9574fa0290e2ecf1cc82c2e37ed49a523d378b5
diff --git a/src/projects/UnitConvertion/files.test.js b/src/projects/UnitConvertion/files.test.js index <HASH>..<HASH> 100644 --- a/src/projects/UnitConvertion/files.test.js +++ b/src/projects/UnitConvertion/files.test.js @@ -1,7 +1,12 @@ const files= require('./files.js'); + const measurementUnits = files.measurementUnits; const measurementSystems = files.measurementSystems; +const generatedMeasurementUnits = files.generatedMeasurementUnits; +const generatedMeasurementSystem =files.generatedMeasurementSystem; + + /* global test, describe, it, expect, jest */ describe('empty test', () => { @@ -19,5 +24,23 @@ describe('testing objects are not empty', () => { } objectIsNotEmpty(measurementUnits) objectIsNotEmpty(measurementSystems) +objectIsNotEmpty(generatedMeasurementUnits) +objectIsNotEmpty(generatedMeasurementSystem) + +}) + + +describe('testing object returns array',()=> { + const isArray=(object) => { + it('object' + object, () =>{ + var result = object + expect(Array.isArray(result)).toBe(true) + }) + } +isArray(measurementUnits) +isArray(measurementSystems) +isArray(generatedMeasurementUnits) +isArray(generatedMeasurementSystem) }) +
Update files.test.js updated with two other generated objects and added test to check isArray
GroceriStar_groceristar-fetch
train
a452b5d192c6e7ae17a019b9d8a19c83a0da6dd4
diff --git a/src/js/server/schemaMiddleware.js b/src/js/server/schemaMiddleware.js index <HASH>..<HASH> 100644 --- a/src/js/server/schemaMiddleware.js +++ b/src/js/server/schemaMiddleware.js @@ -2,6 +2,21 @@ // `options.schemaKey`. You are required to set `options.schemaDir` to a directory that contains a file matching that // key. // +// Any validation errors are transformed using `options.rules.validationErrorsToResponse` before they are sent to the +// user. The default format looks roughly like: +// +// { +// ok: false, +// message: "The JSON you have provided is not valid.", +// errors: { +// field1: ["This field is required."] +// } +// } +// +// The output of this middleware is itself expected to be valid according to a JSON schema, and to be delivered +// using a `schemaHandler`. You are expected to supply `options.responseSchemaKey` and `options.responseSchemaUrl`, +// which will be distributed to the `schemaHandler` instance. +// "use strict"; var fluid = fluid || require("infusion"); var gpii = fluid.registerNamespace("gpii"); @@ -9,7 +24,7 @@ var gpii = fluid.registerNamespace("gpii"); require("./schemaHandler"); fluid.defaults("gpii.schema.middleware.handler", { - gradeNames: ["gpii.express.handler"], + gradeNames: ["gpii.schema.handler"], invokers: { handleRequest: { func: "{that}.sendResponse", @@ -24,8 +39,10 @@ gpii.schema.middleware.rejectOrForward = function (that, req, res, next) { if (that.options.schemaDir && that.options.schemaKey) { var results = that.validator.validate(that.options.schemaKey, req.body); if (results) { + var transformedResults = fluid.model.transformWithRules(results, that.options.rules.validationErrorsToResponse); + // Instantiate a handler that will take care of the rest of the request. - that.events.onInvalidRequest.fire(req, res, 400, results); + that.events.onInvalidRequest.fire(req, res, 400, transformedResults); } else { next(); @@ -41,6 +58,32 @@ gpii.schema.middleware.rejectOrForward = function (that, req, res, next) { fluid.defaults("gpii.schema.middleware", { gradeNames: ["gpii.express.middleware"], + responseSchemaKey: "message.json", + responseSchemaUrl: "http://terms.raisingthefloor.org/schema/message.json", + distributeOptions: [ + { + source: "{that}.options.responseSchemaKey", + target: "{that gpii.express.schemaHandler}.options.schemaKey" + }, + { + source: "{that}.options.responseSchemaUrl", + target: "{that gpii.express.schemaHandler}.options.schemaUrl" + } + ], + messages: { + error: "The JSON you have provided is not valid." + }, + rules: { + validationErrorsToResponse: { + "": "", + "ok": { + literalValue: false + }, + "message": { + literalValue: "{that}.options.messages.error" + } + } + }, components: { validator: { type: "gpii.schema.validator.server",
GPII-<I>: JSON Schema middleware output should itself be valid and should include information about the JSON schema it uses.
GPII_gpii-json-schema
train
87963f9db241e00215df24fcaa522b0685a2b53b
diff --git a/vault/core.go b/vault/core.go index <HASH>..<HASH> 100644 --- a/vault/core.go +++ b/vault/core.go @@ -995,7 +995,7 @@ func (c *Core) RekeyInit(config *SealConfig) error { // Prevent multiple concurrent re-keys if c.rekeyConfig != nil { - return fmt.Errorf("Rekey already in progress") + return fmt.Errorf("rekey already in progress") } // Copy the configuration @@ -1037,6 +1037,11 @@ func (c *Core) RekeyUpdate(key []byte) (*RekeyResult, error) { c.rekeyLock.Lock() defer c.rekeyLock.Unlock() + // Ensure a rekey is in progress + if c.rekeyConfig == nil { + return nil, fmt.Errorf("no rekey in progress") + } + // Check if we already have this piece for _, existing := range c.rekeyProgress { if bytes.Equal(existing, key) { @@ -1106,6 +1111,7 @@ func (c *Core) RekeyUpdate(key []byte) (*RekeyResult, error) { c.logger.Printf("[ERR] core: failed to rekey barrier: %v", err) return nil, fmt.Errorf("failed to rekey barrier: %v", err) } + c.logger.Printf("[INFO] core: security barrier rekeyed") // Store the seal configuration pe := &physical.Entry{ @@ -1185,6 +1191,11 @@ func (c *Core) postUnseal() error { func (c *Core) preSeal() error { defer metrics.MeasureSince([]string{"core", "pre_seal"}, time.Now()) c.logger.Printf("[INFO] core: pre-seal teardown starting") + + // Clear any rekey progress + c.rekeyConfig = nil + c.rekeyProgress = nil + if c.metricsCh != nil { close(c.metricsCh) c.metricsCh = nil diff --git a/vault/core_test.go b/vault/core_test.go index <HASH>..<HASH> 100644 --- a/vault/core_test.go +++ b/vault/core_test.go @@ -1513,7 +1513,12 @@ func TestCore_HandleRequest_MountPoint(t *testing.T) { } func TestCore_Rekey_Lifecycle(t *testing.T) { - c, _, _ := TestCoreUnsealed(t) + c, master, _ := TestCoreUnsealed(t) + + // Verify update not allowed + if _, err := c.RekeyUpdate(master); err == nil { + t.Fatalf("no rekey in progress") + } // Should be no progress num, err := c.RekeyProgress()
vault: minor rekey cleanups
hashicorp_vault
train
319b83e2464e1815e1a1fa9f06b169f9efabc011
diff --git a/Rakefile b/Rakefile index <HASH>..<HASH> 100644 --- a/Rakefile +++ b/Rakefile @@ -47,6 +47,7 @@ spec = Gem::Specification.new do |s| # relevant versions s.add_dependency("rack") s.add_dependency("sinatra") + s.add_dependency("thin") s.add_dependency("json") s.add_dependency("plist") diff --git a/lib/mimic.rb b/lib/mimic.rb index <HASH>..<HASH> 100644 --- a/lib/mimic.rb +++ b/lib/mimic.rb @@ -59,7 +59,7 @@ module Mimic end def start_service(app, options) - Rack::Handler::WEBrick.run(app.url_map, { + Rack::Handler::Thin.run(app.url_map, { :Port => options[:port], :Logger => logger, :AccessLog => logger, diff --git a/spec/fake_host_spec.rb b/spec/fake_host_spec.rb index <HASH>..<HASH> 100644 --- a/spec/fake_host_spec.rb +++ b/spec/fake_host_spec.rb @@ -76,7 +76,7 @@ describe "Mimic::FakeHost" do describe "StubbedRequest" do it "has a unique hash based on it's parameters" do host = Mimic::FakeHost::StubbedRequest.new(stub, "GET", "/path") - host.to_hash.should == Digest::MD5.digest("GET /path") + host.to_hash.should == Digest::MD5.hexdigest("GET /path") end it "has the same hash as an equivalent request" do
Switch to Thin from Webrick as it seems to play more nicely with Daemons.
lukeredpath_mimic
train
2576333b823a739dea5de0116cada7e877eeae17
diff --git a/aerogear-android-store-test/src/org/jboss/aerogear/android/impl/datamanager/EncryptedSQLStoreTest.java b/aerogear-android-store-test/src/org/jboss/aerogear/android/impl/datamanager/EncryptedSQLStoreTest.java index <HASH>..<HASH> 100644 --- a/aerogear-android-store-test/src/org/jboss/aerogear/android/impl/datamanager/EncryptedSQLStoreTest.java +++ b/aerogear-android-store-test/src/org/jboss/aerogear/android/impl/datamanager/EncryptedSQLStoreTest.java @@ -118,60 +118,60 @@ public class EncryptedSQLStoreTest extends PatchedActivityInstrumentationTestCas } -// public void testReadAll() { -// for (int i = 1; i <= 10; i++) { -// Data data = new Data(i, "name " + i, "description " + i); -// store.save(data); -// } -// -// assertEquals("Store should have 10 elements", 10, store.readAll().size()); -// } -// -// public void testRead() { -// Data data = new Data(10, "name", "description"); -// store.save(data); -// -// Data readData = store.read(10); -// assertEquals(data, readData); -// assertTrue("Store can not be empty", !store.isEmpty()); -// } -// -// public void testSave() { -// Data data = new Data(10, "name", "description"); -// store.save(data); -// -// assertFalse("Store can not be empty", store.isEmpty()); -// assertEquals("Store should have 1 elements", 1, store.readAll().size()); -// } -// -// public void testReset() { -// Data data = new Data(10, "name", "description"); -// store.save(data); -// store.reset(); -// -// assertTrue("Store can empty", !store.isEmpty()); -// } -// -// public void testRemove() { -// for (int i = 1; i <= 10; i++) { -// Data data = new Data(i, "name " + i, "description " + i); -// store.save(data); -// } -// -// store.remove(1); -// -// assertEquals("Store should have 9 elements", 9, store.readAll().size()); -// } -// -// public void testIsEmpty() { -// assertTrue("Store can empty", store.isEmpty()); -// } -// -// public void testIsNotEmpty() { -// Data data = new Data(10, "name", "description"); -// store.save(data); -// -// assertFalse("Store can not be empty", store.isEmpty()); -// } + public void testReadAll() { + for (int i = 1; i <= 10; i++) { + Data data = new Data(i, "name " + i, "description " + i); + store.save(data); + } + + assertEquals("Store should have 10 elements", 10, store.readAll().size()); + } + + public void testRead() { + Data data = new Data(10, "name", "description"); + store.save(data); + + Data readData = store.read(10); + assertEquals(data, readData); + assertTrue("Store can not be empty", !store.isEmpty()); + } + + public void testSave() { + Data data = new Data(10, "name", "description"); + store.save(data); + + assertFalse("Store can not be empty", store.isEmpty()); + assertEquals("Store should have 1 elements", 1, store.readAll().size()); + } + + public void testReset() { + Data data = new Data(10, "name", "description"); + store.save(data); + store.reset(); + + assertTrue("Store can empty", store.isEmpty()); + } + + public void testRemove() { + for (int i = 1; i <= 10; i++) { + Data data = new Data(i, "name " + i, "description " + i); + store.save(data); + } + + store.remove(1); + + assertEquals("Store should have 9 elements", 9, store.readAll().size()); + } + + public void testIsEmpty() { + assertTrue("Store can empty", store.isEmpty()); + } + + public void testIsNotEmpty() { + Data data = new Data(10, "name", "description"); + store.save(data); + + assertFalse("Store can not be empty", store.isEmpty()); + } }
Uncomment Encrypted SQL Store tests
aerogear_aerogear-android-store
train
414d250977f574017b27d87e8bf3783082946f31
diff --git a/errors.js b/errors.js index <HASH>..<HASH> 100644 --- a/errors.js +++ b/errors.js @@ -57,6 +57,12 @@ var ObjectValidationError = function() { }; util.inherits(ObjectValidationError, ValidationError); +var LoaderError = function() { + ValidationError.apply(this, arguments); + this.kind = 'LoaderError'; +}; +util.inherits(ObjectValidationError, ValidationError); + // ****************************************************************** // Exports // ****************************************************************** @@ -66,3 +72,4 @@ exports.NumericValidationError = NumericValidationError; exports.StringValidationError = StringValidationError; exports.ArrayValidationError = ArrayValidationError; exports.ObjectValidationError = ObjectValidationError; +exports.LoaderError = LoaderError; diff --git a/jayschema.js b/jayschema.js index <HASH>..<HASH> 100644 --- a/jayschema.js +++ b/jayschema.js @@ -324,8 +324,19 @@ JaySchema.prototype.validate = function(instance, schema, callback) } else { // traditional, non-callback validation - return this._validateImpl(instance, schema); + var errs = []; + if (this._loader) { + var desc = 'You provided a loader callback, but you are calling ' + + 'validate() synchronously. Your loader will be ignored and ' + + 'validation will fail if any missing $refs are encountered.'; + var err = new Errors.LoaderError(null, null, null, null, null, + desc); + errs.push(err); + } + + errs = errs.concat(this._validateImpl(instance, schema)); + return errs; } };
give the user a hint if they provide a loader but try to validate synchronously
natesilva_jayschema
train
0781bb698f8927b52c7a11a02b39eebaa0c62d68
diff --git a/api.go b/api.go index <HASH>..<HASH> 100644 --- a/api.go +++ b/api.go @@ -343,7 +343,6 @@ func PollEvent() Event { return event } } - panic("unreachable") } // Returns the size of the internal back buffer (which is mostly the same as
Remove panic("unreachable") which flunks `go vet` It really was unreachable code :)
nsf_termbox-go
train
4a6383f01ef7fc9e05ab13da4ebcf7f2308a7c0c
diff --git a/recordlinkage/compare.py b/recordlinkage/compare.py index <HASH>..<HASH> 100644 --- a/recordlinkage/compare.py +++ b/recordlinkage/compare.py @@ -502,29 +502,20 @@ class Frequency(BaseCompareFeature): c = c / len(col) # replace missing values - if pandas.notnull(self.missing_value): - c[col.isnull()] = self.missing_value + c[col.isnull()] = self.missing_value return c - def _compute(self, left_data=None, right_data=None): + def _compute_vectorized(self, *data): result = [] - if isinstance(left_data, tuple): - for col in left_data: + if isinstance(data, tuple): + for col in data: result_i = self._compute_frequency(col) result.append(result_i) else: - result_i = self._compute_frequency(col) - result.append(result_i) - - if isinstance(right_data, tuple): - for col in right_data: - result_i = self._compute_frequency(col) - result.append(result_i) - else: - result_i = self._compute_frequency(col) + result_i = self._compute_frequency(*data) result.append(result_i) return tuple(result) diff --git a/tests/test_compare.py b/tests/test_compare.py index <HASH>..<HASH> 100644 --- a/tests/test_compare.py +++ b/tests/test_compare.py @@ -1235,7 +1235,7 @@ class TestCompareStrings(TestData): pytest.raises(ValueError, comp.compute, ix, A, B) -class TestCompareFreq(TestData): +class TestCompareFreq(object): def test_freq(self): # data @@ -1296,7 +1296,8 @@ class TestCompareFreq(TestData): expected = DataFrame(np.ones((100, )) * 5, index=ix) pdt.assert_frame_equal(result, expected) - def test_freq_nan(self): + @pytest.mark.parametrize('missing_value', [0.0, np.nan, 10.0]) + def test_freq_nan(self, missing_value): # data array_repeated = np.repeat(np.arange(10, dtype=np.float64), 10) @@ -1312,10 +1313,10 @@ class TestCompareFreq(TestData): from recordlinkage.compare import Frequency comp = recordlinkage.Compare() - comp.add(Frequency(left_on='col')) + comp.add(Frequency(left_on='col', missing_value=missing_value)) result = comp.compute(ix, A, B) expected_np = np.ones((100, )) / 10 - expected_np[90:] = 0.0 + expected_np[90:] = missing_value expected = DataFrame(expected_np, index=ix) pdt.assert_frame_equal(result, expected)
Minor fixes and improvements for Frequency features
J535D165_recordlinkage
train
cb61c88478d33d7bc75a24de580f0f89a26585d7
diff --git a/core/src/test/java/org/acegisecurity/providers/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/acegisecurity/providers/jaas/JaasAuthenticationProviderTests.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/org/acegisecurity/providers/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/acegisecurity/providers/jaas/JaasAuthenticationProviderTests.java @@ -17,10 +17,7 @@ package net.sf.acegisecurity.providers.jaas; import junit.framework.TestCase; -import net.sf.acegisecurity.Authentication; -import net.sf.acegisecurity.AuthenticationException; -import net.sf.acegisecurity.GrantedAuthority; -import net.sf.acegisecurity.GrantedAuthorityImpl; +import net.sf.acegisecurity.*; import net.sf.acegisecurity.providers.TestingAuthenticationToken; import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken; @@ -31,9 +28,11 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Arrays; import java.util.List; +import javax.security.auth.login.LoginException; + /** - * DOCUMENT ME! + * Tests for the JaasAuthenticationProvider * * @author Ray Krueger * @version $Id$ @@ -165,6 +164,35 @@ public class JaasAuthenticationProviderTests extends TestCase { assertNull("Failure event was fired", eventCheck.failedEvent); } + public void testLoginExceptionResolver() { + assertNotNull(jaasProvider.getLoginExceptionResolver()); + jaasProvider.setLoginExceptionResolver(new LoginExceptionResolver() { + public AcegiSecurityException resolveException(LoginException e) { + return new LockedException("This is just a test!"); + } + }); + + try { + jaasProvider.authenticate(new UsernamePasswordAuthenticationToken( + "user", "password")); + } catch (LockedException e) {} + catch (Exception e) { + fail("LockedException should have been thrown and caught"); + } + } + + public void testNullDefaultAuthorities() { + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", + "password", null); + + assertTrue(jaasProvider.supports( + UsernamePasswordAuthenticationToken.class)); + + Authentication auth = jaasProvider.authenticate(token); + assertTrue("Only ROLE_TEST should have been returned", + auth.getAuthorities().length == 1); + } + public void testUnsupportedAuthenticationObjectReturnsNull() { assertNull(jaasProvider.authenticate( new TestingAuthenticationToken("foo", "bar",
Increased test coverate to <I>%
spring-projects_spring-security
train
24febf29edf7b87a5cb8751595e9eb72fff103e4
diff --git a/src/v2/commands/setup.js b/src/v2/commands/setup.js index <HASH>..<HASH> 100644 --- a/src/v2/commands/setup.js +++ b/src/v2/commands/setup.js @@ -104,7 +104,7 @@ function importTasklist(taskList, taskConfig, usherFilePath) { _.each(taskConfig.import, taskImportName => { const propertyAliasName = getAlias(taskImportName)[1]; taskList[aliasName].tasks[propertyAliasName] = { - tasks: importTasks(tasks[propertyAliasName]) + tasks: importTasks(tasks[propertyAliasName].tasks) }; }); } @@ -116,9 +116,18 @@ function importVariables(varList, config, usherFilePath) { const [importName] = getAlias(config.name || config.from); const variables = _.endsWith(config.from, '.yml') ? loadAndParseYmlFile(varList, path.join(usherFilePath, config.from), 'vars') - : requireModule(importName).vars; + : requireModule(importName); + + if (!config.import) { + varList = _.merge(varList, variables || {}); + } + else { + _.each(config.import, taskImportName => { + _.merge(varList, variables[taskImportName].vars || {}); + }); + } - return variables || {}; + return varList; } module.exports = (config, Logger, usherFilePath) => Promise.try(() => {
Fix bug with import vars from git library
findmypast_usher
train
922bcab5bdec578fb1b918efc48fba4922223ba6
diff --git a/address.py b/address.py index <HASH>..<HASH> 100644 --- a/address.py +++ b/address.py @@ -565,38 +565,28 @@ class Address(object): "timestamp": timestamp, "proofs": [''] } + dataBinary = b'' for i in range(0, len(data)): d = data[i] type = 0 value = d['value'] - if isinstance(value, bool): - type = 1 - d['type'] = 'boolean' - if value: - d['valueForSignature'] = 1 - else: - d['valueForSignature'] = 0 - elif isinstance(value, int): - d['type'] = 'integer' - type = 0 - elif isinstance(value, str): - d['type'] = 'binary' + if d['type'] == 'binary': d['value'] = base58.b58encode(crypto.str2bytes(d['value'])) - type = 2 - else: - logging.error('Wrong data type') keyBytes = crypto.str2bytes(d['key']) - dataBinary = b'' + struct.pack(">H", len(keyBytes)) + dataBinary += struct.pack(">H", len(keyBytes)) dataBinary += keyBytes - dataBinary += struct.pack(">H", type) - if isinstance(value, str): - dataBinary += struct.pack(">H", len(value)) - dataBinary += crypto.str2bytes(value) + if d['type'] == 'binary': + dataBinary += b'\2' + struct.pack(">H", len(value)) + dataBinary += crypto.str2bytes(d['value']) else: - if isinstance(value, bool): - dataBinary += struct.pack(">H", d['valueForSignature']) + if d['type'] == 'boolean': + if value: + dataBinary += b'\1\1' + else: + dataBinary += b'\1\0' else: - dataBinary += struct.pack(">H", value) + dataBinary += b'\0' + struct.pack(">H", value) + print(dataBinary) # check: https://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python #txFee = (int(( (len(crypto.str2bytes(json.dumps(data))) + 2 + 64 )) / 1000.0) + 1 ) * 100000 @@ -613,6 +603,7 @@ class Address(object): dataObject['proofs'] = [ crypto.sign(self.privateKey, sData) ] dataObjectJSON = json.dumps(dataObject) + print(sData) print(dataObjectJSON) return pywaves.wrapper('/transactions/broadcast', dataObjectJSON)
removed some bugs, still signatures for data tx are not accepted
PyWaves_PyWaves
train
28a7ed9a93b696409889ff50fc901f03028183c6
diff --git a/pymongo/common.py b/pymongo/common.py index <HASH>..<HASH> 100644 --- a/pymongo/common.py +++ b/pymongo/common.py @@ -93,7 +93,7 @@ def validate_positive_float(option, value): value = float(value) except (ValueError, TypeError): raise err - if value <= 0: + if not 0 < value < float('inf'): raise err return value diff --git a/test/test_uri_parser.py b/test/test_uri_parser.py index <HASH>..<HASH> 100644 --- a/test/test_uri_parser.py +++ b/test/test_uri_parser.py @@ -84,6 +84,8 @@ class TestURI(unittest.TestCase): self.assertRaises(ConfigurationError, split_options, 'socketTimeoutMS=0.0') self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=foo') self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=0.0') + self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=inf') + self.assertRaises(ConfigurationError, split_options, 'connectTimeoutMS=-inf') self.assertTrue(split_options('socketTimeoutMS=300')) self.assertTrue(split_options('connectTimeoutMS=300')) self.assertEqual({'sockettimeoutms': 0.3}, split_options('socketTimeoutMS=300'))
Prohibit +/-infinity as timeout values
mongodb_mongo-python-driver
train
4ea6a0f83d4e232c10428020dcb90011f196c874
diff --git a/tests/test_file_probing.py b/tests/test_file_probing.py index <HASH>..<HASH> 100644 --- a/tests/test_file_probing.py +++ b/tests/test_file_probing.py @@ -45,6 +45,7 @@ class TestAudioProbe(TestCase): class TestVideoProbe(TestCase): + def setUp(self): self.file = av.open(fate_suite('mpeg2/mpeg2_field_encoding.ts')) @@ -87,5 +88,9 @@ class TestVideoProbe(TestCase): self.assertEqual(stream.average_rate, Fraction(25, 1)) self.assertEqual(stream.width, 720) self.assertEqual(stream.height, 576) - self.assertEqual(stream.coded_width, 720) - self.assertEqual(stream.coded_height, 576) + + # For some reason, these behave differently on OS X (@mikeboers) and + # Ubuntu (Travis). We think it is FFmpeg, but haven't been able to + # confirm. + self.assertIn(stream.coded_width, (720, 0)) + self.assertIn(stream.coded_height, (576, 0))
Pass test_file_probing on OS X (which for unknown reasons is different than Travis)
mikeboers_PyAV
train
918b36ad6e2437f272cb339951b3410e81fd8593
diff --git a/pkg/minikube/cluster/commands.go b/pkg/minikube/cluster/commands.go index <HASH>..<HASH> 100644 --- a/pkg/minikube/cluster/commands.go +++ b/pkg/minikube/cluster/commands.go @@ -154,7 +154,7 @@ func GenLocalkubeStartCmd(kubernetesConfig KubernetesConfig) (string, error) { flagVals = append(flagVals, "--feature-gates="+kubernetesConfig.FeatureGates) } - if kubernetesConfig.APIServerName != "" { + if kubernetesConfig.APIServerName != constants.APIServerName { flagVals = append(flagVals, "--apiserver-name="+kubernetesConfig.APIServerName) }
Check APIServerName against default If the apiserver is something other than the default, pass in the flag. This won't be compatible with the old versions of localkube. Old versions of localkube will work as long as apiserver-name is not specified in minikube, always using the default.
kubernetes_minikube
train
ac4a9aea19a87a50b50a2515a49d2355b5b3af60
diff --git a/opengem/output/risk.py b/opengem/output/risk.py index <HASH>..<HASH> 100644 --- a/opengem/output/risk.py +++ b/opengem/output/risk.py @@ -46,9 +46,11 @@ class RiskXMLWriter(writer.FileWriter): pe_values = _curve_pe_as_gmldoublelist(curve_object) - subnode_pe = self.root_node.findall(".//" + self.abcissa_tag) - if len(subnode_pe): - if subnode_pe[0].text != pe_values: + # This use of not None is b/c of the trap w/ ElementTree find + # for nodes that have no child nodes. + subnode_pe = self.root_node.find(self.abcissa_tag) + if subnode_pe is not None: + if subnode_pe.text != pe_values: raise Exception("Curves must share the same Abcissa!") else: subnode_pe = etree.SubElement(self.root_node,
A little tidy-up from findall to a find check, having checked the lxml docs on how empty nodes are handled in if statements.
gem_oq-engine
train
6ff80f8a92f11f779b13a3ab6f9780f26ea1d3a2
diff --git a/src/java/com/threerings/media/sprite/Sprite.java b/src/java/com/threerings/media/sprite/Sprite.java index <HASH>..<HASH> 100644 --- a/src/java/com/threerings/media/sprite/Sprite.java +++ b/src/java/com/threerings/media/sprite/Sprite.java @@ -1,5 +1,5 @@ // -// $Id: Sprite.java,v 1.28 2001/10/25 01:39:38 shaper Exp $ +// $Id: Sprite.java,v 1.29 2001/10/25 03:01:13 shaper Exp $ package com.threerings.media.sprite; @@ -123,15 +123,26 @@ public class Sprite { // create a starting dirty rectangle with our current position Rectangle dirty = new Rectangle(_bounds); + // move ourselves _x = x; _y = y; - // we need to update our draw position which is based on the size - // of our current frame + + // we need to update our draw position which is based on the + // size of our current frame updateRenderOrigin(); - // grow the dirty rectangle to reflect our new location - dirty.add(_bounds); - // and invalidate the whole shebang + + if (dirty.intersects(_bounds)) { + // grow the dirty rectangle to reflect our new location + dirty.add(_bounds); + } else { + // dirty the new rectangle separately from the old to + // avoid potentially creating a large dirty rectangle if + // the sprite warps from place to place + invalidate(new Rectangle(_bounds)); + } + + // invalidate the potentially-grown starting dirty rectangle invalidate(dirty); }
Don't merge dirty rectangles when moving a sprite if the rectangles don't overlap. git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
threerings_narya
train
bd9323d5058867aa75b708699df6c9012eb1d1fa
diff --git a/packages/veritone-redux-common/src/modules/index.js b/packages/veritone-redux-common/src/modules/index.js index <HASH>..<HASH> 100644 --- a/packages/veritone-redux-common/src/modules/index.js +++ b/packages/veritone-redux-common/src/modules/index.js @@ -5,9 +5,12 @@ export const uiState = { }; import userReducer, * as userModule from './user'; +import * as userConstants from './user/constants'; + export const user = { reducer: userReducer, - ...userModule + ...userModule, + ...userConstants }; import configReducer, * as configModule from './config'; @@ -18,8 +21,11 @@ export const config = { import authRootSaga from './auth/oauthSaga' import authReducer, * as authModule from './auth'; +import * as authConstants from './auth/constants'; + export const auth = { reducer: authReducer, ...authModule, + ...authConstants, authRootSaga };
properly export constants from their new locations
veritone_veritone-sdk
train
9938f55eeec3f7d05fa428def16e2255e94a3d3c
diff --git a/addon/fold/foldcode.js b/addon/fold/foldcode.js index <HASH>..<HASH> 100644 --- a/addon/fold/foldcode.js +++ b/addon/fold/foldcode.js @@ -1,7 +1,7 @@ (function() { "use strict"; - function doFold(cm, pos, options) { + function doFold(cm, pos, options, force) { var finder = options && (options.call ? options : options.rangeFinder); if (!finder) finder = cm.getHelper(pos, "fold"); if (!finder) return; @@ -13,7 +13,7 @@ if (!range || range.to.line - range.from.line < minSize) return null; var marks = cm.findMarksAt(range.from); for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { + if (marks[i].__isFold && force !== "fold") { if (!allowFolded) return null; range.cleared = true; marks[i].clear(); @@ -27,7 +27,7 @@ pos = CodeMirror.Pos(pos.line - 1, 0); range = getRange(false); } - if (!range || range.cleared) return; + if (!range || range.cleared || force === "unfold") return; var myWidget = makeWidget(options); CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); }); @@ -59,7 +59,9 @@ }; // New-style interface - CodeMirror.defineExtension("foldCode", function(pos, options) { doFold(this, pos, options); }); + CodeMirror.defineExtension("foldCode", function(pos, options, force) { + doFold(this, pos, options, force); + }); CodeMirror.registerHelper("fold", "combine", function() { var funcs = Array.prototype.slice.call(arguments, 0);
[foldcode addon] Add experimental force argument to foldCode method
codemirror_CodeMirror
train
099d3965735de418b5a69e3d13e1344fe1a69796
diff --git a/test/run-tests.py b/test/run-tests.py index <HASH>..<HASH> 100755 --- a/test/run-tests.py +++ b/test/run-tests.py @@ -14,19 +14,6 @@ import tempfile import pytest -if not hasattr(contextlib, "suppress"): - """ - Polyfill for ``contextlib.suppress`` - """ - @contextlib.contextmanager - def _contextlib_suppress(*exceptions): - try: - yield - except exceptions: - pass - contextlib.suppress = _contextlib_suppress - - ###################### # Test configuration # ######################
Remove polyfill for contextlib.suppress (not needed since Python <I>)
ipfs_py-ipfs-api
train
5725801d4283a1b5beb08ea7637c9472240aee68
diff --git a/lib/gem_release/helpers.rb b/lib/gem_release/helpers.rb index <HASH>..<HASH> 100644 --- a/lib/gem_release/helpers.rb +++ b/lib/gem_release/helpers.rb @@ -35,7 +35,7 @@ module GemRelease end def gem_version - gemspec.version.to_s + options[:version_number] || gemspec.version.to_s end def gemspec diff --git a/lib/rubygems/commands/bump_command.rb b/lib/rubygems/commands/bump_command.rb index <HASH>..<HASH> 100644 --- a/lib/rubygems/commands/bump_command.rb +++ b/lib/rubygems/commands/bump_command.rb @@ -89,6 +89,7 @@ class Gem::Commands::BumpCommand < Gem::Command end cmd.options[:quiet] = options[:quiet] cmd.options[:quiet_success] = true + cmd.options[:version_number] = @new_version_number cmd.execute true end @@ -98,6 +99,7 @@ class Gem::Commands::BumpCommand < Gem::Command cmd.options[:quiet] = options[:quiet] cmd.options[:quiet_success] = true cmd.options[:push_tags_only] = true + cmd.options[:version_number] = @new_version_number cmd.execute true end
Ensure that a bumped version is used for `tag` and `release`. The gemspec file was not being properly re-evaluated after the version file changed in rubygems <I>, which led to the old version being used to tag and release gems that were just bumped. This workaround ensures that the new version number will be used by subsequent commands by passing it as an option that will be evaluated prior to the gemspec version. [Fixes #<I>]
svenfuchs_gem-release
train
b62b4401b862b6f98799d4b6a789193af37cc036
diff --git a/src/Multiple/ConnectionManagerConcurrent.php b/src/Multiple/ConnectionManagerConcurrent.php index <HASH>..<HASH> 100644 --- a/src/Multiple/ConnectionManagerConcurrent.php +++ b/src/Multiple/ConnectionManagerConcurrent.php @@ -10,6 +10,10 @@ class ConnectionManagerConcurrent extends ConnectionManagerConsecutive { public function create($host, $port) { + if (!$this->managers) { + return Promise\reject(new \UnderflowException('No managers to try to connect through')); + } + $all = array(); foreach ($this->managers as $connector) { /* @var $connection Connector */
Explicitly reject empty lists for concurrent connections
clue_reactphp-connection-manager-extra
train
e6f609bc36f792d743590e5d16b4aceabdcb22ff
diff --git a/spec/integration/associations_spec.rb b/spec/integration/associations_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/associations_spec.rb +++ b/spec/integration/associations_spec.rb @@ -426,4 +426,45 @@ describe PgSearch do results.should_not include(*excluded) end end + + context "chained onto a has_many association" do + with_model :Company do + model do + has_many :positions + end + end + + with_model :Position do + table do |t| + t.string :title + t.belongs_to :company + end + + model do + include PgSearch + pg_search_scope :search, :against => :title, :using => [:tsearch, :trigram] + end + end + + # https://github.com/Casecommons/pg_search/issues/106 + it "should handle numbers in a trigram query properly" do + company = Company.create! + another_company = Company.create! + + included = [ + Position.create!(company_id: company.id, title: "teller 1") + ] + + excluded = [ + Position.create!(company_id: nil, title: "teller 1"), + Position.create!(company_id: another_company.id, title: "teller 1"), + Position.create!(company_id: company.id, title: "penn 1") + ] + + results = company.positions.search('teller 1') + + results.should include(*included) + results.should_not include(*excluded) + end + end end
Add failing spec for Github Issue #<I>
Casecommons_pg_search
train
d64d5070fd1bd86dadec5925e7e47d270928cfac
diff --git a/examples/word_language_model/train.py b/examples/word_language_model/train.py index <HASH>..<HASH> 100644 --- a/examples/word_language_model/train.py +++ b/examples/word_language_model/train.py @@ -50,7 +50,11 @@ class ExamplePrinter(skorch.callbacks.Callback): def my_train_split(X, y): # Return (corpus.train, corpus.valid) in case the network # is fitted using net.fit(corpus.train). - return X, corpus.valid, None, None + # + # TODO: remove dummy y values once #112 is fixed. + # + import numpy as np + return X, corpus.valid, np.zeros(len(X)), np.zeros(len(corpus.valid)) net = Net( module=RNNModel, @@ -59,6 +63,7 @@ net = Net( use_cuda=args.cuda, callbacks=[ skorch.callbacks.Checkpoint(), + skorch.callbacks.ProgressBar(), LRAnnealing(), ExamplePrinter() ],
Temporary workaround for #<I>
skorch-dev_skorch
train
5ff0963958105362f663c06999c4d7ec4bc073d5
diff --git a/lib/jets/lambda/dsl.rb b/lib/jets/lambda/dsl.rb index <HASH>..<HASH> 100644 --- a/lib/jets/lambda/dsl.rb +++ b/lib/jets/lambda/dsl.rb @@ -184,7 +184,8 @@ module Jets::Lambda::Dsl properties: @properties, # lambda function properties iam_policy: @iam_policy, managed_iam_policy: @managed_iam_policy, - lang: lang) + lang: lang, + replacements: replacements(meth)) # Done storing options, clear out for the next added method. clear_properties @@ -199,6 +200,11 @@ module Jets::Lambda::Dsl true end + # Meant to be overridden to add more custom replacements based on the app class type + def replacements(meth) + {} + end + def clear_properties @resources = nil @properties = nil diff --git a/lib/jets/lambda/task.rb b/lib/jets/lambda/task.rb index <HASH>..<HASH> 100644 --- a/lib/jets/lambda/task.rb +++ b/lib/jets/lambda/task.rb @@ -11,6 +11,7 @@ class Jets::Lambda::Task @iam_policy = options[:iam_policy] @managed_iam_policy = options[:managed_iam_policy] @lang = options[:lang] || :ruby + @replacements = options[:replacements] || {} # added replacements to the baseline replacements end def build_function_iam? @@ -82,11 +83,15 @@ class Jets::Lambda::Task handler_path.sub("handlers/", "app/") end - ### - # Useful for Jets::Resource late building. def replacements + # Merge in the custom replacements specific to each app class: ConfigRule, Job, etc. + baseline_replacements.merge(@replacements) + end + + def baseline_replacements { namespace: "#{@class_name.gsub('::','')}#{@meth.to_s.camelize}", # camelized because used in not just keys but also values } end end + diff --git a/lib/jets/rule/dsl.rb b/lib/jets/rule/dsl.rb index <HASH>..<HASH> 100644 --- a/lib/jets/rule/dsl.rb +++ b/lib/jets/rule/dsl.rb @@ -110,16 +110,17 @@ module Jets::Rule::Dsl # Creates a task but registers it to all_managed_rules instead of all_tasks # because we do not want Lambda functions to be created. def register_managed_rule(name, definition) - # A task object is needed to build {namespace} for later replacing. - task = Jets::Lambda::Task.new(self.name, name, resources: @resources) + all_managed_rules[name] = { definition: definition, replacements: replacements(name) } + clear_properties + end - # TODO: figure out better way for specific replacements for different classes + # Also used in the normal Lambda backed config rules + def replacements(meth) name_without_rule = self.name.underscore.gsub(/_rule$/,'') - config_rule_name = "#{name_without_rule}_#{name}".dasherize - replacements = task.replacements.merge(config_rule_name: config_rule_name) - - all_managed_rules[name] = { definition: definition, replacements: replacements } - clear_properties + config_rule_name = "#{name_without_rule}_#{meth}".dasherize + { + config_rule_name: config_rule_name + } end # AWS managed rules are not actual Lambda functions and require their own storage.
fix config rule name replacement for both managed and custom rules
tongueroo_jets
train
054e2c42a532d4f160bdb36d2b3864880c16ce4b
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -157,11 +157,6 @@ module ActiveRecord false end - # Does this adapter support using DISTINCT within COUNT? - def supports_count_distinct? - true - end - # Does this adapter support DDL rollbacks in transactions? That is, would # CREATE TABLE or ALTER TABLE get rolled back by a transaction? def supports_ddl_transactions?
Remove unused method This method is not being called anywhere in our code and a GitHub search show it is not being used in any project.
rails_rails
train
d94773e6856d2764ed88d049da63e7936fb92448
diff --git a/src/transformers/models/hubert/modeling_hubert.py b/src/transformers/models/hubert/modeling_hubert.py index <HASH>..<HASH> 100755 --- a/src/transformers/models/hubert/modeling_hubert.py +++ b/src/transformers/models/hubert/modeling_hubert.py @@ -911,11 +911,7 @@ class HubertModel(HubertPreTrainedModel): attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool() hidden_states = self.feature_projection(extract_features) - - if mask_time_indices is not None: # apply SpecAugment along time axis with given indices - hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype) - - hidden_states = self._mask_hidden_states(hidden_states) + hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) encoder_outputs = self.encoder( hidden_states, diff --git a/src/transformers/models/hubert/modeling_tf_hubert.py b/src/transformers/models/hubert/modeling_tf_hubert.py index <HASH>..<HASH> 100644 --- a/src/transformers/models/hubert/modeling_tf_hubert.py +++ b/src/transformers/models/hubert/modeling_tf_hubert.py @@ -1227,13 +1227,6 @@ class TFHubertMainLayer(tf.keras.layers.Layer): hidden_states = self.feature_projection(hidden_states, training=inputs["training"]) mask_time_indices = kwargs.get("mask_time_indices", None) - if mask_time_indices is not None: # apply SpecAugment along time axis with given indices - hidden_states = tf.where( - tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool), - self.masked_spec_embed[tf.newaxis, tf.newaxis, :], - hidden_states, - ) - if inputs["training"]: hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) diff --git a/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py b/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py index <HASH>..<HASH> 100644 --- a/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py +++ b/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py @@ -1218,13 +1218,6 @@ class TFWav2Vec2MainLayer(tf.keras.layers.Layer): hidden_states = self.feature_projection(hidden_states, training=inputs["training"]) mask_time_indices = kwargs.get("mask_time_indices", None) - if mask_time_indices is not None: # apply SpecAugment along time axis with given indices - hidden_states = tf.where( - tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool), - self.masked_spec_embed[tf.newaxis, tf.newaxis, :], - hidden_states, - ) - if inputs["training"]: hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) diff --git a/src/transformers/models/wav2vec2/modeling_wav2vec2.py b/src/transformers/models/wav2vec2/modeling_wav2vec2.py index <HASH>..<HASH> 100755 --- a/src/transformers/models/wav2vec2/modeling_wav2vec2.py +++ b/src/transformers/models/wav2vec2/modeling_wav2vec2.py @@ -1049,11 +1049,7 @@ class Wav2Vec2Model(Wav2Vec2PreTrainedModel): attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool() hidden_states, extract_features = self.feature_projection(extract_features) - - if mask_time_indices is not None: # apply SpecAugment along time axis with given indices - hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype) - - hidden_states = self._mask_hidden_states(hidden_states) + hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) encoder_outputs = self.encoder( hidden_states,
Provide mask_time_indices to `_mask_hidden_states` to avoid double masking (#<I>) * We need to provide mask_time_indices to `_mask_hidden_states` to avoid applying the mask two times * apply the same to wav2vec2 * Uniformize the style between hubert and wav2vec2 * fix tf as well
huggingface_pytorch-pretrained-BERT
train
7417297216611c695d12916295bfb8be633697cb
diff --git a/tests.py b/tests.py index <HASH>..<HASH> 100644 --- a/tests.py +++ b/tests.py @@ -940,6 +940,26 @@ class RelatedFieldTests(BasePeeweeTestCase): # this should work the same some_tags = EntryTag.select().where(entry__in=some_entries) self.assertEqual(list(some_tags), [a_tag, b_tag]) + + def test_complex_subquery(self): + a_blog = Blog.create(title='a blog') + b_blog = Blog.create(title='b blog') + c_blog = Blog.create(title='c blog') + + a = User.create(username='a', blog=a_blog) + b = User.create(username='b', blog=b_blog) + c = User.create(username='c', blog=c_blog) + + some_users = User.select().where(username__in=['a', 'b']) + + c_blog_qr = Blog.select().join(User).where(~Q(id__in=some_users)) + self.assertEqual(list(c_blog_qr), [c_blog]) + + ac_blog_qr = Blog.select().join(User).where( + ~Q(id__in=some_users) | + Q(username='a') + ) + self.assertEqual(list(ac_blog_qr), [a_blog, c_blog]) class FieldTypeTests(BasePeeweeTestCase):
Checking in test for complex subqueries
coleifer_peewee
train
4607251d231a449944977265f479e308f08b3504
diff --git a/ddl/index.go b/ddl/index.go index <HASH>..<HASH> 100644 --- a/ddl/index.go +++ b/ddl/index.go @@ -746,6 +746,7 @@ func (d *ddl) backfillBatchTasks(startTime time.Time, startHandle int64, reorgIn err1 := kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error { return errors.Trace(reorgInfo.UpdateHandle(txn, nextHandle)) }) + metrics.BatchAddIdxHistogram.WithLabelValues(metrics.LblError).Observe(elapsedTime) log.Warnf("[ddl-reorg] total added index for %d rows, this task [%d,%d) add index for %d failed %v, take time %v, update handle err %v", *totalAddedCount, startHandle, nextHandle, taskAddedCount, err, elapsedTime, err1) return errors.Trace(err) @@ -753,7 +754,7 @@ func (d *ddl) backfillBatchTasks(startTime time.Time, startHandle int64, reorgIn // nextHandle will be updated periodically in runReorgJob, so no need to update it here. d.reorgCtx.setNextHandle(nextHandle) - metrics.BatchAddIdxHistogram.Observe(elapsedTime) + metrics.BatchAddIdxHistogram.WithLabelValues(metrics.LblOK).Observe(elapsedTime) log.Infof("[ddl-reorg] total added index for %d rows, this task [%d,%d) added index for %d rows, take time %v", *totalAddedCount, startHandle, nextHandle, taskAddedCount, elapsedTime) return nil diff --git a/metrics/ddl.go b/metrics/ddl.go index <HASH>..<HASH> 100644 --- a/metrics/ddl.go +++ b/metrics/ddl.go @@ -34,14 +34,14 @@ var ( Buckets: prometheus.ExponentialBuckets(0.01, 2, 20), }, []string{LblType, LblResult}) - BatchAddIdxHistogram = prometheus.NewHistogram( + BatchAddIdxHistogram = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "tidb", Subsystem: "ddl", Name: "batch_add_idx_duration_seconds", Help: "Bucketed histogram of processing time (s) of batch handle data", Buckets: prometheus.ExponentialBuckets(0.001, 2, 20), - }) + }, []string{LblType}) SyncerInit = "init" SyncerRestart = "restart"
metrics:fix add index duration bucket dosen't work (#<I>) * fix add index duration bucket dosen't work
pingcap_tidb
train
b9dcb847418190f2dbbb1d27b0e874add5ea06ae
diff --git a/odl/discr/grid.py b/odl/discr/grid.py index <HASH>..<HASH> 100644 --- a/odl/discr/grid.py +++ b/odl/discr/grid.py @@ -998,11 +998,15 @@ class RegularGrid(TensorGrid): return RegularGrid(new_shape, new_center, new_stride) def __repr__(self): - """repr(self) implementation.""" + """g.__repr__() <==> repr(g).""" return 'RegularGrid({}, {}, {})'.format(list(self.shape), list(self.center), list(self.stride)) + def __str__(self): + """g.__str__() <==> str(g).""" + return self.__repr__() + if __name__ == '__main__': from doctest import testmod, NORMALIZE_WHITESPACE
Changed `__str__()` in `RegularGrid` to be identical to `__repr__()`
odlgroup_odl
train
c1a1361cde22318f5c70e9444aab51ab64688355
diff --git a/pex/interpreter.py b/pex/interpreter.py index <HASH>..<HASH> 100644 --- a/pex/interpreter.py +++ b/pex/interpreter.py @@ -75,6 +75,16 @@ class PythonIdentity(object): "cp": "CPython", } + @staticmethod + def _normalize_macosx_deployment_target(value): + # type: (Any) -> Optional[str] + + # N.B.: Sometimes MACOSX_DEPLOYMENT_TARGET can be configured as a float. + # See: https://github.com/pantsbuild/pex/issues/1337 + if value is None: + return None + return str(value) + @classmethod def get(cls, binary=None): # type: (Optional[str]) -> PythonIdentity @@ -91,7 +101,10 @@ class PythonIdentity(object): supported_tags = tuple(tags.sys_tags()) preferred_tag = supported_tags[0] - configured_macosx_deployment_target = sysconfig.get_config_var("MACOSX_DEPLOYMENT_TARGET") + + configured_macosx_deployment_target = cls._normalize_macosx_deployment_target( + sysconfig.get_config_var("MACOSX_DEPLOYMENT_TARGET") + ) return cls( binary=binary or sys.executable, @@ -109,7 +122,7 @@ class PythonIdentity(object): version=sys.version_info[:3], supported_tags=supported_tags, env_markers=markers.default_environment(), - configured_macosx_deployment_target=configured_macosx_deployment_target or None, + configured_macosx_deployment_target=configured_macosx_deployment_target, ) @classmethod @@ -125,7 +138,17 @@ class PythonIdentity(object): for (interpreter, abi, platform) in supported_tags: yield tags.Tag(interpreter=interpreter, abi=abi, platform=platform) - return cls(supported_tags=iter_tags(), **values) + # N.B.: Old encoded identities may have numeric values; so we support these and convert + # back to strings here as needed. See: https://github.com/pantsbuild/pex/issues/1337 + configured_macosx_deployment_target = cls._normalize_macosx_deployment_target( + values.pop("configured_macosx_deployment_target") + ) + + return cls( + supported_tags=iter_tags(), + configured_macosx_deployment_target=configured_macosx_deployment_target, + **values + ) @classmethod def _find_interpreter_name(cls, python_tag):
Fix MACOSX_DEPLOYMENT_TARGET handling. (#<I>) Previously it was assumed the MACOSX_DEPLOYMENT_TARGET sysconfig var was always a string and that has proven to be false. Fixes #<I>
pantsbuild_pex
train
52fcf25366a4f0bd9a07759348646e428b090045
diff --git a/src/sap.m/src/sap/m/FacetFilter.js b/src/sap.m/src/sap/m/FacetFilter.js index <HASH>..<HASH> 100644 --- a/src/sap.m/src/sap/m/FacetFilter.js +++ b/src/sap.m/src/sap/m/FacetFilter.js @@ -484,7 +484,6 @@ sap.ui.define([ FacetFilter.prototype.init = function() { this._pageSize = 5; - this._addDelegateFlag = false; this._invalidateFlag = false; this._lastCategoryFocusIndex = 0; this._aDomRefs = null; @@ -595,6 +594,7 @@ sap.ui.define([ if (sType !== FacetFilterType.Light) { this._startItemNavigation(); + this.addDelegate(this.oItemNavigation); } if (sType === FacetFilterType.Light) { @@ -632,10 +632,8 @@ sap.ui.define([ } //initialize the delegate add apply it to the control (only once) - if ((!this.oItemNavigation) || this._addDelegateFlag == true) { + if (!this.oItemNavigation) { this.oItemNavigation = new ItemNavigation(); - this.addDelegate(this.oItemNavigation); - this._addDelegateFlag = false; } this._aRows = aRows; for (var i = 0; i < this.$().find(":sapTabbable").length; i++) { @@ -1079,8 +1077,6 @@ sap.ui.define([ }, afterClose: function(oEvent) { - that._addDelegateFlag = true; - this._popoverClosing = false; that._handlePopoverAfterClose(); @@ -1590,7 +1586,6 @@ sap.ui.define([ stretch: Device.system.phone ? true : false, afterClose : function() { - that._addDelegateFlag = true; that._invalidateFlag = true; // Make sure we restore the FacetFilterList back to the lists aggregation and update its active state @@ -2014,7 +2009,6 @@ sap.ui.define([ icon: IconPool.getIconURI("undo"), tooltip: this._bundle.getText("FACETFILTER_RESET"), press: function(oEvent) { - this._addDelegateFlag = true; this._invalidateFlag = true; if (this._popoverClosing) {
[FIX] sap.m.FacetFilter: navigation steps issue * itemNavigation is initialized only once Change-Id: Ic<I>a<I>c0b<I>ce<I>e<I>a<I>b<I>b<I>b6 BCP: <I>
SAP_openui5
train
e90bc9c8f99892d21aa0a6287b59fd172dab71d7
diff --git a/merb-gen/lib/merb-gen.rb b/merb-gen/lib/merb-gen.rb index <HASH>..<HASH> 100644 --- a/merb-gen/lib/merb-gen.rb +++ b/merb-gen/lib/merb-gen.rb @@ -26,12 +26,4 @@ require path / "resource_controller" require path / "resource" require path / "freezer" -# Require all generators that plugins have added to merb, after the app has loaded. -Merb::BootLoader.after_app_loads do - # TODO: remove this if statement once generator hooks are added to merb-core proper - if Merb.respond_to?(:generators) - Merb.generators.each do |file| - require file - end - end -end \ No newline at end of file +Templater::Discovery.discover!("merb-gen") \ No newline at end of file
added templater's new discovery feature to merb-gen
wycats_merb
train
6bdf9d07cc93ba5f3a193ceafc0e13d35353316b
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounter.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounter.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounter.java @@ -39,5 +39,12 @@ public interface CheckpointIDCounter { * @return The previous checkpoint ID */ long getAndIncrement() throws Exception; - + + /** + * Sets the current checkpoint ID. + * + * @param newId The new ID + */ + void setCount(long newId) throws Exception; + } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java @@ -44,4 +44,9 @@ public class StandaloneCheckpointIDCounter implements CheckpointIDCounter { public long getAndIncrement() throws Exception { return checkpointIdCounter.getAndIncrement(); } + + @Override + public void setCount(long newCount) { + checkpointIdCounter.set(newCount); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/ZooKeeperCheckpointIDCounter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/ZooKeeperCheckpointIDCounter.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/ZooKeeperCheckpointIDCounter.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/ZooKeeperCheckpointIDCounter.java @@ -61,6 +61,10 @@ public class ZooKeeperCheckpointIDCounter implements CheckpointIDCounter { private final SharedCountConnectionStateListener connStateListener = new SharedCountConnectionStateListener(); + private final Object startStopLock = new Object(); + + private boolean isStarted; + /** * Creates a {@link ZooKeeperCheckpointIDCounter} instance. * @@ -76,17 +80,29 @@ public class ZooKeeperCheckpointIDCounter implements CheckpointIDCounter { @Override public void start() throws Exception { - sharedCount.start(); - client.getConnectionStateListenable().addListener(connStateListener); + synchronized (startStopLock) { + if (!isStarted) { + sharedCount.start(); + client.getConnectionStateListenable().addListener(connStateListener); + + isStarted = true; + } + } } @Override public void stop() throws Exception { - sharedCount.close(); - client.getConnectionStateListenable().removeListener(connStateListener); + synchronized (startStopLock) { + if (isStarted) { + sharedCount.close(); + client.getConnectionStateListenable().removeListener(connStateListener); + + LOG.info("Removing {} from ZooKeeper", counterPath); + client.delete().deletingChildrenIfNeeded().inBackground().forPath(counterPath); - LOG.info("Removing {} from ZooKeeper", counterPath); - client.delete().deletingChildrenIfNeeded().inBackground().forPath(counterPath); + isStarted = false; + } + } } @Override @@ -108,6 +124,23 @@ public class ZooKeeperCheckpointIDCounter implements CheckpointIDCounter { } } + @Override + public void setCount(long newId) throws Exception { + ConnectionState connState = connStateListener.getLastState(); + + if (connState != null) { + throw new IllegalStateException("Connection state: " + connState); + } + + if (newId > Integer.MAX_VALUE) { + throw new IllegalArgumentException("ZooKeeper checkpoint counter only supports " + + "checkpoints Ids up to " + Integer.MAX_VALUE + ", but given value is" + + newId); + } + + sharedCount.setCount((int) newId); + } + /** * Connection state listener. In case of {@link ConnectionState#SUSPENDED} or {@link * ConnectionState#LOST} we are not guaranteed to read a current count from ZooKeeper. diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounterTest.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounterTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointIDCounterTest.java @@ -157,6 +157,22 @@ public abstract class CheckpointIDCounterTest extends TestLogger { } /** + * Tests a simple {@link CheckpointIDCounter#setCount(long)} operation. + */ + @Test + public void testSetCount() throws Exception { + final CheckpointIDCounter counter = createCompletedCheckpoints(); + counter.start(); + + // Test setCount + counter.setCount(1337); + assertEquals(1337, counter.getAndIncrement()); + assertEquals(1338, counter.getAndIncrement()); + + counter.stop(); + } + + /** * Task repeatedly incrementing the {@link CheckpointIDCounter}. */ private static class Incrementer implements Callable<List<Long>> {
[FLINK-<I>] [runtime] Add setCount(long newCount) to CheckpointIDCounter
apache_flink
train
8602ec5dec59f68c8b7312581c095ce8335c2a43
diff --git a/lib/sprockets.rb b/lib/sprockets.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets.rb +++ b/lib/sprockets.rb @@ -115,9 +115,9 @@ module Sprockets register_bundle_processor 'application/javascript', Bundle register_bundle_processor 'text/css', Bundle - register_bundle_reducer '*/*', :data, :+ - register_bundle_reducer 'application/javascript', :data, Utils.method(:concat_javascript_sources) - register_bundle_reducer '*/*', :links, :+ + register_bundle_metadata_reducer '*/*', :data, :+ + register_bundle_metadata_reducer 'application/javascript', :data, Utils.method(:concat_javascript_sources) + register_bundle_metadata_reducer '*/*', :links, :+ register_compressor 'text/css', :sass, LazyProcessor.new { SassCompressor } register_compressor 'text/css', :scss, LazyProcessor.new { SassCompressor } diff --git a/lib/sprockets/processing.rb b/lib/sprockets/processing.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/processing.rb +++ b/lib/sprockets/processing.rb @@ -204,13 +204,13 @@ module Sprockets # and asset metadata key. attr_reader :bundle_reducers - # Public: Register bundle reducer function. + # Public: Register bundle metadata reducer function. # # Examples # - # Sprockets.register_bundle_reducer 'application/javascript', :jshint_errors, [], :+ + # Sprockets.register_bundle_metadata_reducer 'application/javascript', :jshint_errors, [], :+ # - # Sprockets.register_bundle_reducer 'text/css', :selector_count, 0 { |total, count| + # Sprockets.register_bundle_metadata_reducer 'text/css', :selector_count, 0 { |total, count| # total + count # } # @@ -220,7 +220,7 @@ module Sprockets # block - Proc accepting the memo accumulator and current value # # Returns nothing. - def register_bundle_reducer(mime_type, key, *args, &block) + def register_bundle_metadata_reducer(mime_type, key, *args, &block) case args.size when 0 reducer = block diff --git a/test/sprockets_test.rb b/test/sprockets_test.rb index <HASH>..<HASH> 100644 --- a/test/sprockets_test.rb +++ b/test/sprockets_test.rb @@ -89,7 +89,7 @@ JS2HTMLIMPORT = proc { |input| } Sprockets.register_transformer 'application/javascript', 'text/html', JS2HTMLIMPORT -Sprockets.register_bundle_reducer 'text/css', :selector_count, :+ +Sprockets.register_bundle_metadata_reducer 'text/css', :selector_count, :+ Sprockets.register_postprocessor 'text/css', proc { |input| { selector_count: input[:data].scan(/\{/).size }
Rename bundle reducer to metadata reducer
rails_sprockets
train
40e8d13d476fd52e8d80625784cf8aa3c3d30f17
diff --git a/joomla/filter/filteroutput.php b/joomla/filter/filteroutput.php index <HASH>..<HASH> 100644 --- a/joomla/filter/filteroutput.php +++ b/joomla/filter/filteroutput.php @@ -82,8 +82,8 @@ class JFilterOutput //remove any '-' from the string they will be used as concatonater $str = str_replace('-', ' ', $string); - //$lang = &JFactory::getLanguage(); - //$str = $lang->transliterate($str); + $lang = &JFactory::getLanguage(); + $str = $lang->transliterate($str); // convert certain symbols to letter representation $str = str_replace(array('&', '"', '<', '>'), array('a', 'q', 'l', 'g'), $str);
Forgot to remove a comment before my last commit... This is still related to the JFilteroutput unittest fixes --HG-- extra : convert_revision : svn%3A6f6e1ebd-4c2b-<I>-<I>f-f<I>bde<I>bce9/development/trunk/libraries%<I>
joomla_joomla-framework
train
3094f767d6efdd38cd1e1d181942bfd4fa446dca
diff --git a/src/time.js b/src/time.js index <HASH>..<HASH> 100644 --- a/src/time.js +++ b/src/time.js @@ -13,7 +13,10 @@ Crafty.c("Delay", { var index = this._delays.length; while (--index >= 0) { var item = this._delays[index]; - if (item.start + item.delay + item.pause < now) { + if (item === false) { + // remove canceled item from array + this._delays.splice(index, 1); + } else if (item.start + item.delay + item.pause < now) { item.callback.call(this); if (item.repeat > 0) { // reschedule item @@ -22,7 +25,7 @@ Crafty.c("Delay", { item.pauseBuffer = 0; item.repeat--; } else if (item.repeat <= 0) { - // remove item from array + // remove finished item from array this._delays.splice(index, 1); if(typeof item.callbackOff === "function") item.callbackOff.call(this); @@ -84,7 +87,7 @@ Crafty.c("Delay", { * console.log("delay finished"); * }); * ~~~ - * + * */ delay: function (callback, delay, repeat, callbackOff) { this._delays.push({ @@ -98,7 +101,6 @@ Crafty.c("Delay", { }); return this; }, - /**@ * #.cancelDelay * @comp Delay @@ -109,13 +111,13 @@ Crafty.c("Delay", { * * @example * ~~~ - * var doSomething = function(){ - * console.log("doing something"); + * var doSomething = function(){ + * console.log("doing something"); * }; - * + * * // execute doSomething each 100 miliseconds indefinetely * var ent = Crafty.e("Delay").delay(doSomething, 100, -1); - * + * * // and some time later, cancel further execution of doSomething * ent.cancelDelay(doSomething); * ~~~ @@ -124,11 +126,10 @@ Crafty.c("Delay", { var index = this._delays.length; while (--index >= 0) { var item = this._delays[index]; - if(item.callback == callback) { - this._delays.splice(index, 1); + if(item && item.callback == callback){ + this._delays[index] = false; } } - return this; } });
Small fix for very specific bug in Delay component
craftyjs_Crafty
train
4b0c243d9e043f5a8d9ab0b79eb3ab08cb2cfdc7
diff --git a/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JQMDataTable.java b/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JQMDataTable.java index <HASH>..<HASH> 100644 --- a/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JQMDataTable.java +++ b/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JQMDataTable.java @@ -876,17 +876,21 @@ public class JQMDataTable extends JQMTableGrid { * @return - null if not enhanced yet, otherwise the root element (dataTables_wrapper). */ public Element getRootElement() { + return findUpperElement(WRAPPER); + } + + private Element findUpperElement(String eltStyle) { Element tableElt = getElement(); - Element wrapper = null; + Element rslt = null; Element elt = tableElt.getParentElement(); while (elt != null) { - if (JQMCommon.hasStyle(elt, WRAPPER)) { - wrapper = elt; + if (JQMCommon.hasStyle(elt, eltStyle)) { + rslt = elt; break; } elt = elt.getParentElement(); } - return wrapper; + return rslt; } /** @@ -934,6 +938,8 @@ public class JQMDataTable extends JQMTableGrid { /** Aligns header to match the columns, useful after resize or orientation changes. */ public void adjustColumnSizing() { JsDataTable.adjustColumnSizing(getElement()); + Element sb = findUpperElement(SCROLL_BODY); + if (sb != null) sb.setScrollLeft(0); } public String getColSorts() { diff --git a/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JsDataTable.java b/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JsDataTable.java index <HASH>..<HASH> 100644 --- a/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JsDataTable.java +++ b/plugins/datatables/src/main/java/com/sksamuel/jqm4gwt/plugins/datatables/JsDataTable.java @@ -1373,10 +1373,17 @@ public class JsDataTable { // Order by the grouping on group band click $wnd.$(api.table().body()).off('click.group'); $wnd.$(api.table().body()).on('click.group', 'tr.group', function (event) { + //$wnd.alert(event.currentTarget.offsetWidth + ' | ' + event.offsetX); + var switchAscDesc = false; + if (event.offsetX && event.currentTarget) { + var targetW = event.currentTarget.offsetWidth; + switchAscDesc = targetW && (event.offsetX > targetW - 40) && (event.offsetX <= targetW); + } + var newSorts = []; var currentOrder = api.order()[0]; if (currentOrder[0] === colIdx && currentOrder[1] === 'asc') { - newSorts.push([colIdx, 'desc']); + newSorts.push([colIdx, switchAscDesc ? 'desc' : 'asc']); } else if (currentOrder[0] !== colIdx || currentOrder[1] !== 'asc') { newSorts.push([colIdx, 'asc']); }
JQMDataTable - adjustColumnSizing() and asc/desc resorting on group row click - fixed/improved.
jqm4gwt_jqm4gwt
train
d82cbadbfacd44be1753002246f410500934d8a8
diff --git a/mast.js b/mast.js index <HASH>..<HASH> 100644 --- a/mast.js +++ b/mast.js @@ -56,9 +56,15 @@ Mast = _.extend(Backbone, parent = v.definition.extendsFrom ? entitySet[v.definition.extendsFrom] : Mast[capitalize(v.type)], newEntity = parent.extend(v.definition); + // Extend events hash as well + newEntity.prototype.events = _.extend({},parent.prototype.events,newEntity.prototype.events); + entitySet[v.name] = newEntity; + }); + + // Convert options.routes into a format Backbone's router will accept // (can't have key:function(){} style routes, must use a string function name)
Events hash is now inherited as well.
balderdashy_mast
train
9a9b533f2177b16d1f3fbc0b7122253c9c53e73f
diff --git a/test/utils/grunt.js b/test/utils/grunt.js index <HASH>..<HASH> 100644 --- a/test/utils/grunt.js +++ b/test/utils/grunt.js @@ -17,7 +17,7 @@ exports.runTask = function (task) { that.stderr = stderr; // Callback - done(); + done(err); }); });
If a Grunt task fails during a unit test, fail the test
twolfson_grunt-zip
train
b85234b0ef8be743e0e129fe2cd6e6c4797defc6
diff --git a/lib/delivery_boy/fake.rb b/lib/delivery_boy/fake.rb index <HASH>..<HASH> 100644 --- a/lib/delivery_boy/fake.rb +++ b/lib/delivery_boy/fake.rb @@ -2,7 +2,7 @@ module DeliveryBoy # A fake implementation that is useful for testing. class Fake - FakeMessage = Struct.new(:value, :topic, :key, :offset, :partition, :partition_key, :create_time) do + FakeMessage = Struct.new(:value, :topic, :key, :headers, :offset, :partition, :partition_key, :create_time) do def bytesize key.to_s.bytesize + value.to_s.bytesize end @@ -14,10 +14,10 @@ module DeliveryBoy @delivery_lock = Mutex.new end - def deliver(value, topic:, key: nil, partition: nil, partition_key: nil, create_time: Time.now) + def deliver(value, topic:, key: nil, headers: {}, partition: nil, partition_key: nil, create_time: Time.now) @delivery_lock.synchronize do offset = @messages[topic].count - message = FakeMessage.new(value, topic, key, offset, partition, partition_key, create_time) + message = FakeMessage.new(value, topic, key, headers, offset, partition, partition_key, create_time) @messages[topic] << message end @@ -27,10 +27,10 @@ module DeliveryBoy alias deliver_async! deliver - def produce(value, topic:, key: nil, partition: nil, partition_key: nil, create_time: Time.now) + def produce(value, topic:, key: nil, headers: {}, partition: nil, partition_key: nil, create_time: Time.now) @delivery_lock.synchronize do offset = @buffer[topic].count - message = FakeMessage.new(value, topic, key, offset, partition, partition_key, create_time) + message = FakeMessage.new(value, topic, key, headers, offset, partition, partition_key, create_time) @buffer[topic] << message end
Implement `DeliveryBoy::Fake::FakeMessage#headers` attribute for tests `ruby-kafka` implements a `headers` attribute for their `PendingMessage` class, this is supported naturally with that integration in `delivery_boy`, but not in tests as the `DeliveryBoy::Fake::FakeMessage` class is missing the attribute.
zendesk_delivery_boy
train
838a511f72e20f5368e32a969cda34112847a624
diff --git a/pgmpy/factors/continuous/LinearGaussianCPD.py b/pgmpy/factors/continuous/LinearGaussianCPD.py index <HASH>..<HASH> 100644 --- a/pgmpy/factors/continuous/LinearGaussianCPD.py +++ b/pgmpy/factors/continuous/LinearGaussianCPD.py @@ -79,9 +79,9 @@ class LinearGaussianCPD(BaseFactor): self.evidence = evidence self.sigma_yx = None - variables = [variable] + evidence + self.variables = [variable] + evidence super(LinearGaussianCPD, self).__init__( - variables, pdf="gaussian", mean=self.mean, covariance=self.variance + self.variables, pdf="gaussian", mean=self.mean, covariance=self.variance ) def sum_of_product(self, xi, xj): diff --git a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py index <HASH>..<HASH> 100644 --- a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py +++ b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py @@ -9,13 +9,23 @@ from pgmpy.models import LinearGaussianBayesianNetwork class TestLGBNMethods(unittest.TestCase): - @unittest.skip("TODO") def setUp(self): self.model = LinearGaussianBayesianNetwork([("x1", "x2"), ("x2", "x3")]) self.cpd1 = LinearGaussianCPD("x1", [1], 4) self.cpd2 = LinearGaussianCPD("x2", [-5, 0.5], 4, ["x1"]) self.cpd3 = LinearGaussianCPD("x3", [4, -1], 3, ["x2"]) + def test_cpds_simple(self): + self.assertEqual("x1", self.cpd1.variable) + self.assertEqual(4, self.cpd1.variance) + self.assertEqual([1], self.cpd1.mean) + + self.model.add_cpds(self.cpd1) + cpd = self.model.get_cpds("x1") + self.assertEqual(cpd.variable, self.cpd1.variable) + self.assertEqual(cpd.variance, self.cpd1.variance) + self.assertEqual(cpd.mean, self.cpd1.mean) + @unittest.skip("TODO") def test_add_cpds(self): self.model.add_cpds(self.cpd1)
Fix LinearGaussianCPD member variables [fixes #<I>] This was causing a compilation error when declaring LinearGaussianCPDs and adding it to a LinearGaussianBayesianNetwork model
pgmpy_pgmpy
train
8d81e3c1e703a46a2eb54f20cdd9564e1f72a503
diff --git a/app/mixins/modal.js b/app/mixins/modal.js index <HASH>..<HASH> 100644 --- a/app/mixins/modal.js +++ b/app/mixins/modal.js @@ -2,7 +2,7 @@ import Ember from 'ember'; export default Ember.Mixin.create({ - layoutName: 'modal', + layoutName: 'sl-components/templates/modal', classNames: [ 'modal', 'fade' ], diff --git a/app/mixins/modal.md b/app/mixins/modal.md index <HASH>..<HASH> 100644 --- a/app/mixins/modal.md +++ b/app/mixins/modal.md @@ -25,7 +25,7 @@ To use the modal, you're going to want to do 3 things: 1) In your View file, mix in the Modal mixin. import Ember from 'ember'; - import ModalMixin from 'testapp/mixins/modal'; + import ModalMixin from 'testapp/sl-components/mixins/modal'; export default Ember.View.extend( ModalMixin, { @@ -48,7 +48,7 @@ The main thing to keep in mind here is whether or not you have created a control import Ember from 'ember'; - import ModalManagerMixin from 'testapp/mixins/modalmanager'; + import ModalManager from 'testapp/sl-components/mixins/modalmanager'; export default Ember.Route.extend( ModalManagerMixin, { }); @@ -70,7 +70,7 @@ Here is a full example of an application that uses a list of buttons and shares routes/index.js: import Ember from 'ember'; - import ModalManager from 'testapp/mixins/modalmanager'; + import ModalManager from 'testapp/sl-components/mixins/modalmanager'; export default Ember.Route.extend( ModalManager, { @@ -103,7 +103,7 @@ controllers/hello.js: }); -templates/hello.js: +templates/hello.hbs: <div class="modal-header"> Hello {{modalContent}} @@ -119,7 +119,7 @@ templates/hello.js: views/hello.js: import Ember from 'ember'; - import ModalMixin from 'testapp/mixins/modal'; + import ModalMixin from 'testapp/sl-components/mixins/modal'; export default Ember.View.extend( ModalMixin, { diff --git a/lib/sl-components.js b/lib/sl-components.js index <HASH>..<HASH> 100755 --- a/lib/sl-components.js +++ b/lib/sl-components.js @@ -24,8 +24,7 @@ SlComponents.prototype.treeFor = function treeFor( name ) { files: [ 'components/*.js', 'helpers/*.js', - 'mixins/*.js', - 'templates/components/*.hbs' + 'mixins/*.js' ], destDir: 'sl-components' }); @@ -35,6 +34,16 @@ SlComponents.prototype.treeFor = function treeFor( name ) { return unwatchedTree( path.join( 'app/styles' )); } + if ( name == 'templates' ) { + return pickFiles( path.join( slComponentsPath, 'app' ), { + srcDir: '/', + files: [ + 'templates/**/*.js' + ], + destDir: 'sl-components' + }); + } + if ( name === 'vendor' ) { return pickFiles( path.join( slComponentsPath, 'vendor' ), { srcDir: '/',
Finished work on sample app and changes to support proper structure for template names
softlayer_sl-ember-components
train
87aff36c66bbef412e2d863c26e8733d000960d4
diff --git a/raiden/tests/utils/smoketest.py b/raiden/tests/utils/smoketest.py index <HASH>..<HASH> 100644 --- a/raiden/tests/utils/smoketest.py +++ b/raiden/tests/utils/smoketest.py @@ -56,7 +56,7 @@ from raiden.tests.utils.smartcontracts import deploy_contract_web3, deploy_token from raiden.transfer import channel, views from raiden.transfer.state import CHANNEL_STATE_OPENED from raiden.ui.app import run_app -from raiden.utils import merge_dict, privatekey_to_address, split_endpoint +from raiden.utils import privatekey_to_address, split_endpoint from raiden.utils.http import HTTPExecutor from raiden.utils.typing import Address, AddressHex, ChainID, Dict, Iterator from raiden.waiting import wait_for_block @@ -420,14 +420,11 @@ def run_smoketest( print_step("Starting Raiden") config = deepcopy(App.DEFAULT_CONFIG) - extra_config = args.pop("extra_config", None) - if extra_config: - merge_dict(config, extra_config) args["config"] = config # Should use basic routing in the smoke test for now # TODO: If we ever utilize a PFS in the smoke test we - # need to use the deployed service registry, register the - # PFS service there and then change this argument. + # need to use the deployed service registry, register the + # PFS service there and then change this argument. args["routing_mode"] = RoutingMode.BASIC raiden_stdout = StringIO() diff --git a/raiden/ui/app.py b/raiden/ui/app.py index <HASH>..<HASH> 100644 --- a/raiden/ui/app.py +++ b/raiden/ui/app.py @@ -143,6 +143,7 @@ def run_app( resolver_endpoint: str, routing_mode: RoutingMode, config: Dict[str, Any], + **kwargs: Dict, ): # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument
Allow kwargs in run_app and remove unused extra config from smoketest
raiden-network_raiden
train
4a7ad5235e07a8a781064c6d81133cef64c82975
diff --git a/test/cluster/cluster.go b/test/cluster/cluster.go index <HASH>..<HASH> 100644 --- a/test/cluster/cluster.go +++ b/test/cluster/cluster.go @@ -470,7 +470,7 @@ flynn=$GOPATH/src/github.com/flynn/flynn cd $flynn if [[ -f test/scripts/test-unit.sh ]]; then - test/scripts/test-unit.sh + timeout --signal=QUIT --kill-after=10 5m test/scripts/test-unit.sh fi `[1:]
test: Timeout the unit tests after 5 minutes CI is intermittently hanging indefinitely running `go test`. We need to investigate why, but we should also not allow the test to hang indefinitely.
flynn_flynn
train
0c9b0d44398075bd26baf1fee48b75eac2ce4bb3
diff --git a/Gemfile.lock b/Gemfile.lock index <HASH>..<HASH> 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - coney_island (0.10.2) + coney_island (0.10.5) amqp (>= 1.5.0) eventmachine rails (>= 4.0.1) diff --git a/lib/coney_island/submitter.rb b/lib/coney_island/submitter.rb index <HASH>..<HASH> 100644 --- a/lib/coney_island/submitter.rb +++ b/lib/coney_island/submitter.rb @@ -165,12 +165,14 @@ module ConeyIsland end def self.run_with_em(klass, method, *args) + ConeyIsland.stop_running_inline EventMachine.run do self.cache_jobs klass.send(method, *args) self.flush_jobs self.publisher_shutdown end + ConeyIsland.run_inline end def self.publisher_shutdown diff --git a/lib/coney_island/version.rb b/lib/coney_island/version.rb index <HASH>..<HASH> 100644 --- a/lib/coney_island/version.rb +++ b/lib/coney_island/version.rb @@ -1,3 +1,3 @@ module ConeyIsland - VERSION = "0.10.4" + VERSION = "0.10.5" end
ConeyIsland.run_with_em now submits new jobs to the queue
edraut_coney_island
train
4d564ffb508cc7cc8cf65e1aa92ae6ea1a22ab68
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java index <HASH>..<HASH> 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java @@ -30,8 +30,8 @@ import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; import org.springframework.security.web.access.intercept.AuthorizationFilter; -import org.springframework.security.web.access.intercept.DelegatingAuthorizationManager; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; +import org.springframework.security.web.access.intercept.RequestMatcherDelegatingAuthorizationManager; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; @@ -89,7 +89,8 @@ public final class AuthorizeHttpRequestsConfigurer<H extends HttpSecurityBuilder public final class AuthorizationManagerRequestMatcherRegistry extends AbstractRequestMatcherRegistry<AuthorizedUrl> { - private final DelegatingAuthorizationManager.Builder managerBuilder = DelegatingAuthorizationManager.builder(); + private final RequestMatcherDelegatingAuthorizationManager.Builder managerBuilder = RequestMatcherDelegatingAuthorizationManager + .builder(); private List<RequestMatcher> unmappedMatchers; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java index <HASH>..<HASH> 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java @@ -31,8 +31,8 @@ import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.intercept.AuthorizationFilter; -import org.springframework.security.web.access.intercept.DelegatingAuthorizationManager; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; +import org.springframework.security.web.access.intercept.RequestMatcherDelegatingAuthorizationManager; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.web.bind.annotation.GetMapping; @@ -105,7 +105,8 @@ public class AuthorizeHttpRequestsConfigurerTests { @Test public void configureWhenObjectPostProcessorRegisteredThenInvokedOnAuthorizationManagerAndAuthorizationFilter() { this.spring.register(ObjectPostProcessorConfig.class).autowire(); - verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(DelegatingAuthorizationManager.class)); + verify(ObjectPostProcessorConfig.objectPostProcessor) + .postProcess(any(RequestMatcherDelegatingAuthorizationManager.class)); verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(AuthorizationFilter.class)); }
Update AuthorizationManager references Issue gh-<I>
spring-projects_spring-security
train
54c871fc01fb43e7bc75442e17e156f68e95b23a
diff --git a/plexapi/utils.py b/plexapi/utils.py index <HASH>..<HASH> 100644 --- a/plexapi/utils.py +++ b/plexapi/utils.py @@ -378,3 +378,14 @@ def choose(msg, items, attr): # pragma: no cover except (ValueError, IndexError): pass + +def getAgentIdentifier(section, agent): + """ Return the full agent identifier from a short identifier, name, or confirm full identifier. """ + agents = [] + for ag in section.agents(): + identifiers = [ag.identifier, ag.shortIdentifier, ag.name] + if agent in identifiers: + return ag.identifier + agents += identifiers + raise NotFound('Couldnt find "%s" in agents list (%s)' % + (agent, ', '.join(agents)))
create getAgentIdentifier method in utils Return the full agent identifier from a short identifier, name, or confirm full identifier thanks @jonnywong<I>
pkkid_python-plexapi
train
e5ee00f4d044cebbc61454dcf2479ea0b19378bc
diff --git a/server/server.go b/server/server.go index <HASH>..<HASH> 100644 --- a/server/server.go +++ b/server/server.go @@ -848,7 +848,11 @@ func uiAssetExists(filename string) bool { return false } defer io.Close(f) - return true + stat, err := f.Stat() + if err != nil { + return false + } + return !stat.IsDir() } // newStaticAssetsHandler returns an HTTP handler to serve UI static assets
fix: basehref not set correctly (#<I>)
argoproj_argo-cd
train
104da0b86ed3fd70b08a81c7c54fd105efaf318f
diff --git a/pkg/build/strategies/sti/sti.go b/pkg/build/strategies/sti/sti.go index <HASH>..<HASH> 100644 --- a/pkg/build/strategies/sti/sti.go +++ b/pkg/build/strategies/sti/sti.go @@ -456,7 +456,7 @@ func (b *STI) Execute(command string, user string, config *api.Config) error { if err != nil { return err } - rmScript, err := util.CreateInjectedFilesRemovalScript(injectedFiles) + rmScript, err := util.CreateInjectedFilesRemovalScript(injectedFiles, "/tmp/rm-injections") if err != nil { return err } diff --git a/pkg/util/injection.go b/pkg/util/injection.go index <HASH>..<HASH> 100644 --- a/pkg/util/injection.go +++ b/pkg/util/injection.go @@ -42,7 +42,9 @@ func ExpandInjectedFiles(injections api.InjectionList) ([]string, error) { // CreateInjectedFilesRemovalScript creates a shell script that contains truncation // of all files we injected into the container. The path to the script is returned. -func CreateInjectedFilesRemovalScript(files []string) (string, error) { +// When the scriptName is provided, it is also truncated together with all +// secrets. +func CreateInjectedFilesRemovalScript(files []string, scriptName string) (string, error) { rmScript := "set -e\n" for _, s := range files { rmScript += fmt.Sprintf("truncate -s0 %q\n", s) @@ -52,6 +54,9 @@ func CreateInjectedFilesRemovalScript(files []string) (string, error) { if err != nil { return "", err } + if len(scriptName) > 0 { + rmScript += fmt.Sprintf("truncate -s0 %q", scriptName) + } rmScript += "set +e\n" err = ioutil.WriteFile(f.Name(), []byte(rmScript), 0700) return f.Name(), err diff --git a/pkg/util/injection_test.go b/pkg/util/injection_test.go index <HASH>..<HASH> 100644 --- a/pkg/util/injection_test.go +++ b/pkg/util/injection_test.go @@ -16,7 +16,7 @@ func TestCreateInjectedFilesRemovalScript(t *testing.T) { "/foo", "/bar/bar", } - name, err := CreateInjectedFilesRemovalScript(files) + name, err := CreateInjectedFilesRemovalScript(files, "/tmp/rm-foo") defer os.Remove(name) if err != nil { t.Errorf("Unexpected error: %v", name) @@ -32,6 +32,9 @@ func TestCreateInjectedFilesRemovalScript(t *testing.T) { if !strings.Contains(string(data), fmt.Sprintf("truncate -s0 %q", "/foo")) { t.Errorf("Expected script to contain truncate -s0 \"/foo\", got: %q", string(data)) } + if !strings.Contains(string(data), fmt.Sprintf("truncate -s0 %q", "/tmp/rm-foo")) { + t.Errorf("Expected script to truncate itself, got: %q", string(data)) + } } func TestExpandInjectedFiles(t *testing.T) {
Truncate the injection truncation script itself
openshift_source-to-image
train
295a26e8fdef5396031f6a19b87f3fa69c6c9bae
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Ruby core extentions and class utilities for Hanami ## v1.0.4 - 2017-10-02 ### Fixed +- [Luca Guidi] Make `Hanami::Utils::BasicObject` to be fully compatible with Ruby's `pp` and to be inspected by Pry. - [Thiago Kenji Okada] Fix pluralization/singularization for `"release" => "releases"` ## v1.0.3 - 2017-09-06 diff --git a/lib/hanami/utils/basic_object.rb b/lib/hanami/utils/basic_object.rb index <HASH>..<HASH> 100644 --- a/lib/hanami/utils/basic_object.rb +++ b/lib/hanami/utils/basic_object.rb @@ -21,7 +21,7 @@ module Hanami # # @see http://ruby-doc.org/core/Object.html#method-i-inspect def inspect - "#<#{self.class}:#{'%x' % (__id__ << 1)}#{__inspect}>" # rubocop:disable Style/FormatString + "#<#{self.class}:#{'0x0000%x' % (__id__ << 1)}#{__inspect}>" # rubocop:disable Style/FormatString end # Alias for __id__ @@ -37,13 +37,14 @@ module Hanami # Interface for pp # + # @param printer [PP] the Pretty Printable printer # @return [String] the pretty-printable inspection of the object # # @since 0.9.0 # # @see https://ruby-doc.org/stdlib/libdoc/pp/rdoc/PP.html - def pretty_print(*) - inspect + def pretty_print(printer) + printer.text(inspect) end # Returns true if responds to the given method. diff --git a/spec/unit/hanami/utils/basic_object_spec.rb b/spec/unit/hanami/utils/basic_object_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/hanami/utils/basic_object_spec.rb +++ b/spec/unit/hanami/utils/basic_object_spec.rb @@ -35,8 +35,19 @@ RSpec.describe Hanami::Utils::BasicObject do end end - # See https://github.com/hanami/hanami/issues/629 - it 'is pretty printable' do - pp TestClass.new + describe "#pretty_print" do + # See https://github.com/hanami/hanami/issues/629 + it 'is pretty printable' do + expect { pp TestClass.new }.to output(/TestClass/).to_stdout + end + + # See https://github.com/hanami/utils/issues/234 + it "outputs the inspection to the given printer" do + printer = PP.new + subject = TestClass.new + subject.pretty_print(printer) + + expect(printer.output).to match(/\A#<TestClass:\w+>\z/) + end end end
Make `Hanami::Utils::BasicObject` to be fully compatible with Ruby's `pp` and to be inspected by Pry. (#<I>)
hanami_utils
train
88ccbf3f93d7dfeefd2e1695c4115a535fd2d98a
diff --git a/package.js b/package.js index <HASH>..<HASH> 100644 --- a/package.js +++ b/package.js @@ -18,7 +18,9 @@ Package.onUse(function (api) { 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', - 'dist/fonts/glyphicons-halflings-regular.woff2', + 'dist/fonts/glyphicons-halflings-regular.woff2' + ], 'client', { isAsset: true }); + api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client');
Add support for Meteor <I>
twbs_bootstrap
train
1ea26cde6b0e3a9f06683674d10119f7d9a9c850
diff --git a/tests/Routing/RoutingAnnotationScannerTest.php b/tests/Routing/RoutingAnnotationScannerTest.php index <HASH>..<HASH> 100644 --- a/tests/Routing/RoutingAnnotationScannerTest.php +++ b/tests/Routing/RoutingAnnotationScannerTest.php @@ -8,7 +8,7 @@ class RoutingAnnotationScannerTest extends PHPUnit_Framework_TestCase { { require_once __DIR__.'/fixtures/annotations/BasicController.php'; $scanner = Scanner::create(['App\Http\Controllers\BasicController']); - $definition = $scanner->getRouteDefinitions(); + $definition = str_replace(PHP_EOL, "\n", $scanner->getRouteDefinitions()); $this->assertEquals(trim(file_get_contents(__DIR__.'/results/annotation-basic.php')), $definition); }
Fix RoutingAnnotationScannerTest on Windows.
laravel_framework
train
55cdee05657d10f542a2167de45dcf4a6d0a3d91
diff --git a/compile/compile.go b/compile/compile.go index <HASH>..<HASH> 100644 --- a/compile/compile.go +++ b/compile/compile.go @@ -437,6 +437,10 @@ func (c *Compiler) compileWasm(ctx context.Context) error { // Each entrypoint needs an entry in the manifest along with the // original rule(s) removed from the remaining rego modules. + + // For each package path keep a list of new imports. They are stored as a + // map to remove duplicates for each package. + requiredImports := map[string]map[string]*ast.Import{} for i, entrypoint := range c.entrypointrefs { entrypointPath := c.entrypoints[i] @@ -451,8 +455,19 @@ func (c *Compiler) compileWasm(ctx context.Context) error { // Drop any rules that match the entrypoint path. var rules []*ast.Rule for _, rule := range mf.Parsed.Rules { - if !rule.Path().Equal(entrypoint.Value) { + rulePath := rule.Path() + if !rulePath.Equal(entrypoint.Value) { rules = append(rules, rule) + } else { + pkgPath := rule.Module.Package.Path.String() + newImport := &ast.Import{Path: ast.NewTerm(rulePath)} + if _, ok := requiredImports[pkgPath]; ok { + requiredImports[pkgPath][rulePath.String()] = newImport + } else { + requiredImports[pkgPath] = map[string]*ast.Import{ + rulePath.String(): newImport, + } + } } } @@ -466,6 +481,18 @@ func (c *Compiler) compileWasm(ctx context.Context) error { } } + // Any packages which had rules removed need an import injected for the + // removed rule to keep the policies valid. + for i := 0; i < len(c.bundle.Modules); i++ { + mf := &c.bundle.Modules[i] + pkgPath := mf.Parsed.Package.Path.String() + if imports, ok := requiredImports[pkgPath]; ok { + mf.Raw = nil + for _, newImport := range imports { + mf.Parsed.Imports = append(mf.Parsed.Imports, newImport) + } + } + } return nil }
compile: Add import for removed entrypoints In addition to removing entrypoint rules we will now inject import statements into modules in the same package to maintain any usage of the older rules. Previously any usage of the older rules from the same package without using the fully qualified path would raise an error.
open-policy-agent_opa
train
2ca728ae9bc970cd2e8b9457c6a7c59c11d8003f
diff --git a/spec/support/redirect_server.rb b/spec/support/redirect_server.rb index <HASH>..<HASH> 100644 --- a/spec/support/redirect_server.rb +++ b/spec/support/redirect_server.rb @@ -9,13 +9,13 @@ module RSpec end def self.address - 'http://127.0.0.1:8201/' + 'http://127.0.0.1:8202/' end def self.start @server ||= begin server = WEBrick::HTTPServer.new( - Port: 8201, + Port: 8202, Logger: WEBrick::Log.new("/dev/null"), AccessLogs: [], )
Change redirect port to avoid Vault's cluster default.
hashicorp_vault-ruby
train
f7ff1bbb8b30f9724916b29e4a915e6f2a3e8770
diff --git a/pygubudesigner/__init__.py b/pygubudesigner/__init__.py index <HASH>..<HASH> 100644 --- a/pygubudesigner/__init__.py +++ b/pygubudesigner/__init__.py @@ -0,0 +1,12 @@ +import logging +import argparse + +# Setup logging level +parser = argparse.ArgumentParser() +parser.add_argument('filename') +parser.add_argument('--loglevel') +args = parser.parse_args() + +loglevel = str(args.loglevel).upper() +loglevel = getattr(logging, loglevel, logging.WARNING) +logging.basicConfig(level=loglevel) diff --git a/pygubudesigner/main.py b/pygubudesigner/main.py index <HASH>..<HASH> 100644 --- a/pygubudesigner/main.py +++ b/pygubudesigner/main.py @@ -47,31 +47,33 @@ from .i18n import translator from pygubu.widgets.accordionframe import AccordionFrame from pygubu.widgets.autoarrangeframe import AutoArrangeFrame import pygubu.widgets.simpletooltip as tooltip +import pygubudesigner from pygubudesigner.preferences import PreferencesUI, get_custom_widgets #translator function _ = translator -#initialize standard ttk widgets -import pygubu.builder.ttkstdwidgets - -#initialize extra widgets -widgets_pkg = 'pygubu.builder.widgets' -mwidgets = importlib.import_module(widgets_pkg) -mwpath = os.path.dirname(mwidgets.__file__) -for mfile in os.listdir(mwpath): - if mfile.endswith('.py') and not mfile.startswith('__'): - modulename = "{0}.{1}".format(widgets_pkg, mfile[:-3]) - importlib.import_module(modulename) - -#initialize custom widgets -for path in get_custom_widgets(): - dirname, fname = os.path.split(path) - if fname.endswith('.py'): - if dirname not in sys.path: - sys.path.append(dirname) - modulename = fname[:-3] - importlib.import_module(modulename) +def init_pygubu_widgets(): + #initialize standard ttk widgets + import pygubu.builder.ttkstdwidgets + + #initialize extra widgets + widgets_pkg = 'pygubu.builder.widgets' + mwidgets = importlib.import_module(widgets_pkg) + mwpath = os.path.dirname(mwidgets.__file__) + for mfile in os.listdir(mwpath): + if mfile.endswith('.py') and not mfile.startswith('__'): + modulename = "{0}.{1}".format(widgets_pkg, mfile[:-3]) + importlib.import_module(modulename) + + #initialize custom widgets + for path in get_custom_widgets(): + dirname, fname = os.path.split(path) + if fname.endswith('.py'): + if dirname not in sys.path: + sys.path.append(dirname) + modulename = fname[:-3] + importlib.import_module(modulename) #Initialize images DESIGNER_DIR = os.path.dirname(os.path.abspath(__file__)) @@ -83,8 +85,7 @@ StockImage.register_from_dir( os.path.join(IMAGES_DIR, 'widgets', '16x16'), '16x16-') #Initialize logger -logger = logging.getLogger('pygubu.designer') -logger.setLevel(logging.INFO) +logger = logging.getLogger(__name__) class StatusBarHandler(logging.Handler): @@ -121,6 +122,9 @@ FILE_PATH = os.path.dirname(os.path.abspath(__file__)) class PygubuUI(pygubu.TkApplication): """Main gui class""" + def _init_before(self): + init_pygubu_widgets() + def _create_ui(self): """Creates all gui widgets""" @@ -529,12 +533,7 @@ def start_pygubu(): app = PygubuUI(root) root.deiconify() - filename = None - if len(sys.argv) > 1: - farg = sys.argv[1] - if os.path.isfile(farg): - filename = farg - + filename = pygubudesigner.args.filename if filename is not None: app.load_file(filename)
Allow to specify loggin level from console command.
alejandroautalan_pygubu
train
e306b58443446fb8b525a84ba03cd424c5785af2
diff --git a/spec/behavior/generated-parser-behavior.spec.js b/spec/behavior/generated-parser-behavior.spec.js index <HASH>..<HASH> 100644 --- a/spec/behavior/generated-parser-behavior.spec.js +++ b/spec/behavior/generated-parser-behavior.spec.js @@ -1090,7 +1090,7 @@ describe("generated parser behavior", function() { 'start = line (nl+ line)*', 'line = digit (" "+ digit)*', 'digit = [0-9]', - 'nl = ("\\r" / "\\n" / "\\u2028" / "\\u2029")' + 'nl = [\\r\\n\\u2028\\u2029]' ].join("\n"), options); expect(parser).toFailToParse("1\n2\n\n3\n\n\n4 5 x", { @@ -1100,29 +1100,29 @@ describe("generated parser behavior", function() { }); /* Non-Unix newlines */ - expect(parser).toFailToParse("1\rx", { // Old Mac + expect(parser).toFailToParse("1\rx", { // Old Mac offset: 2, line: 2, column: 1 }); - expect(parser).toFailToParse("1\r\nx", { // Windows + expect(parser).toFailToParse("1\r\nx", { // Windows offset: 3, line: 2, column: 1 }); - expect(parser).toFailToParse("1\n\rx", { // mismatched + expect(parser).toFailToParse("1\n\rx", { // mismatched offset: 3, line: 3, column: 1 }); /* Strange newlines */ - expect(parser).toFailToParse("1\u2028x", { // line separator + expect(parser).toFailToParse("1\u2028x", { // line separator offset: 2, line: 2, column: 1 }); - expect(parser).toFailToParse("1\u2029x", { // paragraph separator + expect(parser).toFailToParse("1\u2029x", { // paragraph separator offset: 2, line: 2, column: 1
Behavior specs cleanup: Improve error reporting specs
pegjs_pegjs
train
4de9d8e63d1d6c963e2eec58d3b84abf064aa104
diff --git a/AbstractComponent.php b/AbstractComponent.php index <HASH>..<HASH> 100644 --- a/AbstractComponent.php +++ b/AbstractComponent.php @@ -26,6 +26,8 @@ extends Template */ public $composite_name_template = '{{parent_name}}[{{name}}]'; + public $html_classes = array(); + /** * Constructor * @@ -34,6 +36,12 @@ extends Template public function __construct( array $model = array() ) { parent::__construct($model); + + $this->add_html_class(sprintf( + 'amarkal-ui-component amarkal-ui-component-%s', + $this->component_type + )); + $this->on_created(); } @@ -89,7 +97,7 @@ extends Template /** * Get the name for this component by parsing the name template. * - * @return type + * @return string */ public function get_name() { @@ -97,13 +105,61 @@ extends Template } /** + * Add an HTML class to the list of HTML classes to be printed when the + * component is rendered. + * + * @param string $class + */ + public function add_html_class( $class ) + { + if( !in_array($class, $this->html_classes) ) + { + $this->html_classes[] = $class; + } + } + + /** + * Remove an HTML class to the list of HTML classes to be printed when the + * component is rendered. + * + * @param string $class + */ + public function remove_html_class( $class ) + { + $i = 0; + foreach( $this->html_classes as $c ) + { + if( $c === $class ) + { + array_splice($this->html_classes,$i,1); + break; + } + $i++; + } + } + + /** + * Set the validity of this component if it supports validation. + * + * @param type $validity + */ + Public function set_validity( $validity ) + { + $this->validity = $validity; + if($validity === $this::INVALID) + { + $this->add_html_class('amarkal-ui-component-error'); + } + } + + /** * Generate common UI component wrapper attributes */ public function component_attributes() { return sprintf( - 'class="amarkal-ui-component amarkal-ui-component-%s" amarkal-component-name="%s"', - $this->component_type, + 'class="%s" amarkal-component-name="%s"', + implode(' ', $this->html_classes), $this->name ); } diff --git a/Form.php b/Form.php index <HASH>..<HASH> 100644 --- a/Form.php +++ b/Form.php @@ -261,8 +261,8 @@ class Form { $this->errors[$name] = $error ? $error : ValidatableComponentInterface::DEFAULT_MESSAGE; $component->value = $this->old_instance[$name]; - $component->validity = $component::INVALID; $this->final_instance[$name] = $this->old_instance[$name]; + $component->set_validity($component::INVALID); } } } diff --git a/components/composite/script.js b/components/composite/script.js index <HASH>..<HASH> 100644 --- a/components/composite/script.js +++ b/components/composite/script.js @@ -3,16 +3,16 @@ Amarkal.UI.registerComponent('composite',{ // Given value must be an object (a PHP associative array) for(var key in values) { this.$el.find('[amarkal-component-name="'+key+'"]') - .amarkalUIcomponent('setValue', values[key]); + .amarkalUIComponent('setValue', values[key]); } }, getValue: function() { var values = {}; this.$el.find('.amarkal-ui-component').each(function(){ var name = $(this).attr('amarkal-component-name'); - $(this).amarkalUIcomponent(); + $(this).amarkalUIComponent(); - values[name] = $(this).amarkalUIcomponent('getValue'); + values[name] = $(this).amarkalUIComponent('getValue'); }); return values; },
Added option to add/remove HTML classes
amarkal_amarkal-ui
train
84c21ede3c4b90d9d0294e4b30e91fd7516c7243
diff --git a/mocpy/moc.py b/mocpy/moc.py index <HASH>..<HASH> 100644 --- a/mocpy/moc.py +++ b/mocpy/moc.py @@ -109,6 +109,8 @@ class MOC(AbstractMoc): pix_arr = np.array(list(self.best_res_pixels_iterator())) neighbour_pix_arr = AbstractMoc._neighbour_pixels(hp, pix_arr) + neighbour_pix_arr = np.setdiff1d(neighbour_pix_arr, pix_arr) + factor = 4 ** (self.HPY_MAX_NORDER - self.max_order) for pix in neighbour_pix_arr: self._interval_set.add((pix * factor, (pix + 1) * factor)) diff --git a/mocpy/tmoc.py b/mocpy/tmoc.py index <HASH>..<HASH> 100644 --- a/mocpy/tmoc.py +++ b/mocpy/tmoc.py @@ -166,6 +166,33 @@ class TimeMoc(AbstractMoc): self._interval_set.add((time_us_start, time_us_end)) + def add_neighbours(self): + """ + Add all the pixels at max order in the neighbourhood of the moc + + """ + import sys + time_delta = 4 ** (self.HPY_MAX_NORDER - self.max_order) + + for itv in sorted(self._interval_set.intervals): + self._interval_set.add((max(itv[0] - time_delta, 0), + min(itv[1] + time_delta, sys.maxsize))) + + def remove_neighbours(self): + """ + Remove all the pixels at max order located at the bound of the moc + + """ + time_delta = 4 ** (self.HPY_MAX_NORDER - self.max_order) + import sys + + intervals = sorted(self._interval_set.intervals) + + self._interval_set.clear() + for itv in intervals: + self._interval_set.add((min(itv[0] + time_delta, sys.maxsize), + max(itv[1] - time_delta, 0))) + def _get_max_pix(self, order): from sys import maxsize return maxsize
Add/remove neighbours for TimeMocs objects (at max_order)
cds-astro_mocpy
train
c809bad46d1f75b4184e6e7e65c15d707611b728
diff --git a/django_static/templatetags/django_static.py b/django_static/templatetags/django_static.py index <HASH>..<HASH> 100644 --- a/django_static/templatetags/django_static.py +++ b/django_static/templatetags/django_static.py @@ -33,6 +33,7 @@ else: _CAN_SYMLINK = getattr(settings, "DJANGO_STATIC_USE_SYMLINK", True) DEBUG = settings.DEBUG +DJANGO_STATIC = getattr(settings, 'DJANGO_STATIC', False) DJANGO_STATIC_SAVE_PREFIX = getattr(settings, 'DJANGO_STATIC_SAVE_PREFIX', '') DJANGO_STATIC_NAME_PREFIX = getattr(settings, 'DJANGO_STATIC_NAME_PREFIX', '') MEDIA_URL = getattr(settings, "DJANGO_STATIC_MEDIA_URL", None) @@ -182,7 +183,7 @@ class StaticFileNode(template.Node): def render(self, context): filename = self.filename_var.resolve(context) - if not getattr(settings, 'DJANGO_STATIC', False): + if not DJANGO_STATIC: if MEDIA_URL: return MEDIA_URL + filename return filename @@ -245,7 +246,20 @@ class StaticFilesNode(template.Node): which we already have routines for doing. """ code = self.nodelist.render(context) - if not getattr(settings, 'DJANGO_STATIC', False): + if not DJANGO_STATIC: + # Append MEDIA_URL if set + # quick and dirty + if MEDIA_URL: + for match in STYLES_REGEX.finditer(code): + for filename in match.groups(): + code = code.replace(filename, MEDIA_URL + filename) + + for match in SCRIPTS_REGEX.finditer(code): + for filename in match.groups(): + code = code.replace(filename, MEDIA_URL + filename) + + return code + return code new_js_filenames = [] @@ -332,7 +346,7 @@ def _static_file(filename, warn_no_file=True): """ """ - if not getattr(settings, 'DJANGO_STATIC', False): + if not DJANGO_STATIC: return file_proxy(filename, disabled=True) def wrap_up(filename):
One more fix for prepending DJANGO_STATIC_MEDIA_URL to filenames: If DJANGO_STATIC_MEDIA_URL is set, it will be prepended to the filename when DJANGO_STATIC is False. This fix makes that true also for the slimall and staticall tags.
peterbe_django-static
train
a0a63c9d5f08cfe4200fccbd7682fd51a54dc61a
diff --git a/src/frontend/org/voltcore/messaging/SocketJoiner.java b/src/frontend/org/voltcore/messaging/SocketJoiner.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltcore/messaging/SocketJoiner.java +++ b/src/frontend/org/voltcore/messaging/SocketJoiner.java @@ -57,6 +57,7 @@ import org.voltcore.utils.VersionChecker; import org.voltcore.utils.ssl.MessagingChannel; import org.voltcore.utils.ssl.SSLConfiguration; import org.voltdb.client.TLSHandshaker; +import org.voltdb.common.Constants; import org.voltdb.utils.MiscUtils; import com.google_voltpatches.common.collect.ImmutableMap; @@ -644,14 +645,13 @@ public class SocketJoiner { */ JSONObject jsObj; if (result.m_remnant != null) { - assert result.m_remnant.getInt() == result.m_remnant.remaining() - && result.m_remnant.hasArray() : "Remnant not array or not a single full message. remnant: " - + result.m_remnant + ", expected length: " - + result.m_remnant.getInt(result.m_remnant.position() - Integer.BYTES); - - jsObj = new JSONObject(new String(result.m_remnant.array(), - result.m_remnant.arrayOffset() + result.m_remnant.position(), result.m_remnant.remaining(), - StandardCharsets.UTF_8)); + int stringLength = result.m_remnant.getInt(); + if (stringLength != result.m_remnant.remaining()) { + throw new IllegalArgumentException( "Remnant not a single full message. remnant: " + + result.m_remnant + ", expected length: " + stringLength); + } + + jsObj = new JSONObject(Constants.UTF8ENCODING.decode(result.m_remnant).toString()); } else { jsObj = readJSONObjFromWire(messagingChannel); } diff --git a/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java b/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java +++ b/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java @@ -271,6 +271,7 @@ public class VoltProjectBuilder { boolean m_jsonApiEnabled = true; boolean m_sslEnabled = false; boolean m_sslExternal = false; + boolean m_sslInternal = false; boolean m_sslDR = false; String m_keystore; @@ -718,6 +719,10 @@ public class VoltProjectBuilder { m_sslExternal = enabled; } + public void setSslInternal(final boolean enabled) { + m_sslInternal = enabled; + } + public void setSslDR(final boolean enabled) { m_sslDR = enabled; } @@ -1290,6 +1295,7 @@ public class VoltProjectBuilder { deployment.setSsl(ssl); ssl.setEnabled(m_sslEnabled); ssl.setExternal(m_sslExternal); + ssl.setInternal(m_sslInternal); ssl.setDr(m_sslDR); if (m_keystore!=null) { KeyOrTrustStoreType store = factory.createKeyOrTrustStoreType(); diff --git a/tests/frontend/org/voltdb/TestSSL.java b/tests/frontend/org/voltdb/TestSSL.java index <HASH>..<HASH> 100644 --- a/tests/frontend/org/voltdb/TestSSL.java +++ b/tests/frontend/org/voltdb/TestSSL.java @@ -72,6 +72,8 @@ public class TestSSL extends JUnit4LocalClusterTest { builder.addStmtProcedure("SelectA", "SELECT * FROM T"); builder.setSslEnabled(true); builder.setSslExternal(true); + builder.setSslInternal(true); + return builder; }
ENG-<I>: Handle all byte buffers as remnant Correctly handle the remnant in SocketJoiner.processSSC. Update the handling so both heap and direct buffers can be used. Always read the size of the string from the buffer so that the string can be decoded when asserts are disabled. VoltProjectBuilder: Add method to be able to enable internal SSL.
VoltDB_voltdb
train
4bc92c8b3bc2335d28e4759b2241d053c6ae9112
diff --git a/docs/source/index.rst b/docs/source/index.rst index <HASH>..<HASH> 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -20,6 +20,18 @@ After downloading the directory, the package can be installed by running:: Changelog ========= +0.8.1 (2017-09-12) +------------------ + +* Introduced a function wrapper for `prior_transform` and `loglikelihood` + functions to allow users to pass `args` and `kwargs`. + +* Fixed a small bug that could cause bounding ellipsoids to fail. + +* Introduced a stability fix to the default + `~dynesty.dynamicsampler.weight_function` when computing evidence-based + weights. + 0.8.0 (2017-09-08) ------------------ diff --git a/dynesty/__init__.py b/dynesty/__init__.py index <HASH>..<HASH> 100644 --- a/dynesty/__init__.py +++ b/dynesty/__init__.py @@ -11,4 +11,4 @@ from . import utils from . import plotting -__version__ = "0.8.0" +__version__ = "0.8.1" diff --git a/dynesty/dynamicsampler.py b/dynesty/dynamicsampler.py index <HASH>..<HASH> 100644 --- a/dynesty/dynamicsampler.py +++ b/dynesty/dynamicsampler.py @@ -119,9 +119,12 @@ def weight_function(results, args=None, return_weights=False): logz = results.logz # final ln(evidence) logz_remain = results.logl[-1] + results.logvol[-1] # remainder logz_tot = np.logaddexp(logz[-1], logz_remain) # estimated upper bound - zin = np.exp(logz_tot) - np.exp(logz) # remaining evidence - zweight = zin / results.samples_n # evidence weight - zweight /= sum(zweight) # normalize + lzones = np.ones_like(logz) + logzin = misc.logsumexp([lzones * logz_tot, logz], axis=0, + b=[lzones, -lzones]) # ln(remaining evidence) + logzweight = logzin - np.log(results.samples_n) # ln(evidence weight) + logzweight -= misc.logsumexp(logzweight) # normalize + zweight = np.exp(logzweight) # convert to linear scale # Derive posterior weights. pweight = np.exp(results.logwt - results.logz[-1]) # importance weight diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ except ImportError: setup( name="dynesty", url="https://github.com/joshspeagle/dynesty", - version="0.8.0", + version="0.8.1", author="Josh Speagle", author_email="jspeagle@cfa.harvard.edu", packages=["dynesty"],
<I> New version release coinciding with a reasonable bugfix. Consolidates the previous few commits (related to #<I> and #<I>) and includes a further internal change to how evidence weights are computed in `weight_function` that should make computations much more stable (which led to problems in some testing).
joshspeagle_dynesty
train
d3e25ca14878dd5df73b213b5a40a73b3805b831
diff --git a/sandbox/library/tests.py b/sandbox/library/tests.py index <HASH>..<HASH> 100644 --- a/sandbox/library/tests.py +++ b/sandbox/library/tests.py @@ -33,6 +33,12 @@ class HashidTests(TestCase): self.assertEqual(len(h.hashid), 10) self.assertEqual(len(h), 10) + def test_hashable(self): + h = Hashid(987) + d = {h: "some value"} + self.assertEqual(d[h], "some value") + + class BookForm(forms.ModelForm): class Meta: model = Book
Test for using Hashid objects as keys in dictionaries (needed for many Django db operations, such as prefetch_related())
nshafer_django-hashid-field
train
b9b981871703a958197852a354c1e63b27029339
diff --git a/addon/components/visualizer-course-vocabularies.js b/addon/components/visualizer-course-vocabularies.js index <HASH>..<HASH> 100644 --- a/addon/components/visualizer-course-vocabularies.js +++ b/addon/components/visualizer-course-vocabularies.js @@ -5,7 +5,6 @@ import { restartableTask, timeout } from 'ember-concurrency'; import { inject as service } from '@ember/service'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; - import { use } from 'ember-could-get-used-to-this'; import ResolveAsyncValue from 'ilios-common/classes/resolve-async-value'; import AsyncProcess from 'ilios-common/classes/async-process'; @@ -18,25 +17,23 @@ export default class VisualizerCourseVocabularies extends Component { @use sessions = new ResolveAsyncValue(() => [this.args.course.sessions, []]); - @use dataObjects = new AsyncProcess(() => [ - this.getDataObjects.bind(this), - this.sessionsWithMinutes, - ]); - - get sessionsWithMinutes() { - return this.sessions.map((session) => { - return { - session, - minutes: Math.round(session.totalSumDuration * 60), - }; - }); - } + @use dataObjects = new AsyncProcess(() => [this.getDataObjects.bind(this), this.sessions]); get isLoaded() { return !!this.dataObjects; } - async getDataObjects(sessionsWithMinutes) { + async getDataObjects(sessions) { + if (!sessions) { + return []; + } + const sessionsWithMinutes = await map(sessions.toArray(), async (session) => { + const hours = await session.getTotalSumDuration(); + return { + session, + minutes: Math.round(hours * 60), + }; + }); return map(sessionsWithMinutes, async ({ session, minutes }) => { const terms = await session.terms; const vocabularies = await all(terms.mapBy('vocabulary')); diff --git a/addon/components/visualizer-course-vocabulary.js b/addon/components/visualizer-course-vocabulary.js index <HASH>..<HASH> 100644 --- a/addon/components/visualizer-course-vocabulary.js +++ b/addon/components/visualizer-course-vocabulary.js @@ -17,25 +17,23 @@ export default class VisualizerCourseVocabulary extends Component { @use sessions = new ResolveAsyncValue(() => [this.args.course.sessions, []]); - @use dataObjects = new AsyncProcess(() => [ - this.getDataObjects.bind(this), - this.sessionsWithMinutes, - ]); - - get sessionsWithMinutes() { - return this.sessions.map((session) => { - return { - session, - minutes: Math.round(session.totalSumDuration * 60), - }; - }); - } + @use dataObjects = new AsyncProcess(() => [this.getDataObjects.bind(this), this.sessions]); get isLoaded() { return !!this.dataObjects; } - async getDataObjects(sessionsWithMinutes) { + async getDataObjects(sessions) { + if (!sessions) { + return []; + } + const sessionsWithMinutes = await map(sessions.toArray(), async (session) => { + const hours = await session.getTotalSumDuration(); + return { + session, + minutes: Math.round(hours * 60), + }; + }); const terms = await map(sessionsWithMinutes, async ({ session, minutes }) => { const sessionTerms = await session.get('terms'); const sessionTermsInThisVocabulary = await filter(sessionTerms.toArray(), async (term) => {
corrects async data fetching/aggregation process.
ilios_common
train
aca3f48d2139b5aa8496981e60a75fdb341cdbb6
diff --git a/newsplease/__init__.py b/newsplease/__init__.py index <HASH>..<HASH> 100644 --- a/newsplease/__init__.py +++ b/newsplease/__init__.py @@ -4,6 +4,7 @@ import os sys.path.append(os.path.dirname(os.path.realpath(__file__))) from newsplease.pipeline.pipelines import InMemoryStorage from newsplease.single_crawler import SingleCrawler +import time class NewsPlease: @@ -19,10 +20,15 @@ class NewsPlease: :return: """ SingleCrawler.create_as_library(url) - results = InMemoryStorage.get_results() - article = results[url] - del results[url] - return article + while True: + results = InMemoryStorage.get_results() + if url in results: + article = results[url] + del results[url] + return article + else: + time.sleep(0.01) + @staticmethod def download_articles(urls): diff --git a/newsplease/single_crawler.py b/newsplease/single_crawler.py index <HASH>..<HASH> 100644 --- a/newsplease/single_crawler.py +++ b/newsplease/single_crawler.py @@ -23,6 +23,8 @@ from scrapy.utils.log import configure_logging from newsplease.config import CrawlerConfig from newsplease.config import JsonConfig from newsplease.helper import Helper +from _thread import start_new_thread +from twisted.internet.error import ReactorAlreadyRunning class SingleCrawler(object): @@ -57,7 +59,7 @@ class SingleCrawler(object): "crawler": "Download", "url": url } - cfg_file_path = os.environ['CColon'] + os.path.sep + 'config' + os.path.sep + 'config_lib.cfg' + cfg_file_path = os.path.dirname(__file__) + os.path.sep + 'config' + os.path.sep + 'config_lib.cfg' return cls(cfg_file_path, site, 0, False, False, True) def __init__(self, cfg_file_path, json_file_path, @@ -135,7 +137,15 @@ class SingleCrawler(object): self.load_crawler(crawler_class, site["url"], ignore_regex) - self.process.start() + + # start the job. if in library_mode, do not stop the reactor and so on after this job has finished + # so that further jobs can be executed. it also needs to run in a thread since the reactor.run method seems + # to not return. also, scrapy will attempt to start a new reactor, which fails with an exception, but + # the code continues to run. we catch this excepion in the function 'start_process'. + if library_mode: + start_new_thread(start_process, (self.process, False,)) + else: + self.process.start() def update_jobdir(self, site): """ @@ -240,6 +250,13 @@ class SingleCrawler(object): " initial.py or this crawler was daemonized.") +def start_process(process, stop_after_job): + try: + process.start(stop_after_job) + except ReactorAlreadyRunning: + pass + + if __name__ == "__main__": SingleCrawler(cfg_file_path=sys.argv[1], json_file_path=sys.argv[2],
fix bug that occurred when crawlin multiple articles
fhamborg_news-please
train
9610c1cadccb39b3fc0697e7bde7f33eee19ffeb
diff --git a/webdriver_test_tools/pageobject/modal.py b/webdriver_test_tools/pageobject/modal.py index <HASH>..<HASH> 100644 --- a/webdriver_test_tools/pageobject/modal.py +++ b/webdriver_test_tools/pageobject/modal.py @@ -6,16 +6,24 @@ from webdriver_test_tools.pageobject import utils, BasePage from webdriver_test_tools.webdriver import actions -# TODO: update docstring (see FormObject for ref) class ModalObject(BasePage): """Page object prototype for modals + Subclasses should set the following attributes: + + :var YAML_FILE: Path to a YAML file representing the modal object. This + file is parsed during initialization using :meth:`parse_yaml` and is + used to determine :attr:`MODAL_LOCATOR` and :attr:`CLOSE_LOCATOR` + :var MODAL_BODY_CLASS: (Optional) Page object for the contents of the modal + body. If set to a subclass of :class:`BasePage + <webdriver_test_tools.pageobject.base.BasePage>`, + :meth:`get_modal_body()` will return an instance of this object. + + The following attributes are determined based on the contents of + :attr:`YAML_FILE`: + :var MODAL_LOCATOR: Locator for the modal element. Override in subclasses :var CLOSE_LOCATOR: Locator for the close button. Override in subclasses - :var MODAL_BODY_CLASS: (Optional) Page object for the contents of the modal body. - If set to a subclass of - :class:`BasePage <webdriver_test_tools.pageobject.base.BasePage>`, - :meth:`get_modal_body()` will return an instance of this object. """ # Attribute with path to YAML file (parsed on __init__) @@ -59,9 +67,9 @@ class ModalObject(BasePage): """Check if the modal is displayed This method checks if the element located by :attr:`MODAL_LOCATOR` - exists and is visible. This should be sufficient for many common implementations - of modals, but can be overridden if this isn't a reliable detection - method for an implementation + exists and is visible. This should be sufficient for many common + implementations of modals, but can be overridden if this isn't a + reliable detection method for an implementation :return: True if the modal is displayed, False otherwise """ @@ -76,9 +84,10 @@ class ModalObject(BasePage): actions.scroll.to_and_click(self.driver, self.find_element(self.CLOSE_LOCATOR)) def get_modal_body(self): - """If :attr:`self.MODAL_BODY_CLASS <MODAL_BODY_CLASS>` is set to a subclass of - :class:`BasePage <webdriver_test_tools.pageobject.base.BasePage>`, - returns an instance of that object. Otherwise, returns None + """If :attr:`self.MODAL_BODY_CLASS <MODAL_BODY_CLASS>` is set to a + subclass of :class:`BasePage + <webdriver_test_tools.pageobject.base.BasePage>`, returns an instance + of that object. Otherwise, returns None """ return self.MODAL_BODY_CLASS(self.driver) if inspect.isclass(self.MODAL_BODY_CLASS) and issubclass(self.MODAL_BODY_CLASS, BasePage) else None
Updated ModalObject docstring
connordelacruz_webdriver-test-tools
train
0311107a077ea372527ae74839eec8042197332f
diff --git a/src/main/java/jcifs/ntlmssp/Type3Message.java b/src/main/java/jcifs/ntlmssp/Type3Message.java index <HASH>..<HASH> 100644 --- a/src/main/java/jcifs/ntlmssp/Type3Message.java +++ b/src/main/java/jcifs/ntlmssp/Type3Message.java @@ -96,12 +96,43 @@ public class Type3Message extends NtlmMessage { */ public Type3Message ( CIFSContext tc, Type2Message type2, String targetName, String password, String domain, String user, String workstation, int flags ) throws GeneralSecurityException, CIFSException { + // keep old behavior of anonymous auth when no password is provided + this(tc, type2, targetName, password, domain, user, workstation, flags, false); + } + + + /** + * Creates a Type-3 message in response to the given Type-2 message. + * + * @param tc + * context to use + * @param type2 + * The Type-2 message which this represents a response to. + * @param targetName + * SPN of the target system, optional + * @param password + * The password to use when constructing the response. + * @param domain + * The domain in which the user has an account. + * @param user + * The username for the authenticating user. + * @param workstation + * The workstation from which authentication is + * taking place. + * @param flags + * @param nonAnonymous + * actually perform authentication with empty password + * @throws GeneralSecurityException + * @throws CIFSException + */ + public Type3Message ( CIFSContext tc, Type2Message type2, String targetName, String password, String domain, String user, String workstation, + int flags, boolean nonAnonymous ) throws GeneralSecurityException, CIFSException { setFlags(flags | getDefaultFlags(tc, type2)); setWorkstation(workstation); setDomain(domain); setUser(user); - if ( password == null || password.length() == 0 ) { + if ( password == null || ( !nonAnonymous && password.length() == 0 ) ) { setLMResponse(null); setNTResponse(null); return; diff --git a/src/main/java/jcifs/smb/NtlmContext.java b/src/main/java/jcifs/smb/NtlmContext.java index <HASH>..<HASH> 100644 --- a/src/main/java/jcifs/smb/NtlmContext.java +++ b/src/main/java/jcifs/smb/NtlmContext.java @@ -272,7 +272,8 @@ public class NtlmContext implements SSPContext { this.auth.isGuest() ? "." : this.auth.getUserDomain(), this.auth.isGuest() ? "GUEST" : this.auth.getUsername(), this.workstation, - this.ntlmsspFlags); + this.ntlmsspFlags, + !this.auth.isAnonymous()); msg3.setupMIC(this.type1Bytes, token);
Allow authentication with empty password (#<I>) This adds another constructor to Type3Message to indicate that empty passwords should not be treated as anonymous.
AgNO3_jcifs-ng
train
3480b97eaa04abe548c65be3576c3cb8aaf64e01
diff --git a/lib/register/boot.rb b/lib/register/boot.rb index <HASH>..<HASH> 100644 --- a/lib/register/boot.rb +++ b/lib/register/boot.rb @@ -127,7 +127,7 @@ module Register :Method => {:name => :Word, :source => :Object, :instructions => :Object, :binary => :Object, :arguments => :List , :for_class => :Class, :locals => :List } , :Value => {}, - :Variable => {:type => :Class, :name => :Word , :value => :Object} + :Variable => {:value_type => :Class, :name => :Word , :value => :Object} } end diff --git a/lib/register/parfait/layout.rb b/lib/register/parfait/layout.rb index <HASH>..<HASH> 100644 --- a/lib/register/parfait/layout.rb +++ b/lib/register/parfait/layout.rb @@ -49,7 +49,7 @@ module Parfait # but now we are concerned with booting, ie getting a working structure def add_instance_variable name , type raise "Name shouldn't be nil" unless name - raise "Type shouldn't be nil" unless type + raise "Value Type shouldn't be nil" unless type self.push(name) self.push(type) self.get_length @@ -84,7 +84,7 @@ module Parfait end def type_at index - type_index = index * 2 + type_index = index * 2 get(type_index) end diff --git a/lib/register/parfait/variable.rb b/lib/register/parfait/variable.rb index <HASH>..<HASH> 100644 --- a/lib/register/parfait/variable.rb +++ b/lib/register/parfait/variable.rb @@ -3,14 +3,14 @@ module Parfait def initialize type , name , value = nil raise "not type #{type}(#{type.class})" unless Register.machine.space.get_class_by_name(type) - self.type , self.name , self.value = type , name , value - self.value = 0 if self.type == :Integer and value == nil + self.value_type , self.name , self.value = type , name , value + self.value = 0 if self.value_type == :Integer and value == nil raise "must give name for variable" unless name end - attributes [:type , :name, :value] + attributes [:value_type , :name, :value] def to_s - "Variable(#{self.type} ,#{self.name})" + "Variable(#{self.value_type} ,#{self.name})" end def inspect to_s diff --git a/lib/soml/compiler/name_expression.rb b/lib/soml/compiler/name_expression.rb index <HASH>..<HASH> 100644 --- a/lib/soml/compiler/name_expression.rb +++ b/lib/soml/compiler/name_expression.rb @@ -25,7 +25,7 @@ module Soml end # either an argument, so it's stored in message if( index = @method.has_arg(name)) - ret = use_reg @method.arguments[index].type + ret = use_reg @method.arguments[index].value_type add_code Register.get_slot(statement , :message , Parfait::Message.get_indexed(index), ret ) return ret else # or a local so it is in the frame @@ -33,7 +33,7 @@ module Soml if(index) frame = use_reg :Frame add_code Register.get_slot(statement , :message , :frame , frame ) - ret = use_reg @method.locals[index].type + ret = use_reg @method.locals[index].value_type add_code Register.get_slot(statement , frame , Parfait::Frame.get_indexed(index), ret ) return ret end
rename variable type to value_type in preparation for next rename
ruby-x_rubyx
train
35bc56eda86783a50facd594d1b50d60cdad87be
diff --git a/examples/tuneHHCell.py b/examples/tuneHHCell.py index <HASH>..<HASH> 100644 --- a/examples/tuneHHCell.py +++ b/examples/tuneHHCell.py @@ -22,34 +22,44 @@ if __name__ == '__main__': #above parameters will not be modified outside these bounds: min_constraints = [50, 10] max_constraints = [200, 60] - + + known_target_values = {'cell:hhcell/channelDensity:naChans/mS_per_cm2': 120, + 'cell:hhcell/channelDensity:kChans/mS_per_cm2': 36 } max_peak_no = 'hhpop[0]/v:max_peak_no' + average_maximum = 'hhpop[0]/v:average_maximum' + average_minimum = 'hhpop[0]/v:average_minimum' - weights = {max_peak_no: 1} + weights = {max_peak_no: 5, + average_maximum: 1, + average_minimum: 1} - target_data = {max_peak_no: 30} + target_data = {max_peak_no: 34, + average_maximum: 30.72, + average_minimum: -75} simulator = 'jNeuroML_NEURON' simulator = 'jNeuroML' - run_optimisation(prefix = 'TestHHpy', - neuroml_file = 'test_data/HHCellNetwork.net.nml', - target = 'HHCellNetwork', - parameters = parameters, - max_constraints = max_constraints, - min_constraints = min_constraints, - weights = weights, - target_data = target_data, - sim_time = 700, - population_size = 10, - max_evaluations = 20, - num_selected = 5, - num_offspring = 5, - mutation_rate = 0.5, - num_elites = 1, - simulator = simulator, - nogui = nogui) + run_optimisation(prefix = 'TestHHpy', + neuroml_file = 'test_data/HHCellNetwork.net.nml', + target = 'HHCellNetwork', + parameters = parameters, + max_constraints = max_constraints, + min_constraints = min_constraints, + weights = weights, + target_data = target_data, + sim_time = 700, + population_size = 20, + max_evaluations = 60, + num_selected = 10, + num_offspring = 10, + mutation_rate = 0.5, + num_elites = 3, + seed = 12345, + simulator = simulator, + nogui = nogui, + known_target_values = known_target_values) diff --git a/pyneuroml/tune/NeuroMLTuner.py b/pyneuroml/tune/NeuroMLTuner.py index <HASH>..<HASH> 100644 --- a/pyneuroml/tune/NeuroMLTuner.py +++ b/pyneuroml/tune/NeuroMLTuner.py @@ -38,7 +38,9 @@ DEFAULTS = {'simTime': 500, 'numElites': 1, 'seed': 12345, 'simulator': 'jNeuroML', + 'knownTargetValues': '{}', 'nogui': False, + 'showPlotAlready': True, 'verbose': False} @@ -157,11 +159,21 @@ def process_args(): default=DEFAULTS['simulator'], help="Simulator to run") + parser.add_argument('-knownTargetValues', + type=str, + metavar='<knownTargetValues>', + help="List of name/value pairs which represent the known values of the target parameters") + parser.add_argument('-nogui', action='store_true', default=DEFAULTS['nogui'], help="Should GUI elements be supressed?") + parser.add_argument('-showPlotAlready', + action='store_true', + default=DEFAULTS['showPlotAlready'], + help="Should generated plots be suppressed until show() called?") + parser.add_argument('-verbose', action='store_true', default=DEFAULTS['verbose'], @@ -332,9 +344,14 @@ def _run_optimisation(a): plt.xlabel("Time (ms)") plt.ylabel("Membrane potential(mV)") - plt.show() - - utils.plot_generation_evolution(sim_var.keys(), individuals_file_name = '%s/ga_individuals.csv'%run_dir) + utils.plot_generation_evolution(sim_var.keys(), + individuals_file_name = '%s/ga_individuals.csv'%run_dir, + target_values=a.known_target_values) + + if a.show_plot_already: + plt.show() + + return reportj
Retested HH cell tuner Adding more options on run_optimisation() to help plotting
NeuroML_pyNeuroML
train
f0ab71e1d8bf4d915fab59108b16fd665f5430ec
diff --git a/lib/jekyll-redirect-from/redirect_page.rb b/lib/jekyll-redirect-from/redirect_page.rb index <HASH>..<HASH> 100644 --- a/lib/jekyll-redirect-from/redirect_page.rb +++ b/lib/jekyll-redirect-from/redirect_page.rb @@ -15,7 +15,7 @@ module JekyllRedirectFrom @name = name self.process(name) - self.data = {} + self.data = { "layout" => nil } data.default_proc = proc do |_, key| site.frontmatter_defaults.find(File.join(dir, name), type, key)
Explicitly set layout to nil on redirect pages
jekyll_jekyll-redirect-from
train
b0c35455166c59d1b1bfb2d534eb071d2e7dc976
diff --git a/dallinger/experiment_server/experiment_server.py b/dallinger/experiment_server/experiment_server.py index <HASH>..<HASH> 100644 --- a/dallinger/experiment_server/experiment_server.py +++ b/dallinger/experiment_server/experiment_server.py @@ -60,6 +60,9 @@ app = Flask("Experiment_Server") @app.before_first_request def _config(): + app.config["SECRET_KEY"] = os.environ.get( + "FLASK_SECRET_KEY", "THIS IS A BAD SECRET" + ) config = get_config() if not config.ready: config.load() @@ -92,7 +95,6 @@ login.login_view = "dashboard.login" login.request_loader(dashboard.load_user_from_request) login.user_loader(dashboard.load_user) login.unauthorized_handler(dashboard.unauthorized) -app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY") app.config["dashboard_tabs"] = dashboard.dashboard_tabs """Basic routes.""" diff --git a/tests/test_deployment.py b/tests/test_deployment.py index <HASH>..<HASH> 100644 --- a/tests/test_deployment.py +++ b/tests/test_deployment.py @@ -558,6 +558,7 @@ class TestDeploySandboxSharedSetupNoExternalCalls(object): aws_secret_access_key="fake aws secret", DASHBOARD_USER="admin", DASHBOARD_PASSWORD=mock.ANY, # password is random + FLASK_SECRET_KEY=mock.ANY, # password is random smtp_password="fake email password", smtp_username="fake email username", whimsical=True, diff --git a/tests/test_experiment_server.py b/tests/test_experiment_server.py index <HASH>..<HASH> 100644 --- a/tests/test_experiment_server.py +++ b/tests/test_experiment_server.py @@ -56,6 +56,13 @@ class TestAppConfiguration(object): server.load_user_config() assert server.options["workers"] == u"2" + def test_flask_secret_loaded_from_environ(self, webapp): + import os + + os.environ["FLASK_SECRET_KEY"] = "A TEST SECRET KEY" + webapp.get("/") + assert webapp.application.config["SECRET_KEY"] == "A TEST SECRET KEY" + @pytest.mark.usefixtures("experiment_dir") @pytest.mark.slow
Test fixes. Move secret setting later in the app launch.
Dallinger_Dallinger
train
88dfbd9977c15331a8d3f05a38e88b3c69ecd579
diff --git a/uni_form/helpers.py b/uni_form/helpers.py index <HASH>..<HASH> 100644 --- a/uni_form/helpers.py +++ b/uni_form/helpers.py @@ -44,7 +44,6 @@ class Button(BaseInput): Note: The first argument is also slugified and turned into the id for the button. """ - input_type = 'button' field_classes = 'button' @@ -69,22 +68,35 @@ class Reset(BaseInput): def render_field(field, form, template="uni_form/field.html", labelclass=None): - if not isinstance(field, str): + """ + Renders a field, if the field is a django-uni-form object like a `Row` or a + `Fieldset`, calls its render method. The field is added to a list that the form + holds called `rendered_fields` to avoid double rendering fields. Finally a Django + form `BoundField` is instantiated, rendered and its html returned. + """ + if hasattr(field, 'render'): return field.render(form) + else: + # This allows fields to be unicode strings, always they don't use non ASCII + try: + field = str(field) + except UnicodeEncodeError: + raise Exception("Field '%s' is using forbidden unicode characters" % field) try: field_instance = form.fields[field] except KeyError: raise Exception("Could not resolve form field '%s'." % field) - bound_field = BoundField(form, field_instance, field) - html = render_to_string(template, {'field': bound_field, 'labelclass': labelclass}) + if not hasattr(form, 'rendered_fields'): form.rendered_fields = [] if not field in form.rendered_fields: form.rendered_fields.append(field) else: raise Exception("A field should only be rendered once: %s" % field) - return html + + bound_field = BoundField(form, field_instance, field) + return render_to_string(template, {'field': bound_field, 'labelclass': labelclass}) class Layout(object):
Refactoring render_field, documenting it and allowing unicode field names.
pydanny-archive_django-uni-form
train
b2f48e1c772c01dd6ce276342416142d25564c6d
diff --git a/src/ContentBundle/Block/Service/BreadcrumbsBlockService.php b/src/ContentBundle/Block/Service/BreadcrumbsBlockService.php index <HASH>..<HASH> 100644 --- a/src/ContentBundle/Block/Service/BreadcrumbsBlockService.php +++ b/src/ContentBundle/Block/Service/BreadcrumbsBlockService.php @@ -47,7 +47,7 @@ class BreadcrumbsBlockService extends AbstractBlockService implements BlockServi // add homepage link as first breadcrumb if not exists in breadcrumbs if (!array_key_exists('index', $parameters['breadcrumbs'])) { - $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getTitle()], $parameters['breadcrumbs']); + $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']); } return $parameters;
Get short title instead of title (#<I>) get the short title in the breadcrumbs, because the title can be long.
Opifer_Cms
train
4f9f7e6874d3f31410e732f46527d11358af2d3f
diff --git a/sanic_prometheus/__init__.py b/sanic_prometheus/__init__.py index <HASH>..<HASH> 100644 --- a/sanic_prometheus/__init__.py +++ b/sanic_prometheus/__init__.py @@ -77,7 +77,6 @@ def monitor(app, endpoint_type='url:1', async def before_response(request, response): if request.path != '/metrics': metrics.after_request_handler(m, request, response, get_endpoint) - return response # can't access the loop directly before Sanic starts get_loop_fn = lambda: app.loop
remove early return that kills other middlewares
dkruchinin_sanic-prometheus
train
d885a27ea1c8445137c653f5c563f8edfb56a82c
diff --git a/tests/tests.py b/tests/tests.py index <HASH>..<HASH> 100755 --- a/tests/tests.py +++ b/tests/tests.py @@ -16,6 +16,7 @@ class DNSTest(unittest.TestCase): def setUp(self): self.channel = pycares.Channel(timeout=10.0, tries=1, servers=['8.8.8.8', '8.8.4.4']) + self.is_ci = os.environ.get('APPVEYOR') or os.environ.get('TRAVIS') or os.environ.get('GITHUB_ACTION') def tearDown(self): self.channel = None @@ -36,7 +37,7 @@ class DNSTest(unittest.TestCase): self.channel.process_fd(pycares.ARES_SOCKET_BAD, fd) def assertNoError(self, errorno): - if errorno == pycares.errno.ARES_ETIMEOUT and (os.environ.get('APPVEYOR') or os.environ.get('TRAVIS')): + if errorno == pycares.errno.ARES_ETIMEOUT and self.is_ci: raise unittest.SkipTest('timeout') self.assertEqual(errorno, None)
test: add generic way to check for a CI
saghul_pycares
train
7920eb8475ad090c42f61f5051df8449ee9ccf1b
diff --git a/LiSE/LiSE/rule.py b/LiSE/LiSE/rule.py index <HASH>..<HASH> 100644 --- a/LiSE/LiSE/rule.py +++ b/LiSE/LiSE/rule.py @@ -367,14 +367,7 @@ class Rule(object): """ curtime = (branch, tick) = engine.time for trigger in self.triggers: - if not ( - trigger.__name__ in self._trigger_results_cache and - branch in self._trigger_results_cache[trigger.__name__] and - tick in self._trigger_results_cache[trigger.__name__][branch] and - args in self._trigger_results_cache[trigger.__name__][branch][tick] - ): - self._trigger_results_cache[trigger.__name__][branch][tick][args] = trigger(engine, *args) - result = self._trigger_results_cache[trigger.__name__][branch][tick][args] + result = trigger(engine, *args) if engine.time != curtime: engine.time = curtime if result: @@ -388,14 +381,7 @@ class Rule(object): """ curtime = (branch, tick) = engine.time for prereq in self.prereqs: - if not( - prereq.__name__ in self._prereq_results_cache and - branch in self._prereq_results_cache[prereq.__name__] and - tick in self._prereq_results_cache[prereq.__name__][branch] and - args in self._prereq_results_cache[prereq.__name__][branch][tick] - ): - self._prereq_results_cache[prereq.__name__][branch][tick][args] = prereq(self.engine, *args) - result = self._prereq_results_cache[prereq.__name__][branch][tick][args] + result = prereq(self.engine, *args) engine.time = curtime if not result: return False
Stop caching trigger and prereq results
LogicalDash_LiSE
train
11a31dff22dfaa87e9efa83de5bb823e1f98b39e
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ def readme_as_rest(): setup( name='zipline', - version='0.5.3', + version='0.5.4', description='A backtester for financial algorithms.', author='Quantopian Inc.', author_email='opensource@quantopian.com',
Updates release version to <I> Bugfix release. Notable fixes: - algorithm crashes due to missing data panel slots - slippage model getting out of sync with the algorithm.
quantopian_zipline
train
7c0eef082df719a96273d0b156077a0f10b68a78
diff --git a/osbs/http.py b/osbs/http.py index <HASH>..<HASH> 100644 --- a/osbs/http.py +++ b/osbs/http.py @@ -265,7 +265,10 @@ class PycurlAdapter(object): def request(self, url, method, data=None, kerberos_auth=False, allow_redirects=True, verify_ssl=True, use_json=False, headers=None, stream=False, username=None, password=None): - self.c.reset() + # FIXME: workaround for pycurl bug + # self.c.reset() + self._c = pycurl.Curl() + self.url = url headers = headers or {} method = method.lower()
http: create new pycurl instance instead of reset()
projectatomic_osbs-client
train
c6da8db4718714e5a369ecff8cb2abe251efe399
diff --git a/lib/jsduck/ast.rb b/lib/jsduck/ast.rb index <HASH>..<HASH> 100644 --- a/lib/jsduck/ast.rb +++ b/lib/jsduck/ast.rb @@ -59,7 +59,7 @@ module JsDuck # foo: function() {} elsif property?(ast) && function?(ast["value"]) - make_method(key_to_s(ast["key"]), ast["value"]) + make_method(key_value(ast["key"]), ast["value"]) else {:type => :property} @@ -175,15 +175,15 @@ module JsDuck h = {} if ast && ast["type"] == "ObjectExpression" ast["properties"].each do |p| - h[key_to_s(p["key"])] = p["value"] + h[key_value(p["key"])] = p["value"] end end return h end # Converts object expression property key to string value - def key_to_s(key) - key["type"] == "Identifier" ? key["name"] : key["value"] + def key_value(key) + @evaluator.key_value(key) end # Fully serializes the node diff --git a/lib/jsduck/evaluator.rb b/lib/jsduck/evaluator.rb index <HASH>..<HASH> 100644 --- a/lib/jsduck/evaluator.rb +++ b/lib/jsduck/evaluator.rb @@ -20,7 +20,7 @@ module JsDuck when "ObjectExpression" h = {} ast["properties"].each do |p| - key = p["key"]["type"] == "Identifier" ? p["key"]["name"] : to_value(p["key"]) + key = key_value(p["key"]) value = to_value(p["value"]) h[key] = value end @@ -32,6 +32,11 @@ module JsDuck end end + # Turns object property key into string value + def key_value(key) + key["type"] == "Identifier" ? key["name"] : key["value"] + end + end end
Refactor #key_value method into Evaluator.
senchalabs_jsduck
train
777c2a810d0776aa56c13d7d7af47a823fd7c609
diff --git a/Lib/glyphs2ufo/casting.py b/Lib/glyphs2ufo/casting.py index <HASH>..<HASH> 100644 --- a/Lib/glyphs2ufo/casting.py +++ b/Lib/glyphs2ufo/casting.py @@ -53,7 +53,7 @@ CUSTOM_FLOAT_PARAMS = frozenset(( CUSTOM_TRUTHY_PARAMS = frozenset(( 'isFixedPitch', 'postscriptForceBold', 'postscriptIsFixedPitch', - 'DisableAllAutomaticBehaviour')) + "Don't use Production Names", 'DisableAllAutomaticBehaviour')) CUSTOM_INTLIST_PARAMS = frozenset(( 'fsType', 'openTypeOS2CodePageRanges', 'openTypeOS2FamilyClass',
[casting] Add custom param for glyph naming
googlefonts_glyphsLib
train
ba5c524965bf4a77b0994127c686e3e2daf3bbe7
diff --git a/vcs/backends/base.py b/vcs/backends/base.py index <HASH>..<HASH> 100644 --- a/vcs/backends/base.py +++ b/vcs/backends/base.py @@ -324,7 +324,7 @@ class BaseChangeset(object): def last(self): if self.repository is None: raise ChangesetError("Cannot check if it's most recent revision") - return self.revision == self.repository.revisions[-1] + return self.raw_id == self.repository.revisions[-1] @LazyProperty def parents(self): @@ -336,14 +336,14 @@ class BaseChangeset(object): @LazyProperty def id(self): """ - Returns string identifing this changeset. + Returns string identifying this changeset. """ raise NotImplementedError @LazyProperty def raw_id(self): """ - Returns raw string identifing this changeset. + Returns raw string identifying this changeset. """ raise NotImplementedError @@ -351,14 +351,14 @@ class BaseChangeset(object): def short_id(self): """ Returns shortened version of ``raw_id`` attribute, as string, - identifing this changeset, useful for web representation. + identifying this changeset, useful for web representation. """ raise NotImplementedError @LazyProperty def revision(self): """ - Returns integer identifing this changeset. + Returns integer identifying this changeset. """ raise NotImplementedError
fixed last property in base. Some spelling fixes
codeinn_vcs
train
a393f10ac7a953e92f05174916a3f57db07ba95e
diff --git a/packages/node_modules/@ciscospark/plugin-credentials/test/unit/spec/credentials.js b/packages/node_modules/@ciscospark/plugin-credentials/test/unit/spec/credentials.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-credentials/test/unit/spec/credentials.js +++ b/packages/node_modules/@ciscospark/plugin-credentials/test/unit/spec/credentials.js @@ -375,7 +375,7 @@ describe(`plugin-credentials`, () => { assert.isDefined(spark.credentials.supertoken); return spark.credentials.logout() .then(() => { - assert.isUndefined(spark.credentials.supertoken.access_token); + assert.isUndefined(spark.credentials.supertoken); assert.notCalled(spark.credentials._redirect); }); }); @@ -395,7 +395,7 @@ describe(`plugin-credentials`, () => { assert.isDefined(spark.credentials.supertoken); return spark.credentials.logout({noRedirect: true}) .then(() => { - assert.isUndefined(spark.credentials.supertoken.access_token); + assert.isUndefined(spark.credentials.supertoken); assert.notCalled(spark.credentials._redirect); }); });
test(plugin-credentials): Fixes tests for logout changes
webex_spark-js-sdk
train
65ea114b0e0f007109af12712001f218427d3c1b
diff --git a/app/scripts/directives/vjs.directive.js b/app/scripts/directives/vjs.directive.js index <HASH>..<HASH> 100644 --- a/app/scripts/directives/vjs.directive.js +++ b/app/scripts/directives/vjs.directive.js @@ -15,34 +15,33 @@ angular.module('vjs.video', []) transclude: true, link: function postLink(scope, element, attrs, ctrl, transclude) { var vid = null; - if (element[0].nodeName === 'VIDEO') { - vid = element[0]; + if (!window.videojs) { + throw new Error('directive must be attached to a video tag!'); } - if (vid) { - if (window.videojs) { - //attach transcluded content - transclude(function (content) { - element.append(content); - }); - - //bootstrap videojs - window.videojs(vid, { - //options - }, function () { - - }); - - //dispose of videojs before destroying directive - scope.$on('$destroy', function () { - window.videojs(vid).dispose(); - }); - } else { - throw new Error('video.js was not found!'); - } + if (element[0].nodeName === 'VIDEO') { + vid = element[0]; } else { - throw new Error('directive must be attached to a video tag!'); + throw new Error('video.js was not found!'); } + + //attach transcluded content + transclude(function (content) { + element.append(content); + }); + + //bootstrap videojs + window.videojs(vid, { + //options + }, function () { + + }); + + //dispose of videojs before destroying directive + scope.$on('$destroy', function () { + window.videojs(vid).dispose(); + }); + } }; });
Refactored code to remove several nested if statements
arm0th_vjs-video
train
4e6b88afe0ad33c662b2857c4e4fe2e2693ccd17
diff --git a/scanpy/preprocessing/_deprecated/highly_variable_genes.py b/scanpy/preprocessing/_deprecated/highly_variable_genes.py index <HASH>..<HASH> 100644 --- a/scanpy/preprocessing/_deprecated/highly_variable_genes.py +++ b/scanpy/preprocessing/_deprecated/highly_variable_genes.py @@ -16,6 +16,8 @@ def filter_genes_dispersion(data, copy=False): """Extract highly variable genes [Satija15]_ [Zheng17]_. + This is a deprecated function. Use scanpy.api.highly_variable_genes instead. + If trying out parameters, pass the data matrix instead of AnnData. Depending on `flavor`, this reproduces the R-implementations of Seurat
add remark to docstring
theislab_scanpy
train
a9c1b18d253b6770a6b90b9c63e299086324299d
diff --git a/config/impl/src/main/java/org/jboss/windup/config/loader/WindupConfigurationLoaderImpl.java b/config/impl/src/main/java/org/jboss/windup/config/loader/WindupConfigurationLoaderImpl.java index <HASH>..<HASH> 100644 --- a/config/impl/src/main/java/org/jboss/windup/config/loader/WindupConfigurationLoaderImpl.java +++ b/config/impl/src/main/java/org/jboss/windup/config/loader/WindupConfigurationLoaderImpl.java @@ -76,10 +76,10 @@ public class WindupConfigurationLoaderImpl implements WindupRuleLoader executionMetadata.setProviders(providers); for (WindupRuleProvider provider : providers) { + // If there is a filter, and it rejects the ruleProvider, then skip this rule provider if (ruleProviderFilter != null && !ruleProviderFilter.accept(provider)) { - // if there is a filter, and it rejects the ruleProvider, then skip this rule provider - LOG.info(provider + " didn't pass the filter so is ignored."); + LOG.info("Skiped by filter: " + provider); continue; } @@ -94,7 +94,7 @@ public class WindupConfigurationLoaderImpl implements WindupRuleLoader if (rule instanceof Context) provider.enhanceMetadata((Context) rule); - if (rule instanceof RuleBuilder && StringUtils.isEmpty(rule.getId())) + if (rule instanceof RuleBuilder && StringUtils.isBlank(rule.getId())) { // set synthetic id ((RuleBuilder) rule).withId(generatedRuleID(provider, rule, i)); @@ -139,6 +139,7 @@ public class WindupConfigurationLoaderImpl implements WindupRuleLoader private String generatedRuleID(WindupRuleProvider provider, Rule rule, int idx) { - return "GeneratedID_" + provider.getID() + "_" + idx; + String provID = provider.getID().replace("org.jboss.windup.rules.", "w:"); + return "GeneratedID_" + provID + "_" + idx; } }
Change msgs (makes output a bit nicer and more readable)
windup_windup
train
caa1a4ee1c55ac788e2d95e94d953e29a24f8485
diff --git a/client/my-sites/checkout/composite-checkout/composite-checkout.js b/client/my-sites/checkout/composite-checkout/composite-checkout.js index <HASH>..<HASH> 100644 --- a/client/my-sites/checkout/composite-checkout/composite-checkout.js +++ b/client/my-sites/checkout/composite-checkout/composite-checkout.js @@ -48,7 +48,7 @@ import { fetchPaymentCountries } from 'state/countries/actions'; import { StateSelect } from 'my-sites/domains/components/form'; import ManagedContactDetailsFormFields from 'components/domains/contact-details-form-fields/managed-contact-details-form-fields'; import { getPlan } from 'lib/plans'; -import { getTld } from 'lib/domains'; +import { getTopLevelOfTld } from 'lib/domains'; import PageViewTracker from 'lib/analytics/page-view-tracker'; import { useStripe } from 'lib/stripe'; import CheckoutTerms from '../checkout/checkout-terms.jsx'; @@ -389,7 +389,7 @@ export default function CompositeCheckout( { ! hasDomainRegistration( responseCart ) && ! hasTransferProduct( responseCart ); const getIsFieldDisabled = () => isDisabled; - const tlds = getAllTlds( domainNames ); + const tlds = getAllTopLevelTlds( domainNames ); return ( <React.Fragment> @@ -756,8 +756,8 @@ function getAnalyticsPath( purchaseId, product, selectedSiteSlug, selectedFeatur return { analyticsPath, analyticsProps }; } -function getAllTlds( domainNames ) { - return Array.from( new Set( domainNames.map( getTld ) ) ).sort(); +function getAllTopLevelTlds( domainNames ) { + return Array.from( new Set( domainNames.map( getTopLevelOfTld ) ) ).sort(); } function displayRenewalSuccessNotice( responseCart, purchases, translate, moment ) {
Get top level TLD before deciding which cctld forms to display (#<I>) #<I> fixed a theretofore unnoticed bug that caused problems with multi level TLDs, like me.uk. This PR ports that fix to composite checkout. Note that composite checkout is not yet live in the countries and currencies most likely to have been affected by this.
Automattic_wp-calypso
train
71622a5c963b1fc397db523009c861efd09b6146
diff --git a/ayrton/execute.py b/ayrton/execute.py index <HASH>..<HASH> 100644 --- a/ayrton/execute.py +++ b/ayrton/execute.py @@ -162,7 +162,7 @@ class Command: try: os.execvpe (cmd, args, self.options['_env']) except FileNotFoundError: - sys.exit (127) + os._exit (127) def prepare_args (self, cmd, args, kwargs): ans= [cmd]
[*] os._exit() works better than sys.esit () :)
StyXman_ayrton
train