hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
0c9e78e2eeb880a3efd13f8e903ea210a7ee03d9
|
diff --git a/nova-client/src/main/java/com/woorea/openstack/nova/Nova.java b/nova-client/src/main/java/com/woorea/openstack/nova/Nova.java
index <HASH>..<HASH> 100644
--- a/nova-client/src/main/java/com/woorea/openstack/nova/Nova.java
+++ b/nova-client/src/main/java/com/woorea/openstack/nova/Nova.java
@@ -14,6 +14,7 @@ import com.woorea.openstack.nova.api.extensions.KeyPairsExtension;
import com.woorea.openstack.nova.api.extensions.SecurityGroupsExtension;
import com.woorea.openstack.nova.api.extensions.SnapshotsExtension;
import com.woorea.openstack.nova.api.extensions.VolumesExtension;
+import com.woorea.openstack.nova.api.extensions.HostsExtension;
public class Nova extends OpenStackClient {
@@ -39,6 +40,8 @@ public class Nova extends OpenStackClient {
private final QuotaSetsResource QUOTA_SETS;
+ private final HostsExtension HOSTS;
+
public Nova(String endpoint, OpenStackClientConnector connector) {
super(endpoint, connector);
EXTENSIONS = new ExtensionsResource(this);
@@ -52,6 +55,7 @@ public class Nova extends OpenStackClient {
VOLUMES = new VolumesExtension(this);
AGGREGATES = new AggregatesExtension(this);
QUOTA_SETS = new QuotaSetsResource(this);
+ HOSTS = new HostsExtension(this);
}
public Nova(String endpoint) {
@@ -101,4 +105,9 @@ public class Nova extends OpenStackClient {
public QuotaSetsResource quotaSets() {
return QUOTA_SETS;
}
+
+ public HostsExtension hosts() {
+ return HOSTS;
+ }
+
}
|
Add HostsExtension to class Nova(OpenStackClient), and enable "/os-hosts" operations.
|
woorea_openstack-java-sdk
|
train
|
7566315c7af0213c6c8c0958150114263307b08d
|
diff --git a/src/Composer/Package/Archiver/ArchiveManager.php b/src/Composer/Package/Archiver/ArchiveManager.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Package/Archiver/ArchiveManager.php
+++ b/src/Composer/Package/Archiver/ArchiveManager.php
@@ -72,7 +72,7 @@ class ArchiveManager
*/
public function getPackageFilename(PackageInterface $package)
{
- $nameParts = array(preg_replace('#[^a-z0-9-_.]#i', '-', $package->getName()));
+ $nameParts = array(preg_replace('#[^a-z0-9-_]#i', '-', $package->getName()));
if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) {
$nameParts = array_merge($nameParts, array($package->getDistReference(), $package->getDistType()));
|
Don't put dots in archive filenames they cause problems with PharData
composer/satis#<I>
|
mothership-ec_composer
|
train
|
3ae7b0a4bd378e470faa4964972ef06703dfc5c8
|
diff --git a/multiqc/plots/bargraph.py b/multiqc/plots/bargraph.py
index <HASH>..<HASH> 100644
--- a/multiqc/plots/bargraph.py
+++ b/multiqc/plots/bargraph.py
@@ -179,8 +179,9 @@ def plot (data, cats = None, pconfig = None):
if config.plots_force_flat or (not config.plots_force_interactive and len(plotsamples[0]) > config.plots_flat_numseries):
try:
return matplotlib_bargraph(plotdata, plotsamples, pconfig)
- except:
+ except Exception as e:
logger.error("############### Error making MatPlotLib figure! Falling back to HighCharts.")
+ logger.debug(e, exc_info=True)
return highcharts_bargraph(plotdata, plotsamples, pconfig)
else:
# Use MatPlotLib to generate static plots if requested
diff --git a/multiqc/plots/linegraph.py b/multiqc/plots/linegraph.py
index <HASH>..<HASH> 100644
--- a/multiqc/plots/linegraph.py
+++ b/multiqc/plots/linegraph.py
@@ -150,8 +150,9 @@ def plot (data, pconfig=None):
if config.plots_force_flat or (not config.plots_force_interactive and len(plotdata[0]) > config.plots_flat_numseries):
try:
return matplotlib_linegraph(plotdata, pconfig)
- except:
+ except Exception as e:
logger.error("############### Error making MatPlotLib figure! Falling back to HighCharts.")
+ logger.debug(e, exc_info=True)
return highcharts_linegraph(plotdata, pconfig)
else:
# Use MatPlotLib to generate static plots if requested
|
Log debug exception details in lineplot and bargraph when we hit an exception from matplotlib
|
ewels_MultiQC
|
train
|
ae47868273be2ee5a454d1ca0ef9599f9500612d
|
diff --git a/lib/record_store/record/ptr.rb b/lib/record_store/record/ptr.rb
index <HASH>..<HASH> 100644
--- a/lib/record_store/record/ptr.rb
+++ b/lib/record_store/record/ptr.rb
@@ -2,7 +2,12 @@ module RecordStore
class Record::PTR < Record
attr_accessor :ptrdname
- validate :validate_fqdn_inside_in_addr_arpa_zone
+ OCTET_LABEL_SEQUENCE_REGEX = /\A(([0-9]|[1-9][0-9]|[1-9][0-9][0-9])\.){1,4}/
+ IN_ADDR_ARPA_SUFFIX_REGEX = /in-addr\.arpa\.\z/
+ FQDN_FORMAT_REGEX = Regexp.new(OCTET_LABEL_SEQUENCE_REGEX.source + IN_ADDR_ARPA_SUFFIX_REGEX.source)
+
+ validates_format_of :fqdn, with: FQDN_FORMAT_REGEX
+ validate :validate_fqdn_octets_in_range
def initialize(record)
super
@@ -18,8 +23,16 @@ module RecordStore
ptrdname.to_s
end
- def validate_fqdn_inside_in_addr_arpa_zone
- errors.add(:fqdn, 'must be in the `in-addr.arpa.` zone') unless fqdn.end_with?('in-addr.arpa.')
+ def validate_fqdn_octets_in_range
+ OCTET_LABEL_SEQUENCE_REGEX.match(fqdn) do |m|
+ unless m.captures.all? { |o| o.to_d.between?(0, 255) }
+ errors.add(:fqdn, 'octet labels must be within the range 0-255')
+ end
+ end
+
+ unless IN_ADDR_ARPA_SUFFIX_REGEX.match?(fqdn)
+ errors.add(:fqdn, 'PTR records may only exist in the in-addr.arpa zone')
+ end
end
end
end
diff --git a/test/record_test.rb b/test/record_test.rb
index <HASH>..<HASH> 100644
--- a/test/record_test.rb
+++ b/test/record_test.rb
@@ -387,4 +387,36 @@ class RecordTest < Minitest::Test
ptrdname: 'a.root-servers.net.'
), :valid?)
end
+
+ def test_invalid_when_no_octets
+ refute_predicate(Record::PTR.new(
+ fqdn: 'in-addr.arpa',
+ ttl: 3600,
+ ptrdname: 'a.root-servers.net.'
+ ), :valid?)
+ end
+
+ def test_valid_when_between_one_to_four_octets
+ assert_predicate(Record::PTR.new(
+ fqdn: '111.22.3.in-addr.arpa',
+ ttl: 3600,
+ ptrdname: 'a.root-servers.net.'
+ ), :valid?)
+ end
+
+ def test_invalid_when_over_four_octets
+ refute_predicate(Record::PTR.new(
+ fqdn: '1.2.3.4.5.in-addr.arpa',
+ ttl: 3600,
+ ptrdname: 'a.root-servers.net.'
+ ), :valid?)
+ end
+
+ def test_invalid_when_octet_out_of_range
+ refute_predicate(Record::PTR.new(
+ fqdn: '256.in-addr.arpa',
+ ttl: 3600,
+ ptrdname: 'a.root-servers.net.'
+ ), :valid?)
+ end
end
|
Require PTR FQDNs to have 1-4 octets within 0-<I>
|
Shopify_record_store
|
train
|
e34924dc16baefa316f8ab4a2e5b92516527cfd8
|
diff --git a/sources/elasticsearch/logs2dataflow.py b/sources/elasticsearch/logs2dataflow.py
index <HASH>..<HASH> 100755
--- a/sources/elasticsearch/logs2dataflow.py
+++ b/sources/elasticsearch/logs2dataflow.py
@@ -306,9 +306,14 @@ hosts_buckets, bytes_transfered = get_log_aggregate(
)
graph = []
+max_count = max(hosts_buckets.values())
+bytes_per_req = 1. * bytes_transfered['sum'] / bytes_transfered['count']
+
for host, count in hosts_buckets.iteritems():
graph.append('{source}\t{edge}\t{target}\t{value:.4f}\t{metadata}'.format(
- source='web:shops', edge='http fetch', target='bots:{}'.format(host), value=1.0, metadata='{:.4f} requests/hour'.format(1.)))
+ source='web:shops', edge='http fetch', target='bots:{}'.format(host), value=1.0 * count / max_count,
+ metadata='{reqs:.0f} requests/hour, {gibs:.2f} GiB/hour'.format(reqs=1. * count / 24, gibs=bytes_per_req * count / 1024 / 1024 / 1024 / 24)
+ ))
print('# bots HTTP traffic')
print("\n".join(set(graph)))
|
Analyze bots traffic
Resolves #9
|
macbre_data-flow-graph
|
train
|
00883fc4099e7155f709a19b4d98085c282d8df9
|
diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Console/Tests/ApplicationTest.php
+++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php
@@ -41,6 +41,13 @@ class ApplicationTest extends TestCase
{
protected static $fixturesPath;
+ private $colSize;
+
+ protected function setUp()
+ {
+ $this->colSize = getenv('COLUMNS');
+ }
+
public static function setUpBeforeClass()
{
self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
@@ -383,6 +390,7 @@ class ApplicationTest extends TestCase
*/
public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
{
+ putenv('COLUMNS=120');
if (method_exists($this, 'expectException')) {
$this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException');
$this->expectExceptionMessage($expectedExceptionMessage);
@@ -468,6 +476,7 @@ class ApplicationTest extends TestCase
public function testFindAlternativeExceptionMessageMultiple()
{
+ putenv('COLUMNS=120');
$application = new Application();
$application->add(new \FooCommand());
$application->add(new \Foo1Command());
@@ -1692,6 +1701,7 @@ class ApplicationTest extends TestCase
protected function tearDown()
{
+ putenv($this->colSize ? 'COLUMNS' : 'COLUMNS='.$this->colSize);
putenv('SHELL_VERBOSITY');
unset($_ENV['SHELL_VERBOSITY']);
unset($_SERVER['SHELL_VERBOSITY']);
diff --git a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php
+++ b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php
@@ -21,6 +21,19 @@ use Symfony\Component\Console\Output\StreamOutput;
*/
class ProgressBarTest extends TestCase
{
+ private $colSize;
+
+ protected function setUp()
+ {
+ $this->colSize = getenv('COLUMNS');
+ putenv('COLUMNS=120');
+ }
+
+ protected function tearDown()
+ {
+ putenv($this->colSize ? 'COLUMNS' : 'COLUMNS='.$this->colSize);
+ }
+
public function testMultipleStart()
{
$bar = new ProgressBar($output = $this->getOutputStream());
diff --git a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php
+++ b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php
@@ -26,9 +26,11 @@ class SymfonyStyleTest extends TestCase
protected $command;
/** @var CommandTester */
protected $tester;
+ private $colSize;
protected function setUp()
{
+ $this->colSize = getenv('COLUMNS');
putenv('COLUMNS=121');
$this->command = new Command('sfstyle');
$this->tester = new CommandTester($this->command);
@@ -36,7 +38,7 @@ class SymfonyStyleTest extends TestCase
protected function tearDown()
{
- putenv('COLUMNS');
+ putenv($this->colSize ? 'COLUMNS' : 'COLUMNS='.$this->colSize);
$this->command = null;
$this->tester = null;
}
diff --git a/src/Symfony/Component/Console/Tests/TerminalTest.php b/src/Symfony/Component/Console/Tests/TerminalTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Console/Tests/TerminalTest.php
+++ b/src/Symfony/Component/Console/Tests/TerminalTest.php
@@ -16,6 +16,15 @@ use Symfony\Component\Console\Terminal;
class TerminalTest extends TestCase
{
+ private $colSize;
+ private $lineSize;
+
+ protected function setUp()
+ {
+ $this->colSize = getenv('COLUMNS');
+ $this->lineSize = getenv('LINES');
+ }
+
public function test()
{
putenv('COLUMNS=100');
@@ -31,6 +40,12 @@ class TerminalTest extends TestCase
$this->assertSame(60, $terminal->getHeight());
}
+ protected function tearDown()
+ {
+ putenv($this->colSize ? 'COLUMNS' : 'COLUMNS='.$this->colSize);
+ putenv($this->lineSize ? 'LINES' : 'LINES='.$this->lineSize);
+ }
+
public function test_zero_values()
{
putenv('COLUMNS=0');
|
Make tests independent from each other
Environment variables set in a test need to be restored to their
previous values or unset if we want to be able to run tests
independently.
|
symfony_symfony
|
train
|
35268b43a315b2d44d9912159f189e2b80c610cf
|
diff --git a/nodeconductor/cost_tracking/admin.py b/nodeconductor/cost_tracking/admin.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/cost_tracking/admin.py
+++ b/nodeconductor/cost_tracking/admin.py
@@ -1,4 +1,3 @@
-from django.conf.urls import patterns, url
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.contenttypes.models import ContentType
|
Remove leftover imports (NC-<I>)
|
opennode_waldur-core
|
train
|
4abf76cf85609854216d639769c7bb6c1a8baa7f
|
diff --git a/dockermake/builds.py b/dockermake/builds.py
index <HASH>..<HASH> 100644
--- a/dockermake/builds.py
+++ b/dockermake/builds.py
@@ -120,7 +120,7 @@ class BuildTarget(object):
def _get_stack_key(self, istep):
names = [self.from_image]
- for i in xrange(istep+1):
+ for i in range(istep+1):
step = self.steps[i]
if isinstance(step, FileCopyStep):
continue
|
Fix cache busting in python 3
|
avirshup_DockerMake
|
train
|
bbffce8ef9eb07d19c224f5361c4af1ce10ee845
|
diff --git a/liquibase-core/src/main/java/liquibase/change/core/AddUniqueConstraintChange.java b/liquibase-core/src/main/java/liquibase/change/core/AddUniqueConstraintChange.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/change/core/AddUniqueConstraintChange.java
+++ b/liquibase-core/src/main/java/liquibase/change/core/AddUniqueConstraintChange.java
@@ -253,6 +253,7 @@ public class AddUniqueConstraintChange extends AbstractChange {
inverse.setSchemaName(getSchemaName());
inverse.setTableName(getTableName());
inverse.setConstraintName(getConstraintName());
+ inverse.setUniqueColumns(getColumnNames());
return new Change[]{
inverse,
|
CORE-<I>: Revert Unique Index failed for SQLAnywhere
|
liquibase_liquibase
|
train
|
ca541fe73dbc81ebd311c2426e1547c0f27c2330
|
diff --git a/src/main/java/com/dlsc/preferencesfx/PreferencesFx.java b/src/main/java/com/dlsc/preferencesfx/PreferencesFx.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/dlsc/preferencesfx/PreferencesFx.java
+++ b/src/main/java/com/dlsc/preferencesfx/PreferencesFx.java
@@ -136,6 +136,10 @@ public class PreferencesFx {
*/
public PreferencesFx saveSettings(boolean save) {
preferencesFxModel.setSaveSettings(save);
+ // if settings shouldn't be saved, clear them if there are any present
+ if (!save) {
+ preferencesFxModel.getStorageHandler().clearPreferences();
+ }
return this;
}
diff --git a/src/main/java/com/dlsc/preferencesfx/util/StorageHandler.java b/src/main/java/com/dlsc/preferencesfx/util/StorageHandler.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/dlsc/preferencesfx/util/StorageHandler.java
+++ b/src/main/java/com/dlsc/preferencesfx/util/StorageHandler.java
@@ -14,6 +14,7 @@ import static com.dlsc.preferencesfx.util.Constants.WINDOW_WIDTH;
import com.google.gson.Gson;
import java.util.ArrayList;
+import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
@@ -185,8 +186,24 @@ public class StorageHandler {
return FXCollections.observableArrayList(gson.fromJson(json, ArrayList.class));
}
+ /**
+ * Clears the preferences.
+ * @return true if successful, false if there was an exception.
+ */
+ public boolean clearPreferences() {
+ try {
+ preferences.clear();
+ } catch (BackingStoreException e) {
+ return false;
+ }
+ return true;
+ }
+
public Preferences getPreferences() {
return preferences;
}
+
+
+
}
|
StorageHandler: added method to clear the preferences
PreferencesFx: clear the preferences if there are any, if saveSettings is set to false
|
dlemmermann_PreferencesFX
|
train
|
7447eac5ef1c7175e1734e507c132fae9e38515e
|
diff --git a/src/s9e/TextFormatter/Plugins/MarkdownLite/Parser.php b/src/s9e/TextFormatter/Plugins/MarkdownLite/Parser.php
index <HASH>..<HASH> 100644
--- a/src/s9e/TextFormatter/Plugins/MarkdownLite/Parser.php
+++ b/src/s9e/TextFormatter/Plugins/MarkdownLite/Parser.php
@@ -48,15 +48,26 @@ class Parser extends ParserBase
if (!$spn)
{
+ // NOTE: might be the continuation of a quote :\
continue;
}
+ preg_match_all(
+ '/> ?|\\* *\\* *\\*[* ]*$|- *- *-[- ]*$|[-*+] |\\d\\. |#+$/S',
+ substr($line, 0, $spn),
+ $matches
+ );
+
// Blockquote: ">" or "> "
- // List item: "* " preceded by any number of spaces
- // List item: "- " preceded by any number of spaces
- // List item: "+ " preceded by any number of spaces
+ // List item: "* "
+ // List item: "- "
+ // List item: "+ "
// List item: at least one digit followed by ". "
- // HR: "* * *" or "- - -" or "***" or "---"
+ // HR: At least three * or - alone on a line, with any number of spaces between
+ // Headings: #+ alone on a line
+ // Headings: possibly any number of - or = alone on a line
+ //
+ // NOTE: apparently the only elements allowed after a list item are more list items
}
// Inline code
|
MarkdownLite: saved notes [ci skip]
|
s9e_TextFormatter
|
train
|
c70c2ea0d97b8c82a67043a796dad03fad757826
|
diff --git a/parsl/app/errors.py b/parsl/app/errors.py
index <HASH>..<HASH> 100644
--- a/parsl/app/errors.py
+++ b/parsl/app/errors.py
@@ -23,3 +23,39 @@ class AppException(ParslError):
What this exception contains depends entirely on context
'''
pass
+
+class AppFailure(ParslError):
+ ''' An error raised during execution of an app.
+ What this exception contains depends entirely on context
+ Contains:
+ reason (string)
+ exitcode (int)
+ retries (int/None)
+ '''
+
+ def __init__(self, reason, exitcode, retries=None):
+ self.reason = reason
+ self.exitcode = exitcode
+ self.retries = retries
+
+
+class MissingOutputs(ParslError):
+ ''' Error raised at the end of app execution due to missing
+ output files
+
+ Contains:
+ reason (string)
+ outputs (List of strings/files..)
+ '''
+
+ def __init__(self, reason, outputs):
+ self.reason = reason
+ self.outputs = outputs
+
+ def __repr__ (self):
+ return "Missing Outputs: {0}, Reason:{1}".format(self.outputs, self.reason)
+
+ def __str__ (self):
+ return "Reason:{0} Missing:{1}".format(self.reason, self.outputs)
+
+
|
Exception for exit failures vs missing outputs failures
|
Parsl_parsl
|
train
|
b8ae02a6c68df083b008e911ddaf95948d5afa28
|
diff --git a/lib/Doctrine/DBAL/Migrations/Tools/Console/Command/DiffCommand.php b/lib/Doctrine/DBAL/Migrations/Tools/Console/Command/DiffCommand.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/DBAL/Migrations/Tools/Console/Command/DiffCommand.php
+++ b/lib/Doctrine/DBAL/Migrations/Tools/Console/Command/DiffCommand.php
@@ -118,7 +118,7 @@ EOT
$currentPlatform = $configuration->getConnection()->getDatabasePlatform()->getName();
$code = array();
foreach ($sql as $query) {
- if (strpos($query, $configuration->getMigrationsTableName()) !== false) {
+ if (stripos($query, $configuration->getMigrationsTableName()) !== false) {
continue;
}
$code[] = sprintf("\$this->addSql(%s);", var_export($query, true));
|
migrationsTableName should be case insensitive
Oracle returns all table names UPPERCASE, so this check fails and migrationsTable is included to every migration.
|
doctrine_migrations
|
train
|
ea2211c145294d2ba001e59cd4f5759af75d1343
|
diff --git a/src/Utilities/LocalesManager.php b/src/Utilities/LocalesManager.php
index <HASH>..<HASH> 100644
--- a/src/Utilities/LocalesManager.php
+++ b/src/Utilities/LocalesManager.php
@@ -381,7 +381,8 @@ class LocalesManager implements LocalesManagerInterface
$currentLocale = $this->getCurrentLocaleEntity();
if ( ! empty($regional = $currentLocale->regional())) {
- setlocale(LC_TIME, $regional . '.utf8');
+ setlocale(LC_TIME, "$regional.UTF-8");
+ setlocale(LC_MONETARY, "$regional.UTF-8");
}
}
}
|
Updating/Fixing the regional stuff (LC_TIME and LC_MONETARY)
|
ARCANEDEV_Localization
|
train
|
fe3af0f030e7fe222a1427b4bdfb3ea7389e121b
|
diff --git a/eppy/runner/run_functions.py b/eppy/runner/run_functions.py
index <HASH>..<HASH> 100644
--- a/eppy/runner/run_functions.py
+++ b/eppy/runner/run_functions.py
@@ -87,7 +87,7 @@ def multirunner(args):
run(*args[0], **args[1])
-def run(idf=None, weather=None, output_directory='run_outputs', annual=False,
+def run(idf=None, weather=None, output_directory='', annual=False,
design_day=False, idd=None, epmacro=False, expandobjects=False,
readvars=False, output_prefix=None, output_suffix=None, version=False,
verbose='v'):
@@ -103,7 +103,8 @@ def run(idf=None, weather=None, output_directory='run_outputs', annual=False,
Full or relative path to the weather file.
output_directory : str, optional
- Full or relative path to an output directory (default: 'run_outputs)
+ Full or relative path to an output directory (default: current
+ directory)
annual : bool, optional
If True then force annual simulation (default: False)
|
Default output folder for IDF5.run() is current directory
This is to match the behaviour of the CLI.
|
santoshphilip_eppy
|
train
|
ddfb8d9fa67b98d84a8bfa4e6ad1dbc102cc5e42
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -17,7 +17,7 @@ module.exports = function(db) {
throw new Error('Not enough arguments');
}
- if (args.length == 1) return arguments[0];
+ if (args.length == 1) return '!' + arguments[0];
var key = args.pop();
return '!' + args.join('#') + '!' + key;
|
Update index.js
If top level, should return with an exclamation as well.
|
heapwolf_level-key
|
train
|
9406810d2075cf18cf1ac5464a34739d893dabdb
|
diff --git a/tests/test_parse_requirements.py b/tests/test_parse_requirements.py
index <HASH>..<HASH> 100644
--- a/tests/test_parse_requirements.py
+++ b/tests/test_parse_requirements.py
@@ -239,12 +239,13 @@ def test_parse_requirements_with_environment_markers(monkeypatch):
def test_parse_requirements_with_invalid_wheel_filename(monkeypatch):
+ INVALID_WHEEL_NAME = "pip-1.3.1-invalid-format.whl"
files = {
- "a.txt": ["https://github.com/pypa/pip/archive/pip-1.3.1-invalid-format.whl"]
+ "a.txt": ["https://github.com/pypa/pip/archive/" + INVALID_WHEEL_NAME],
}
monkeypatch.setattr(pip_api._parse_requirements, "_read_file", files.get)
- with pytest.raises(PipError):
+ with pytest.raises(PipError, match=r"Invalid wheel name: " + INVALID_WHEEL_NAME):
pip_api.parse_requirements("a.txt")
@@ -255,5 +256,7 @@ def test_parse_requirements_with_missing_egg_suffix(monkeypatch):
}
monkeypatch.setattr(pip_api._parse_requirements, "_read_file", files.get)
- with pytest.raises(PipError):
+ with pytest.raises(
+ PipError, match=r"Missing egg fragment in URL: " + PEP508_PIP_EXAMPLE_URL
+ ):
pip_api.parse_requirements("a.txt")
|
Assert on `PipError` messages in requirements parsing tests
|
di_pip-api
|
train
|
36cc2ac1a941e9a6f521ffdfc00c8ee34af33b40
|
diff --git a/validator/sawtooth_validator/journal/consensus/poet1/poet_consensus.py b/validator/sawtooth_validator/journal/consensus/poet1/poet_consensus.py
index <HASH>..<HASH> 100644
--- a/validator/sawtooth_validator/journal/consensus/poet1/poet_consensus.py
+++ b/validator/sawtooth_validator/journal/consensus/poet1/poet_consensus.py
@@ -912,7 +912,7 @@ class PoetConsensus(object):
def create_block_message(self, block):
msg = poet_transaction_block.PoetTransactionBlockMessage()
- msg.TransactionBlock = block
+ msg.transaction_block = block
return msg
def build_certificate_list(self, block_store, block):
diff --git a/validator/sawtooth_validator/journal/consensus/poet1/poet_transaction_block.py b/validator/sawtooth_validator/journal/consensus/poet1/poet_transaction_block.py
index <HASH>..<HASH> 100644
--- a/validator/sawtooth_validator/journal/consensus/poet1/poet_transaction_block.py
+++ b/validator/sawtooth_validator/journal/consensus/poet1/poet_transaction_block.py
@@ -63,7 +63,7 @@ class PoetTransactionBlockMessage(
super(PoetTransactionBlockMessage, self).__init__(minfo)
tinfo = minfo.get('TransactionBlock', {})
- self.TransactionBlock = PoetTransactionBlock(tinfo)
+ self.transaction_block = PoetTransactionBlock(tinfo)
class PoetTransactionBlock(transaction_block.TransactionBlock):
|
Workaround pylint invalid-name error
Renames the TransactionBlock attribute to transaction_block.
This change isn't necessarily a real fix or 'correct' per-se, but there
doesn't appear to be any code remaining that references these fields, so
it should be an okay workaround until PoET is integrated with the
validator.
|
hyperledger_sawtooth-core
|
train
|
ca19d7082e9b714554679f16e78e800f01c912d1
|
diff --git a/graph/Schema.java b/graph/Schema.java
index <HASH>..<HASH> 100644
--- a/graph/Schema.java
+++ b/graph/Schema.java
@@ -19,6 +19,7 @@
package hypergraph.graph;
import javax.annotation.Nullable;
+import java.time.LocalDateTime;
public class Schema {
@@ -101,10 +102,10 @@ public class Schema {
PROPERTY_LABEL(0),
PROPERTY_SCOPE(1),
PROPERTY_ABSTRACT(2),
- PROPERTY_DATATYPE(3),
- PROPERTY_REGEX(4),
- PROPERTY_VALUE(5),
- PROPERTY_VALUE_REF(6),
+ PROPERTY_REGEX(3),
+ PROPERTY_VALUE_TYPE(4),
+ PROPERTY_VALUE_REF(5),
+ PROPERTY_VALUE(6),
PROPERTY_WHEN(7),
PROPERTY_THEN(8),
EDGE_SUB_OUT(20),
@@ -167,10 +168,10 @@ public class Schema {
LABEL(Infix.PROPERTY_LABEL),
SCOPE(Infix.PROPERTY_SCOPE),
ABSTRACT(Infix.PROPERTY_ABSTRACT),
- DATATYPE(Infix.PROPERTY_DATATYPE),
REGEX(Infix.PROPERTY_REGEX),
- VALUE(Infix.PROPERTY_VALUE),
+ VALUE_TYPE(Infix.PROPERTY_VALUE_TYPE),
VALUE_REF(Infix.PROPERTY_VALUE_REF),
+ VALUE(Infix.PROPERTY_VALUE),
WHEN(Infix.PROPERTY_WHEN),
THEN(Infix.PROPERTY_THEN);
@@ -185,26 +186,28 @@ public class Schema {
}
}
- public enum DataType {
- LONG(0),
- DOUBLE(2),
- STRING(4),
- BOOLEAN(6),
- DATE(8);
+ public enum ValueType {
+ INTEGER(0, Integer.class),
+ LONG(1, Long.class),
+ FLOAT(2, Float.class),
+ DOUBLE(3, Double.class),
+ STRING(4, String.class),
+ BOOLEAN(5, Boolean.class),
+ DATE(6, LocalDateTime.class);
- private final byte value;
+ private final byte key;
- DataType(int value) {
- this.value = (byte) value;
+ ValueType(int key, Class<?> valueClass) {
+ this.key = (byte) key;
}
public byte[] value() {
- return new byte[]{value};
+ return new byte[]{key};
}
- public static DataType of(byte value) {
- for (DataType t : DataType.values()) {
- if (t.value == value) {
+ public static ValueType of(byte value) {
+ for (ValueType t : ValueType.values()) {
+ if (t.key == value) {
return t;
}
}
diff --git a/graph/vertex/TypeVertex.java b/graph/vertex/TypeVertex.java
index <HASH>..<HASH> 100644
--- a/graph/vertex/TypeVertex.java
+++ b/graph/vertex/TypeVertex.java
@@ -43,7 +43,7 @@ public abstract class TypeVertex extends Vertex<
protected String label;
protected String scope;
protected Boolean isAbstract;
- protected Schema.DataType dataType;
+ protected Schema.ValueType valueType;
protected String regex;
TypeVertex(Graph.Type graph, Schema.Vertex.Type type, byte[] iid, String label, @Nullable String scope) {
@@ -90,9 +90,9 @@ public abstract class TypeVertex extends Vertex<
public abstract TypeVertex isAbstract(boolean isAbstract);
- public abstract Schema.DataType dataType();
+ public abstract Schema.ValueType valueType();
- public abstract TypeVertex dataType(Schema.DataType dataType);
+ public abstract TypeVertex valueType(Schema.ValueType valueType);
public abstract String regex();
@@ -174,12 +174,12 @@ public abstract class TypeVertex extends Vertex<
return this;
}
- public Schema.DataType dataType() {
- return dataType;
+ public Schema.ValueType valueType() {
+ return valueType;
}
- public TypeVertex dataType(Schema.DataType dataType) {
- this.dataType = dataType;
+ public TypeVertex valueType(Schema.ValueType valueType) {
+ this.valueType = valueType;
return this;
}
@@ -215,7 +215,7 @@ public abstract class TypeVertex extends Vertex<
commitPropertyLabel();
if (scope != null) commitPropertyScope();
if (isAbstract != null && isAbstract) commitPropertyAbstract();
- if (dataType != null) commitPropertyDataType();
+ if (valueType != null) commitPropertyValueType();
if (regex != null && !regex.isEmpty()) commitPropertyRegex();
}
@@ -231,8 +231,8 @@ public abstract class TypeVertex extends Vertex<
graph.storage().put(join(iid, Schema.Property.LABEL.infix().key()), label.getBytes());
}
- private void commitPropertyDataType() {
- graph.storage().put(join(iid, Schema.Property.DATATYPE.infix().key()), dataType.value());
+ private void commitPropertyValueType() {
+ graph.storage().put(join(iid, Schema.Property.VALUE_TYPE.infix().key()), valueType.value());
}
private void commitPropertyRegex() {
@@ -352,17 +352,17 @@ public abstract class TypeVertex extends Vertex<
}
@Override
- public Schema.DataType dataType() {
- if (dataType != null) return dataType;
- byte[] val = graph.storage().get(join(iid, Schema.Property.DATATYPE.infix().key()));
- if (val != null) dataType = Schema.DataType.of(val[0]);
- return dataType;
+ public Schema.ValueType valueType() {
+ if (valueType != null) return valueType;
+ byte[] val = graph.storage().get(join(iid, Schema.Property.VALUE_TYPE.infix().key()));
+ if (val != null) valueType = Schema.ValueType.of(val[0]);
+ return valueType;
}
@Override
- public TypeVertex dataType(Schema.DataType dataType) {
- graph.storage().put(join(iid, Schema.Property.DATATYPE.infix().key()), dataType.value());
- this.dataType = dataType;
+ public TypeVertex valueType(Schema.ValueType valueType) {
+ graph.storage().put(join(iid, Schema.Property.VALUE_TYPE.infix().key()), valueType.value());
+ this.valueType = valueType;
return this;
}
|
Replaced the term 'DataType' with 'ValueType'
|
graknlabs_grakn
|
train
|
aa51ea53f9374a79d6fe1db62ff3a3974bb7a7a9
|
diff --git a/src/Ratchet/Component/Server/IOServerComponent.php b/src/Ratchet/Component/Server/IOServerComponent.php
index <HASH>..<HASH> 100644
--- a/src/Ratchet/Component/Server/IOServerComponent.php
+++ b/src/Ratchet/Component/Server/IOServerComponent.php
@@ -161,6 +161,8 @@ class IOServerComponent implements MessageComponentInterface {
$new_socket->set_nonblock();
$new_connection = new Connection($new_socket);
+ $new_connection->remoteAddress = $new_socket->getRemoteAddress();
+
$this->_resources[] = $new_connection->getSocket()->getResource();
$this->_connections[$new_connection->getSocket()->getResource()] = $new_connection;
|
IO adds remoteAddress to Connection
|
ratchetphp_Ratchet
|
train
|
b43bf68f9c5b1396ae50db6a1ea087efb7b3b19f
|
diff --git a/dev/TestSession.php b/dev/TestSession.php
index <HASH>..<HASH> 100644
--- a/dev/TestSession.php
+++ b/dev/TestSession.php
@@ -96,8 +96,12 @@ class TestSession {
$form->setField(new SimpleByName($k), $v);
}
- if($button) $submission = $form->submitButton(new SimpleByName($button));
- else $submission = $form->submit();
+ if($button) {
+ $submission = $form->submitButton(new SimpleByName($button));
+ if(!$submission) throw new Exception("Can't find button '$button' to submit as part of test.");
+ } else {
+ $submission = $form->submit();
+ }
$url = Director::makeRelative($form->getAction()->asString());
@@ -138,6 +142,15 @@ class TestSession {
}
/**
+ * Return the fake HTTP_REFERER; set each time get() or post() is called.
+ *
+ * @return string
+ */
+ public function lastUrl() {
+ return $this->lastUrl;
+ }
+
+ /**
* Get the most recent response's content
*/
public function lastContent() {
|
MINOR: Minor fixes to FunctionalTest
|
silverstripe_silverstripe-framework
|
train
|
5d28cf05d07dfba60252d55fdaff5b31f0552895
|
diff --git a/bot.go b/bot.go
index <HASH>..<HASH> 100644
--- a/bot.go
+++ b/bot.go
@@ -184,7 +184,11 @@ func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldna
}
var apiResp APIResponse
- json.Unmarshal(bytes, &apiResp)
+
+ err = json.Unmarshal(bytes, &apiResp)
+ if err != nil {
+ return APIResponse{}, err
+ }
if !apiResp.Ok {
return APIResponse{}, errors.New(apiResp.Description)
@@ -431,14 +435,7 @@ func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
return APIResponse{}, err
}
- var apiResp APIResponse
- json.Unmarshal(resp.Result, &apiResp)
-
- if bot.Debug {
- log.Printf("setWebhook resp: %+v\n", apiResp)
- }
-
- return apiResp, nil
+ return resp, nil
}
// GetWebhookInfo allows you to fetch information about a webhook and if
|
Fix returning APIResponse from SetWebHook
|
go-telegram-bot-api_telegram-bot-api
|
train
|
b81c50c62ce775ecdb15371058c08ec79999a99f
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -174,7 +174,7 @@ In the example below, the `inspector` variable will be used. For the client-sid
* `boolean`
* `null`
* `date` (instanceof Date), you can use the `validDate: true` to check if the date is valid
- * `object` (constructor === Object)
+ * `object` (typeof element === 'object') *Note: array, null, or dates don't match the object type*
* `array` (constructor === Array)
* A function (candidate isinstance)
* `any` (it can be anything)
@@ -446,7 +446,7 @@ inspector.validate(schema, c3); // Invalid: Neither @.lorem nor @.ipsum is in c3
* **default**: false.
* **usable on**: object.
-Only keys provided in field "properties" may exist in object. Strict will be ignored if properties has the special key '*'.
+Only keys provided in field "properties" may exist in the object. Strict will be ignored if properties has the special key '*'.
#### Example
diff --git a/lib/schema-inspector.js b/lib/schema-inspector.js
index <HASH>..<HASH> 100644
--- a/lib/schema-inspector.js
+++ b/lib/schema-inspector.js
@@ -138,12 +138,12 @@
return element != null && element instanceof Date;
},
"object": function (element) {
- return element != null && element.constructor === Object;
+ return typeof element === 'object' && element.constructor !== Array && element != null;
},
"array": function (element) {
return element != null && element.constructor === Array;
},
- "any": function (element) {
+ "any": function () {
return true;
}
};
@@ -159,7 +159,7 @@
function _realType(candidate) {
for (var i in _typeIs) {
if (_simpleType(i, candidate)) {
- if (i !== 'any') { return i; }
+ if (i !== 'any' && (i !== 'object' || candidate.constructor === Object)) { return i; }
return 'an instance of ' + candidate.constructor.name;
}
}
@@ -234,7 +234,7 @@
return _simpleType(type, candidate);
});
if (!typeIsValid) {
- types = types.map(function (t) {return typeof t === 'function' ? 'and instance of ' + t.name : t; });
+ types = types.map(function (t) {return typeof t === 'function' ? 'an instance of ' + t.name : t; });
this.report('must be ' + types.join(' or ') + ', but is ' + _realType(candidate), null, 'type');
}
},
@@ -694,7 +694,7 @@
], callback);
};
-// Sanitization ----------------------------------------------------------------
+ // Sanitization ----------------------------------------------------------------
// functions called by _sanitization.type method.
var _forceType = {
number: function (post, schema) {
diff --git a/test/sanitization_test.js b/test/sanitization_test.js
index <HASH>..<HASH> 100644
--- a/test/sanitization_test.js
+++ b/test/sanitization_test.js
@@ -1465,5 +1465,41 @@ exports.sanitization = function () {
candidate.should.be.eql(candidate);
});
+ test('candidate #4 | remove useless keys on custom classes (constructor function)', function () {
+ function G(obj) {
+ Object.keys(obj).forEach(key => {
+ this[key] = obj[key];
+ });
+ }
+
+ var candidate = new G({
+ good: 'key',
+ bad: 'key'
+ });
+
+ var result = si.sanitize(schema, candidate);
+ result.should.be.an.Object;
+ candidate.should.be.eql(new G({ good: 'key' }));
+ });
+
+ test('candidate #5 | remove useless keys on custom classes (constructor class)', function () {
+ class G {
+ constructor(obj) {
+ Object.keys(obj).forEach(key => {
+ this[key] = obj[key];
+ });
+ }
+ }
+
+ var candidate = new G({
+ good: 'key',
+ bad: 'key'
+ });
+
+ var result = si.sanitize(schema, candidate);
+ result.should.be.an.Object;
+ candidate.should.be.eql(new G({ good: 'key' }));
+ });
+
});
};
diff --git a/test/validation_test.js b/test/validation_test.js
index <HASH>..<HASH> 100644
--- a/test/validation_test.js
+++ b/test/validation_test.js
@@ -143,7 +143,7 @@ exports.validation = function () {
result.error[0].property.should.equal('@[0]');
result.error[1].property.should.equal('@[3]');
result.error[2].property.should.equal('@[4]');
- result.error[2].message.should.equal('must be and instance of F, but is an instance of G');
+ result.error[2].message.should.equal('must be an instance of F, but is an instance of G');
});
}); // suite "schema #1.1"
|
Implement sanatize.strict on custom classes (#<I>)
* Implement sanatize.strict on custom classes
Fixes #<I>
* Change to tab for comment
* Change docs for change
* Add test with class syntax
|
Atinux_schema-inspector
|
train
|
1e89553fb04c9058b19e1289fb857cb153250b33
|
diff --git a/nion/swift/ConsoleDialog.py b/nion/swift/ConsoleDialog.py
index <HASH>..<HASH> 100644
--- a/nion/swift/ConsoleDialog.py
+++ b/nion/swift/ConsoleDialog.py
@@ -231,7 +231,7 @@ class ConsoleWidget(Widgets.CompositeWidgetBase):
class ConsoleDialog(Dialog.ActionDialog):
def __init__(self, document_controller):
- super().__init__(document_controller.ui, _("Python Console"), document_controller.app)
+ super().__init__(document_controller.ui, _("Python Console"), document_controller.app, persistent_id="ConsoleDialog")
self.__document_controller = document_controller
diff --git a/nion/swift/ScriptsDialog.py b/nion/swift/ScriptsDialog.py
index <HASH>..<HASH> 100644
--- a/nion/swift/ScriptsDialog.py
+++ b/nion/swift/ScriptsDialog.py
@@ -113,7 +113,7 @@ class RunScriptDialog(Dialog.ActionDialog):
def __init__(self, document_controller):
ui = document_controller.ui
- super().__init__(ui, _("Interactive Dialog"), document_controller.app)
+ super().__init__(ui, _("Interactive Dialog"), document_controller.app, persistent_id="ScriptsDialog")
self.ui = ui
self.document_controller = document_controller
|
Save/restore console/script windows with same position/size.
|
nion-software_nionswift
|
train
|
1a6d07b3e098af38b37c64a2221a54c8ef563ac8
|
diff --git a/edit_interface.php b/edit_interface.php
index <HASH>..<HASH> 100644
--- a/edit_interface.php
+++ b/edit_interface.php
@@ -274,45 +274,40 @@ case 'edit':
$level1type = $edit_fact->getTag();
switch ($record::RECORD_TYPE) {
- case 'OBJE':
- case 'NOTE':
- // OBJE and NOTE facts are all special, and none can take lower-level links
- break;
- case 'SOUR':
case 'REPO':
- // SOUR and REPO facts may only take a NOTE
- if ($level1type!='NOTE') {
+ // REPO:NAME facts may take a NOTE (but the REPO record may not).
+ if ($level1type === 'NAME') {
print_add_layer('NOTE');
+ print_add_layer('SHARED_NOTE');
}
break;
case 'FAM':
case 'INDI':
// FAM and INDI records have real facts. They can take NOTE/SOUR/OBJE/etc.
- if ($level1type!='SEX') {
- if ($level1type!='SOUR' && $level1type!='REPO') {
+ if ($level1type !== 'SEX' && $level1type !== 'NOTE') {
+ if ($level1type !== 'SOUR') {
print_add_layer('SOUR');
}
- if ($level1type!='OBJE' && $level1type!='REPO') {
+ if ($level1type !== 'OBJE') {
print_add_layer('OBJE');
}
- if ($level1type!='NOTE') {
- print_add_layer('NOTE');
- }
- // Shared Note addition ------------
- if ($level1type!='SHARED_NOTE' && $level1type!='NOTE') {
- print_add_layer('SHARED_NOTE');
- }
- if ($level1type!='ASSO' && $level1type!='REPO' && $level1type!='NOTE') {
+ print_add_layer('NOTE');
+ print_add_layer('SHARED_NOTE');
+ if ($level1type !== 'ASSO' && $level1type !== 'NOTE' && $level1type !== 'SOUR') {
print_add_layer('ASSO');
}
// allow to add godfather and godmother for CHR fact or best man and bridesmaid for MARR fact in one window
- if ($level1type=='CHR' || $level1type=='MARR') {
+ if ($level1type === 'CHR' || $level1type === 'MARR') {
print_add_layer('ASSO2');
}
- // RESN can be added to all level 1 tags
- print_add_layer('RESN');
+ if ($level1type !== 'SOUR') {
+ print_add_layer('RESN');
+ }
}
break;
+ default:
+ // Other types of record do not have these lower-level records
+ break;
}
if (Auth::isAdmin() || $SHOW_GEDCOM_RECORD) {
echo
@@ -365,7 +360,7 @@ case 'add':
// Genealogical facts (e.g. for INDI and FAM records) can have 2 SOUR/NOTE/OBJE/ASSO/RESN ...
if ($level0type=='INDI' || $level0type=='FAM') {
// ... but not facts which are simply links to other records
- if ($fact!='OBJE' && $fact!='SHARED_NOTE' && $fact!='OBJE' && $fact!='REPO' && $fact!='SOUR' && $fact!='ASSO') {
+ if ($fact!='OBJE' && $fact!='NOTE' && $fact!='SHARED_NOTE' && $fact!='OBJE' && $fact!='REPO' && $fact!='SOUR' && $fact!='ASSO') {
print_add_layer('SOUR');
print_add_layer('OBJE');
// Don’t add notes to notes!
diff --git a/library/WT/Tree.php b/library/WT/Tree.php
index <HASH>..<HASH> 100644
--- a/library/WT/Tree.php
+++ b/library/WT/Tree.php
@@ -361,7 +361,7 @@ class WT_Tree {
$tree->setPreference('PREFER_LEVEL2_SOURCES', '1');
$tree->setPreference('QUICK_REQUIRED_FACTS', 'BIRT,DEAT');
$tree->setPreference('QUICK_REQUIRED_FAMFACTS', 'MARR');
- $tree->setPreference('REPO_FACTS_ADD', 'PHON,EMAIL,FAX,WWW,NOTE,SHARED_NOTE,RESN');
+ $tree->setPreference('REPO_FACTS_ADD', 'PHON,EMAIL,FAX,WWW,RESN');
$tree->setPreference('REPO_FACTS_QUICK', '');
$tree->setPreference('REPO_FACTS_UNIQUE', 'NAME,ADDR');
$tree->setPreference('REPO_ID_PREFIX', 'R');
|
Fix #<I> - should not be able to add NOTEs in certain circumstances
|
fisharebest_webtrees
|
train
|
89c759b0a5e93947741bc13b96dd342b73e42ef7
|
diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceLockTest.java b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceLockTest.java
index <HASH>..<HASH> 100644
--- a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceLockTest.java
+++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceLockTest.java
@@ -19,71 +19,34 @@ package org.apache.shardingsphere.proxy.backend.communication.jdbc.connection;
import org.junit.Test;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
public final class ResourceLockTest {
@Test
- public void assertDoAwait() throws InterruptedException {
- int numberOfThreads = 10;
+ public void assertDoAwait() {
ResourceLock resourceLock = new ResourceLock();
- ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
- CountDownLatch latch = new CountDownLatch(numberOfThreads);
- AtomicInteger counter = new AtomicInteger();
- for (int i = 0; i < numberOfThreads; i++) {
- service.submit(() -> {
- resourceLock.doAwait();
- counter.incrementAndGet();
- latch.countDown();
- });
- }
- latch.await();
- assertThat(numberOfThreads, is(counter.get()));
+ long startTime = System.currentTimeMillis();
+ resourceLock.doAwait();
+ assertTrue(System.currentTimeMillis() - startTime >= 200L);
}
@Test
- public void assertDoAwaitThrowsException() throws InterruptedException {
- int numberOfThreads = 10;
+ public void assertDoNotify() {
ResourceLock resourceLock = new ResourceLock();
- ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
- CountDownLatch latch = new CountDownLatch(numberOfThreads);
- AtomicInteger counter = new AtomicInteger();
- for (int i = 0; i < numberOfThreads; i++) {
- service.submit(() -> {
- resourceLock.doAwait();
- counter.incrementAndGet();
- latch.countDown();
- });
- }
- latch.await(100, TimeUnit.MILLISECONDS);
- service.shutdownNow();
- assertThat(numberOfThreads, not(counter.get()));
- }
-
- @Test
- public void assertDoNotify() throws InterruptedException {
- int numberOfThreads = 10;
- ResourceLock resourceLock = new ResourceLock();
- ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
- CountDownLatch latch = new CountDownLatch(numberOfThreads);
- AtomicInteger counter = new AtomicInteger();
- for (int i = 0; i < numberOfThreads; i++) {
- service.submit(() -> {
- resourceLock.doAwait();
- counter.incrementAndGet();
- latch.countDown();
- resourceLock.doNotify();
- });
- }
- latch.await();
- assertThat(numberOfThreads, is(counter.get()));
+ long startTime = System.currentTimeMillis();
+ ExecutorService executorService = Executors.newFixedThreadPool(1);
+ executorService.submit(() -> {
+ try {
+ Thread.sleep(50L);
+ } catch (final InterruptedException ignored) {
+ }
+ resourceLock.doNotify();
+ });
+ resourceLock.doAwait();
+ assertTrue(System.currentTimeMillis() - startTime < 200L);
}
}
|
Refactor ResourceLockTest to remove unstable test cases (#<I>)
|
apache_incubator-shardingsphere
|
train
|
4802da29301ae28069161e6647271bd30153d5a9
|
diff --git a/conz.py b/conz.py
index <HASH>..<HASH> 100644
--- a/conz.py
+++ b/conz.py
@@ -13,6 +13,7 @@ from __future__ import print_function
import os
import sys
import signal
+import textwrap
import contextlib
@@ -126,6 +127,25 @@ class Color:
color = Color()
+def rewrap(s, width=79):
+ """ Join all lines from input string and wrap it at specified width """
+ s = ' '.join([l.strip() for l in s.strip().split('\n')])
+ return '\n'.join(textwrap.wrap(s, width))
+
+
+def striplines(s):
+ """ Strip whitespace from each line of input string """
+ return '\n'.join([l.strip() for l in s.strip().split('\n')])
+
+
+def safeint(s):
+ """ Convert the string to int without raising errors """
+ try:
+ return int(s.strip())
+ except (TypeError, ValueError):
+ return None
+
+
class Progress:
"""
Wrapper that manages step progress
@@ -270,6 +290,94 @@ class Console:
ans = read(prompt + ' ')
return clean(ans)
+ def rvpl(self, prompt, error='Entered value is invalid',
+ validator=lambda x: x != '', clean=lambda x: x.strip(),
+ strict=True, default=None):
+ """ Start a read-validate-print loop
+
+ The RVPL will read the user input, validate it, and loop until the
+ entered value passes the validation, then return it.
+
+ Error message can be customized using the ``error`` argument. If the
+ value is a callable, it will be called with the value and it will be
+ expected to return a printable message. Exceptions raised by the
+ ``error`` function are not trapped.
+
+ The ``validator`` argument is is a function that validates the user
+ input. Default validator simply validates if user entered any value.
+
+ The ``clean`` argument specifies a function for the ``read()`` method
+ with the same semantics.
+ """
+ val = self.read(prompt, clean)
+ while not validator(val):
+ if not strict:
+ return default
+ if hasattr(error, '__call__'):
+ self.perr(error(val))
+ else:
+ self.perr(error)
+ val = self.read(prompt, clean)
+ return val
+
+ def menu(self, choices, prompt='Please choose from the provided options:',
+ error='Invalid choice', intro=None, strict=True, default=None,
+ formatter=lambda x, y: '{0:>3}) {1}'.format(x, y),
+ numerator=lambda x: [i + 1 for i in range(x)],
+ clean=safeint):
+ """ Print a menu
+
+ The choices must be an iterable of two-tuples where the first value is
+ the value of the menu item, and the second is the label for that
+ matches the value.
+
+ The menu will be printed with numeric choices. For example::
+
+ 1) foo
+ 2) bar
+
+ Formatting of the number is controlled by the formatter function which
+ can be overridden by passing the ``formatter`` argument.
+
+ The numbers used for the menu are generated using the numerator
+ function which can be specified using the ``numerator`` function. This
+ funciton must take the number of choices and retrun the same number of
+ items that will be used as choice characters as a list.
+
+ The cleaner function is passed to ``pvpl()`` method can be customized
+ using ``clean`` argument. This function should generally be customized
+ whenever ``numerator`` is customized, as default cleaner converts
+ input to integers to match the default numerator.
+
+ Optional ``intro`` argument can be passed to print a message above the
+ menu.
+
+ The return value of this method is the value user has chosen. The
+ prompt will keep asking the user for input until a valid choice is
+ selected. Each time an invalid selection is made, error message is
+ printed. This message can be customized using ``error`` argument.
+
+ If ``strct`` argument is set, then only values in choices are allowed,
+ otherwise any value will be allowed. The ``default`` argument can be
+ used to define what value is returned in case user select an invalid
+ value when strict checking is off.
+ """
+ numbers = list(numerator(len(choices)))
+ labels = (label for _, label in choices)
+ values = [value for value, _ in choices]
+ # Print intro and menu itself
+ if intro:
+ self.pstd('\n' + rewrap(intro))
+ for n, label in zip(numbers, labels):
+ self.pstd(formatter(n, label))
+ # Define the validator
+ validator = lambda x: x in numbers
+ val = self.rvpl(prompt, error=error, validator=validator, clean=clean,
+ strict=strict, default=default)
+ if not strict:
+ return val
+ return values[numbers.index(val)]
+
def readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line
|
Implemented user ineraction controls: RVPL and menu
|
Othernet-Project_conz
|
train
|
2d0cd6d49979b4f18aba8f913f82d592fb835088
|
diff --git a/troposphere/autoscaling.py b/troposphere/autoscaling.py
index <HASH>..<HASH> 100644
--- a/troposphere/autoscaling.py
+++ b/troposphere/autoscaling.py
@@ -132,16 +132,13 @@ class AutoScalingGroup(AWSObject):
if 'AutoScalingRollingUpdate' in update_policy.properties:
rolling_update = update_policy.AutoScalingRollingUpdate
- isMinRef = isinstance(
+ isMinNoCheck = isinstance(
rolling_update.MinInstancesInService,
- Ref
+ (FindInMap, Ref)
)
- isMaxRef = isinstance(self.MaxSize, Ref)
+ isMaxNoCheck = isinstance(self.MaxSize, (FindInMap, Ref))
- isMinMap = isinstance(self.MinSize, FindInMap)
- isMaxMap = isinstance(self.MaxSize, FindInMap)
-
- if not (isMinRef or isMaxRef or isMinMap or isMaxMap):
+ if not (isMinNoCheck or isMaxNoCheck):
maxCount = int(self.MaxSize)
minCount = int(rolling_update.MinInstancesInService)
|
Combine ASG validation of Ref and FindInMap
|
cloudtools_troposphere
|
train
|
ec1495ef523bcbbee456b1bda8ee2798bef356f6
|
diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
@@ -2159,6 +2159,11 @@ public abstract class AbstractCommandLineRunner<A extends Compiler,
String name = input.getName();
String code = input.getSourceFile().getCode();
+ // Ignore weak files.
+ if (input.getSourceFile().isWeak()) {
+ continue;
+ }
+
// Ignore empty fill files created by the compiler to facilitate cross-module code motion.
// Note that non-empty fill files (ones whose code has actually been moved into) are still
// emitted. In particular, this ensures that if there are no (real) inputs the bundle will be
|
Omit weak files from the bundle output.
Weak files are omitted from the compiled output, so they shouldn't be present in the bundle output either.
PiperOrigin-RevId: <I>
|
google_closure-compiler
|
train
|
dd6d3518bb878c0cb003b163e339e4622fa3b3e2
|
diff --git a/spec/mongo/auth/scram/negotiation_spec.rb b/spec/mongo/auth/scram/negotiation_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongo/auth/scram/negotiation_spec.rb
+++ b/spec/mongo/auth/scram/negotiation_spec.rb
@@ -1,5 +1,4 @@
require 'spec_helper'
-require 'cgi'
describe 'SCRAM-SHA auth mechanism negotiation' do
require_scram_sha_256_support
|
Remove unused cgi require (#<I>)
|
mongodb_mongo-ruby-driver
|
train
|
fdd7af90892cd5b969942f9a3c2f18f962e899f4
|
diff --git a/src/diagrams/git/gitGraphAst.js b/src/diagrams/git/gitGraphAst.js
index <HASH>..<HASH> 100644
--- a/src/diagrams/git/gitGraphAst.js
+++ b/src/diagrams/git/gitGraphAst.js
@@ -4,6 +4,13 @@ import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config';
import { getConfig } from '../../config';
import common from '../common/common';
+import {
+ setTitle,
+ getTitle,
+ getAccDescription,
+ setAccDescription,
+ clear as commonClear,
+} from '../../commonDb';
let mainBranchName = getConfig().gitGraph.mainBranchName;
let commits = {};
@@ -14,6 +21,9 @@ let curBranch = mainBranchName;
let direction = 'LR';
let seq = 0;
+/**
+ *
+ */
function getId() {
return random({ length: 7 });
}
@@ -326,6 +336,7 @@ export const clear = function () {
branches[mainBranch] = null;
curBranch = mainBranch;
seq = 0;
+ commonClear();
};
export const getBranchesAsObjArray = function () {
@@ -390,5 +401,9 @@ export default {
getCurrentBranch,
getDirection,
getHead,
+ setTitle,
+ getTitle,
+ getAccDescription,
+ setAccDescription,
commitType,
};
diff --git a/src/diagrams/git/gitGraphParserV2.spec.js b/src/diagrams/git/gitGraphParserV2.spec.js
index <HASH>..<HASH> 100644
--- a/src/diagrams/git/gitGraphParserV2.spec.js
+++ b/src/diagrams/git/gitGraphParserV2.spec.js
@@ -616,4 +616,29 @@ describe('when parsing a gitGraph', function () {
);
}
});
+ describe('accessibility', () => {
+ it('should handle a title and a description (accDescr)', () => {
+ const str = `gitGraph:
+ accTitle: This is a title
+ accDescr: This is a description
+ commit
+ `;
+ parser.parse(str);
+ expect(parser.yy.getTitle()).toBe('This is a title');
+ expect(parser.yy.getAccDescription()).toBe('This is a description');
+ });
+ it('should handle a title and a multiline description (accDescr)', () => {
+ const str = `gitGraph:
+ accTitle: This is a title
+ accDescr {
+ This is a description
+ using multiple lines
+ }
+ commit
+ `;
+ parser.parse(str);
+ expect(parser.yy.getTitle()).toBe('This is a title');
+ expect(parser.yy.getAccDescription()).toBe('This is a description\nusing multiple lines');
+ });
+ });
});
diff --git a/src/diagrams/git/parser/gitGraph.jison b/src/diagrams/git/parser/gitGraph.jison
index <HASH>..<HASH> 100644
--- a/src/diagrams/git/parser/gitGraph.jison
+++ b/src/diagrams/git/parser/gitGraph.jison
@@ -13,6 +13,9 @@
%x type_directive
%x arg_directive
%x close_directive
+%x acc_title
+%x acc_descr
+%x acc_descr_multiline
%options case-insensitive
@@ -22,6 +25,13 @@
<type_directive>":" { this.popState(); this.begin('arg_directive'); return ':'; }
<type_directive,arg_directive>\}\%\% { this.popState(); this.popState(); return 'close_directive'; }
<arg_directive>((?:(?!\}\%\%).|\n)*) return 'arg_directive';
+accTitle\s*":"\s* { this.begin("acc_title");return 'acc_title'; }
+<acc_title>(?!\n|;|#)*[^\n]* { this.popState(); return "acc_title_value"; }
+accDescr\s*":"\s* { this.begin("acc_descr");return 'acc_descr'; }
+<acc_descr>(?!\n|;|#)*[^\n]* { this.popState(); return "acc_descr_value"; }
+accDescr\s*"{"\s* { this.begin("acc_descr_multiline");}
+<acc_descr_multiline>[\}] { this.popState(); }
+<acc_descr_multiline>[^\}]* return "acc_descr_multiline_value";
(\r?\n)+ /*{console.log('New line');return 'NL';}*/ return 'NL';
\s+ /* skip all whitespace */
\#[^\n]* /* skip comments */
@@ -90,6 +100,9 @@ line
statement
: commitStatement
| mergeStatement
+ | acc_title acc_title_value { $$=$2.trim();yy.setTitle($$); }
+ | acc_descr acc_descr_value { $$=$2.trim();yy.setAccDescription($$); }
+ | acc_descr_multiline_value { $$=$1.trim();yy.setAccDescription($$); } | section {yy.addSection($1.substr(8));$$=$1.substr(8);}
| BRANCH ID {yy.branch($2)}
| CHECKOUT ID {yy.checkout($2)}
// | RESET reset_arg {yy.reset($2)}
|
Adding acc to gitGrapg parser
|
knsv_mermaid
|
train
|
dc0746db8d4e6bd7eeaf4cab00deb3c7757b0978
|
diff --git a/abilian/services/indexing/service.py b/abilian/services/indexing/service.py
index <HASH>..<HASH> 100644
--- a/abilian/services/indexing/service.py
+++ b/abilian/services/indexing/service.py
@@ -1,3 +1,4 @@
+# coding=utf-8
"""
Indexing service for Abilian.
@@ -9,6 +10,8 @@ Based on Flask-whooshalchemy by Karl Gyllstrom.
:copyright: (c) 2012 by Karl Gyllstrom
:license: BSD (see LICENSE.txt)
"""
+from __future__ import absolute_import
+
import os
import logging
from inspect import isclass
@@ -18,6 +21,7 @@ from sqlalchemy import event
from sqlalchemy.orm.session import Session
import whoosh.index
+from whoosh.collectors import WrappingCollector
from whoosh.filedb.filestore import RamStorage, FileStorage
from whoosh.writing import AsyncWriter, CLEAR
from whoosh.qparser import DisMaxParser
@@ -46,6 +50,22 @@ _TEXT_ANALYZER = StemmingAnalyzer() | CharsetFilter(accent_map)
_pending_indexation_attr = 'abilian_pending_indexation'
+# as of whoosh 2.5.7, a method is missing on WrappingCollector. See
+# https://bitbucket.org/mchaput/whoosh/issue/394/error-when-searching-with-groupedby-and
+_PATCHED = False
+
+if not _PATCHED:
+ def wrapping_collector_remove(self, global_docnum):
+ return self.child.remove(global_docnum)
+
+ from abilian.core.logging import patch_logger
+ patch_logger.info(WrappingCollector.remove)
+ WrappingCollector.remove = wrapping_collector_remove
+ _PATCHED = True
+ del patch_logger
+ del wrapping_collector_remove
+## END PATCH
+
class IndexServiceState(ServiceState):
whoosh_base = None
indexes = None
@@ -290,7 +310,8 @@ class WhooshIndexService(Service):
if filters:
filter_q = wq.And(filters) if len(filters) > 1 else filters[0]
- search_args['filter'] = filter_q
+ #search_args['filter'] = filter_q
+ query = filter_q & query
if facet_by_type:
if not object_types:
|
indexing: don't restrict security & contenttypes with filters, but combine with AND
way faster (in my case: <I>s with filters, <I>-<I>ms with AND(filters, query))
|
abilian_abilian-core
|
train
|
b67a1545dfff969b142986cddce84eafbc0540c6
|
diff --git a/src/CoandaCMS/Coanda/Pages/PagesModuleProvider.php b/src/CoandaCMS/Coanda/Pages/PagesModuleProvider.php
index <HASH>..<HASH> 100644
--- a/src/CoandaCMS/Coanda/Pages/PagesModuleProvider.php
+++ b/src/CoandaCMS/Coanda/Pages/PagesModuleProvider.php
@@ -399,10 +399,12 @@ class PagesModuleProvider implements \CoandaCMS\Coanda\CoandaModuleProvider {
App::abort('404');
}
+ $meta = $this->buildMeta($page);
+
$data = [
'name' => $page->present()->name,
'type' => $page->type,
- 'meta' => $this->buildMeta($page),
+ 'meta' => $meta,
'attributes' => $this->buildAttributes($page),
'page' => $page,
'template' => $this->templateDirectory() . 'pagetypes.' . $page->type
@@ -420,6 +422,7 @@ class PagesModuleProvider implements \CoandaCMS\Coanda\CoandaModuleProvider {
// Give the layout the rendered page and the data, and it can work some magic to give us back a complete page...
$layout_data = [
'content' => $rendered_page,
+ 'meta' => $meta,
'data' => $data,
'layout' => $layout,
'module' => 'pages',
@@ -450,8 +453,8 @@ class PagesModuleProvider implements \CoandaCMS\Coanda\CoandaModuleProvider {
private function buildMeta($page)
{
return [
- 'title' => 'XXXXX',
- 'description' => 'XXXXX'
+ 'title' => $page->currentVersion()->meta_page_title,
+ 'description' => $page->currentVersion()->meta_description
];
}
}
\ No newline at end of file
|
Tidied up the meta details.
|
CoandaCMS_coanda-core
|
train
|
00b6e29d0a0ded9b1f947b040202377184f25afa
|
diff --git a/xibless/types.py b/xibless/types.py
index <HASH>..<HASH> 100644
--- a/xibless/types.py
+++ b/xibless/types.py
@@ -122,6 +122,9 @@ class Literal(object):
def __init__(self, value):
self.value = value
+ def __repr__(self):
+ return "<Literal %r>" % self.value
+
def __or__(self, other):
return Flags([self]) | other
diff --git a/xibless/view.py b/xibless/view.py
index <HASH>..<HASH> 100644
--- a/xibless/view.py
+++ b/xibless/view.py
@@ -2,8 +2,8 @@ from __future__ import division
from collections import namedtuple, defaultdict
-from .base import GeneratedItem
-from .types import Literal
+from .base import GeneratedItem, const
+from .types import Flags
class Pack(object):
# Corners
@@ -358,28 +358,30 @@ class View(GeneratedItem):
tmpl.initmethod = "initWithFrame:$rect$"
x, y, w, h = self.frameRect()
tmpl.rect = Rect(x, y, w, h).objcValue()
- if self.anchor.growX and self.anchor.growY:
- resizeMask = 'NSViewWidthSizable|NSViewHeightSizable'
- elif self.anchor.growX:
- if self.anchor.corner in (Pack.LowerLeft, Pack.LowerRight):
- resizeMask = 'NSViewWidthSizable|NSViewMaxYMargin'
+ anchor = self.anchor
+ if anchor.growX and anchor.growY:
+ resizeMask = const.NSViewWidthSizable | const.NSViewHeightSizable
+ elif anchor.growX:
+ if anchor.corner in {Pack.LowerLeft, Pack.LowerRight}:
+ resizeMask = const.NSViewWidthSizable | const.NSViewMaxYMargin
else:
- resizeMask = 'NSViewWidthSizable|NSViewMinYMargin'
- elif self.anchor.growY:
- if self.anchor.corner in (Pack.UpperLeft, Pack.LowerLeft):
- resizeMask = 'NSViewHeightSizable|NSViewMaxXMargin'
+ resizeMask = const.NSViewWidthSizable | const.NSViewMinYMargin
+ elif anchor.growY:
+ if anchor.corner in {Pack.UpperLeft, Pack.LowerLeft}:
+ resizeMask = const.NSViewHeightSizable | const.NSViewMaxXMargin
else:
- resizeMask = 'NSViewHeightSizable|NSViewMinXMargin'
+ resizeMask = const.NSViewHeightSizable | const.NSViewMinXMargin
else:
- if self.anchor.corner == Pack.LowerLeft:
- resizeMask = 'NSViewMaxXMargin|NSViewMaxYMargin'
- elif self.anchor.corner == Pack.UpperRight:
- resizeMask = 'NSViewMinXMargin|NSViewMinYMargin'
- elif self.anchor.corner == Pack.LowerRight:
- resizeMask = 'NSViewMinXMargin|NSViewMaxYMargin'
- else:
- resizeMask = 'NSViewMaxXMargin|NSViewMinYMargin'
- self.properties['autoresizingMask'] = Literal(resizeMask)
+ resizeMask = Flags()
+ if anchor.corner in {Pack.LowerLeft, Pack.UpperLeft, Pack.Left, Pack.Above, Pack.Below, Pack.Middle}:
+ resizeMask |= const.NSViewMaxXMargin
+ if anchor.corner in {Pack.LowerRight, Pack.UpperRight, Pack.Right, Pack.Above, Pack.Below, Pack.Middle}:
+ resizeMask |= const.NSViewMinXMargin
+ if anchor.corner in {Pack.LowerLeft, Pack.LowerRight, Pack.Below, Pack.Left, Pack.Right, Pack.Middle}:
+ resizeMask |= const.NSViewMaxYMargin
+ if anchor.corner in {Pack.UpperLeft, Pack.UpperRight, Pack.Above, Pack.Left, Pack.Right, Pack.Middle}:
+ resizeMask |= const.NSViewMinYMargin
+ self.properties['autoresizingMask'] = resizeMask
if self.parent is not None:
tmpl.addtoparent = self.generateAddToParent()
return tmpl
|
Support sides and middle in View.setAnchor().
|
hsoft_xibless
|
train
|
3d824116c051fd1b26a88159f851bc5d8f703783
|
diff --git a/bot/bot.go b/bot/bot.go
index <HASH>..<HASH> 100644
--- a/bot/bot.go
+++ b/bot/bot.go
@@ -20,9 +20,6 @@ type Bot interface {
// Post will be called to handle events that yield a post the Bot has
// not seen before.
Post(contr Controller, post *redditproto.Link)
- // Alarm handles alarms set by the bot through Controller. Bots will be
- // passed the name of their alarm.
- Alarm(contr Controller, name string)
// TearDown will be called at the end of execution so the bot can free
// its resources. It will not be run in parallel.
TearDown()
@@ -41,7 +38,6 @@ func Run(agent string, bot Bot, subreddits ...string) error {
bot: bot,
op: operator.New(cli),
subreddits: subreddits,
- alarms: make(chan alarm),
}
return eng.Run()
}
diff --git a/bot/controller.go b/bot/controller.go
index <HASH>..<HASH> 100644
--- a/bot/controller.go
+++ b/bot/controller.go
@@ -1,16 +1,9 @@
package bot
-import (
- "time"
-)
-
// Controller defines the interface for bots to interact with the engine. These
// methods are requests to the engine to perform actions on behalf of the bot,
// when it decides it is time.
type Controller interface {
- // SetAlarm configures a delayed event. The name will be passed to the
- // bot's Alarm() method when the delay expires.
- SetAlarm(delay time.Duration, name string)
// Stop stops the engine execution.
Stop()
}
diff --git a/bot/rtengine.go b/bot/rtengine.go
index <HASH>..<HASH> 100644
--- a/bot/rtengine.go
+++ b/bot/rtengine.go
@@ -20,16 +20,6 @@ const (
maxTipSize = 100
)
-// An alarm represents a delayed, named event.
-type alarm struct {
- // delay is the delay from alarm creation after which to generated an
- // event.
- delay time.Duration
- // name is the name of the event generated by the alarm (bots use this
- // to differentiate between alarms).
- name string
-}
-
// rtEngine is a real time engine that runs bots against live reddit and feeds
// it new content as it is posted.
type rtEngine struct {
@@ -43,8 +33,6 @@ type rtEngine struct {
// stop is a switch bots can set to signal the engine should stop.
stop bool
- // alarms is the channel over which bots (indirectly) set alarms.
- alarms chan alarm
}
// Stop is a function exposed over the Controller interface; bots can use this
@@ -53,19 +41,7 @@ func (r *rtEngine) Stop() {
r.stop = true
}
-// SetAlarm is a function exposed over the Controller interface; bots can use
-// this to generated their own named events on a delay.
-func (r *rtEngine) SetAlarm(delay time.Duration, name string) {
- r.alarms <- alarm{
- delay: delay,
- name: name,
- }
-}
-
func (r *rtEngine) Run() error {
- alarmStream := make(chan string)
- go r.alarmClock(alarmStream)
-
errors := make(chan error)
postStream := make(chan *redditproto.Link)
go r.postMonitor(errors, postStream, 30)
@@ -77,8 +53,6 @@ func (r *rtEngine) Run() error {
select {
case post := <-postStream:
go r.bot.Post(r, post)
- case alarm := <-alarmStream:
- go r.bot.Alarm(r, alarm)
case err := <-errors:
return err
}
@@ -86,18 +60,6 @@ func (r *rtEngine) Run() error {
return nil
}
-// alarmClock receives alarms, and sets a timer that generates events over the
-// alarmStream when they "go off".
-func (r *rtEngine) alarmClock(alarmStream chan<- string) {
- for true {
- alarm := <-r.alarms
- go func() {
- time.Sleep(alarm.delay)
- alarmStream <- alarm.name
- }()
- }
-}
-
// postMonitor runs continuously, polling the requested subreddits for new posts
// and feeding them back over the postStream channel. It makes at most
// queriesPerMinute to reddit.
|
Remove alarm feature from rtengine.
With time.AfterFunc, this is stupid.
Former-commit-id: a<I>bb<I>cd<I>d<I>d4e<I>f<I>da<I>cae
|
turnage_graw
|
train
|
88d67b73705630013083a3ac6e461442fbe9ef05
|
diff --git a/buildcfg/jsdoc/symbols/publish.js b/buildcfg/jsdoc/symbols/publish.js
index <HASH>..<HASH> 100644
--- a/buildcfg/jsdoc/symbols/publish.js
+++ b/buildcfg/jsdoc/symbols/publish.js
@@ -17,7 +17,7 @@ exports.publish = function(data, opts) {
// get all doclets with the "api" property.
var docs = data({api: {isString: true}}).get();
- // get sorted symbols, filter out those that are members of private classes
+ // get symbols data, filter out those that are members of private classes
var symbols = docs.filter(function(doc) {
var include = true;
var constructor = doc.memberof;
@@ -30,10 +30,9 @@ exports.publish = function(data, opts) {
}).map(function(doc) {
return {
name: doc.longname,
+ extends: doc.augments,
path: path.join(doc.meta.path, doc.meta.filename)
};
- }).sort(function(a, b) {
- return a.name < b.name ? -1 : 1;
});
process.stdout.write(JSON.stringify({symbols: symbols}, null, 2));
diff --git a/tasks/generate-symbols.js b/tasks/generate-symbols.js
index <HASH>..<HASH> 100644
--- a/tasks/generate-symbols.js
+++ b/tasks/generate-symbols.js
@@ -39,6 +39,15 @@ function readSymbols(callback) {
}
+function makeUnique(array) {
+ var values = {};
+ array.forEach(function(value) {
+ values[value] = true;
+ });
+ return Object.keys(values);
+}
+
+
/**
* Generate a list of .js paths in the source directory that are newer than
* the symbols file.
@@ -48,16 +57,16 @@ function readSymbols(callback) {
* any error, the symbols array, and the array of newer source paths.
*/
function getNewer(symbols, date, callback) {
- var all = [];
- var newer = [];
+ var allPaths = [];
+ var newerPaths = [];
var walker = walk(sourceDir);
walker.on('file', function(root, stats, next) {
var sourcePath = path.join(root, stats.name);
if (/\.js$/.test(sourcePath)) {
- all.push(sourcePath);
+ allPaths.push(sourcePath);
if (stats.mtime > date) {
- newer.push(sourcePath);
+ newerPaths.push(sourcePath);
}
}
next();
@@ -67,10 +76,47 @@ function getNewer(symbols, date, callback) {
});
walker.on('end', function() {
// prune symbols if file no longer exists or has been modified
+ var lookup = {};
+ symbols.forEach(function(symbol) {
+ lookup[symbol.name] = symbol;
+ });
+
+ /**
+ * Gather paths for all parent symbols.
+ * @param {Object} symbol Symbol to check.
+ * @param {Array.<string>} paths Current paths.
+ */
+ function gatherParentPaths(symbol, paths) {
+ if (symbol.extends) {
+ symbol.extends.forEach(function(name) {
+ if (name in lookup) {
+ var parent = lookup[name];
+ paths.push(parent.path);
+ gatherParentPaths(parent, paths);
+ }
+ });
+ }
+ }
+
+ var dirtyPaths = [];
+
symbols = symbols.filter(function(symbol) {
- return newer.indexOf(symbol.path) < 0 && all.indexOf(symbol.path) >= 0;
+ var dirty = allPaths.indexOf(symbol.path) < 0;
+ if (!dirty) {
+ // confirm that symbol and all parent paths are not newer
+ var paths = [symbol.path];
+ gatherParentPaths(symbol, paths);
+ dirty = paths.some(function(p) {
+ return newerPaths.indexOf(p) >= 0;
+ });
+ if (dirty) {
+ dirtyPaths.push(symbol.path);
+ }
+ }
+ return !dirty;
});
- callback(null, symbols, newer);
+
+ callback(null, symbols, makeUnique(newerPaths.concat(dirtyPaths)));
});
}
@@ -135,7 +181,9 @@ function writeSymbols(symbols, output, callback) {
return;
}
- symbols = symbols.concat(data.symbols);
+ symbols = symbols.concat(data.symbols).sort(function(a, b) {
+ return a.name < b.name ? -1 : 1;
+ });
var str = JSON.stringify({symbols: symbols}, null, ' ');
fse.outputFile(destPath, str, callback);
|
Regenerate symbols if parents have changed
The generate-symbols.js task runs JSDoc on source files. Because this takes a long time (<I>s) to run on the whole library, the resulting symbols file includes additional metadata to make it possible to do incremental symbol generation on subsequent runs. The 'path' and 'extends' metadata for a symbol are used to determine what needs to be regenerated.
|
openlayers_openlayers
|
train
|
4ca63165a348815fa1ac6128bc72e5336ffc0db8
|
diff --git a/host-controller/src/main/java/org/jboss/as/host/controller/operations/NewRemoteDomainControllerAddHandler.java b/host-controller/src/main/java/org/jboss/as/host/controller/operations/NewRemoteDomainControllerAddHandler.java
index <HASH>..<HASH> 100644
--- a/host-controller/src/main/java/org/jboss/as/host/controller/operations/NewRemoteDomainControllerAddHandler.java
+++ b/host-controller/src/main/java/org/jboss/as/host/controller/operations/NewRemoteDomainControllerAddHandler.java
@@ -83,8 +83,8 @@ public class NewRemoteDomainControllerAddHandler extends AbstractAddStepHandler
parametersValidator.validate(operation);
ModelNode dc = model.get(DOMAIN_CONTROLLER);
- final int port = operation.require(PORT).asInt();
- final String host = operation.require(HOST).asString();
+ final ModelNode port = operation.require(PORT);
+ final ModelNode host = operation.require(HOST);
dc.get(REMOTE, PORT).set(port);
dc.get(REMOTE, HOST).set(host);
@@ -93,8 +93,8 @@ public class NewRemoteDomainControllerAddHandler extends AbstractAddStepHandler
}
hostControllerInfo.setMasterDomainController(false);
- hostControllerInfo.setRemoteDomainControllerHost(host);
- hostControllerInfo.setRemoteDomainControllerPort(port);
+ hostControllerInfo.setRemoteDomainControllerHost(host.resolve().asString());
+ hostControllerInfo.setRemoteDomainControllerPort(port.resolve().asInt());
overallConfigPersister.initializeDomainConfigurationPersister(true);
NewDomainModelUtil.initializeSlaveDomainRegistry(rootRegistration, overallConfigPersister.getDomainPersister(), fileRepository);
|
Restore ability to use expressions in remote DC config
|
wildfly_wildfly
|
train
|
234804cd782b1d3b4ae46ab4ec6789c166e7fc2d
|
diff --git a/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenBuilder.java b/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenBuilder.java
index <HASH>..<HASH> 100644
--- a/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenBuilder.java
+++ b/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenBuilder.java
@@ -22,20 +22,20 @@
package org.jboss.as.clustering.jgroups.subsystem;
+import org.jboss.as.clustering.jgroups.auth.BinaryAuthToken;
import org.jboss.as.controller.PathAddress;
-import org.jgroups.auth.SimpleToken;
/**
* @author Paul Ferraro
*/
-public class PlainAuthTokenBuilder extends AuthTokenBuilder<SimpleToken> {
+public class PlainAuthTokenBuilder extends AuthTokenBuilder<BinaryAuthToken> {
public PlainAuthTokenBuilder(PathAddress address) {
super(address);
}
@Override
- public SimpleToken apply(String sharedSecret) {
- return new SimpleToken(sharedSecret);
+ public BinaryAuthToken apply(String sharedSecret) {
+ return new BinaryAuthToken(sharedSecret.getBytes());
}
}
diff --git a/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenResourceDefinition.java b/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenResourceDefinition.java
index <HASH>..<HASH> 100644
--- a/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenResourceDefinition.java
+++ b/clustering/jgroups/extension/src/main/java/org/jboss/as/clustering/jgroups/subsystem/PlainAuthTokenResourceDefinition.java
@@ -23,13 +23,13 @@
package org.jboss.as.clustering.jgroups.subsystem;
import org.jboss.as.clustering.function.Consumers;
+import org.jboss.as.clustering.jgroups.auth.BinaryAuthToken;
import org.jboss.as.controller.PathElement;
-import org.jgroups.auth.SimpleToken;
/**
* @author Paul Ferraro
*/
-public class PlainAuthTokenResourceDefinition extends AuthTokenResourceDefinition<SimpleToken> {
+public class PlainAuthTokenResourceDefinition extends AuthTokenResourceDefinition<BinaryAuthToken> {
static final PathElement PATH = pathElement("plain");
|
WFLY-<I> AUTH plain token should use case-sensitive shared secret comparison.
|
wildfly_wildfly
|
train
|
187fd274500ea96218c1aa34ab2aec68a0b8cfed
|
diff --git a/code/fields/MultiValueField.php b/code/fields/MultiValueField.php
index <HASH>..<HASH> 100644
--- a/code/fields/MultiValueField.php
+++ b/code/fields/MultiValueField.php
@@ -149,6 +149,10 @@ class MultiValueField extends DBField implements CompositeDBField {
return $this->changed;
}
+ public function scaffoldFormField($title = null) {
+ return new MultiValueTextField($this->name, $title);
+ }
+
/**
* Convert to a textual list of items
*/
|
ENHANCEMENT: Added scaffolding to the db field.
|
symbiote_silverstripe-multivaluefield
|
train
|
7829e0f363027d5963f7b6ddb7dba3d6efecac73
|
diff --git a/python/orca/example/learn/mxnet/lenet_mnist.py b/python/orca/example/learn/mxnet/lenet_mnist.py
index <HASH>..<HASH> 100644
--- a/python/orca/example/learn/mxnet/lenet_mnist.py
+++ b/python/orca/example/learn/mxnet/lenet_mnist.py
@@ -124,14 +124,15 @@ if __name__ == '__main__':
ray_ctx = RayContext(sc=sc)
ray_ctx.init()
- config = create_config(opt.batch_size, optimizer="sgd",
+ config = create_config(optimizer="sgd",
optimizer_params={'learning_rate': opt.learning_rate},
log_interval=opt.log_interval, seed=42)
estimator = Estimator(config, model_creator=get_model,
loss_creator=get_loss, validation_metrics_creator=get_metrics,
num_workers=opt.num_workers, num_servers=opt.num_servers,
eval_metrics_creator=get_metrics)
- estimator.fit(train_data=get_train_data_iter, val_data=get_test_data_iter, nb_epoch=opt.epochs)
+ estimator.fit(data=get_train_data_iter, validation_data=get_test_data_iter,
+ epochs=opt.epochs, batch_size=opt.batch_size)
estimator.shutdown()
ray_ctx.stop()
sc.stop()
|
Refactor MXNet API (#<I>)
* refactor API
* minor
* style
|
intel-analytics_BigDL
|
train
|
fa39162a496d91805624f66333ad8478f0e24a5c
|
diff --git a/web/concrete/core/models/groups.php b/web/concrete/core/models/groups.php
index <HASH>..<HASH> 100644
--- a/web/concrete/core/models/groups.php
+++ b/web/concrete/core/models/groups.php
@@ -112,6 +112,17 @@
return $g;
}
}
+
+ public static function getByPath($gPath) {
+ $db = Loader::db();
+ $row = $db->getRow("select * from Groups where gPath = ?", array($gPath));
+ if (isset($row['gID'])) {
+ $g = new Group;
+ $g->setPropertiesFromArray($row);
+ return $g;
+ }
+ }
+
public function getGroupMembers() {
$user_list = new UserList();
@@ -386,6 +397,7 @@
$r = $db->prepare("update Groups set gName = ?, gDescription = ? where gID = ?");
$res = $db->Execute($r, $v);
$group = Group::getByID($this->gID);
+ $group->rescanGroupPath();
Events::fire('on_group_update', $this);
return $group;
@@ -417,6 +429,7 @@
GroupTreeNode::add($ng, $node);
Events::fire('on_group_add', $ng);
+ $ng->rescanGroupPath();
return $ng;
}
}
|
fixing some groups stuff
Former-commit-id: c1ab7dba9e<I>e<I>f<I>a9bb2f<I>c<I>de<I>
|
concrete5_concrete5
|
train
|
be14c936b38970faef5c25113ed0338dc5b08d80
|
diff --git a/app/controllers/pwb/omniauth_callbacks_controller.rb b/app/controllers/pwb/omniauth_callbacks_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/pwb/omniauth_callbacks_controller.rb
+++ b/app/controllers/pwb/omniauth_callbacks_controller.rb
@@ -1,13 +1,17 @@
require_dependency 'pwb/application_controller'
module Pwb
- class OmniauthCallbacksController < Devise::OmniauthCallbacksController
- def facebook
- @user = User.find_for_oauth(request.env['omniauth.auth'])
- if @user.persisted?
- sign_in_and_redirect @user, event: :authentication
- set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
- end
- end
- end
-end
\ No newline at end of file
+ class OmniauthCallbacksController < Devise::OmniauthCallbacksController
+ def facebook
+ # https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope
+ # Use the session locale set earlier; use the default if it isn't available.
+ I18n.locale = session[:omniauth_login_locale] || I18n.default_locale
+
+ @user = User.find_for_oauth(request.env['omniauth.auth'])
+ if @user.persisted?
+ sign_in_and_redirect @user, event: :authentication
+ set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
+ end
+ end
+ end
+end
diff --git a/app/models/pwb/user.rb b/app/models/pwb/user.rb
index <HASH>..<HASH> 100644
--- a/app/models/pwb/user.rb
+++ b/app/models/pwb/user.rb
@@ -17,6 +17,11 @@ module Pwb
return authorization.user if authorization
email = auth.info[:email]
+ unless email.present?
+ # below is a workaround for when email is not available from auth provider
+ email = "#{SecureRandom.urlsafe_base64}@example.com"
+ # in future might redirect to a page where email can be requested
+ end
user = User.where(email: email).first
if user
user.create_authorization(auth)
diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb
index <HASH>..<HASH> 100644
--- a/config/initializers/devise.rb
+++ b/config/initializers/devise.rb
@@ -248,7 +248,11 @@ Devise.setup do |config|
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
- config.omniauth :facebook, Rails.application.secrets.facebook_app_id, Rails.application.secrets.facebook_app_secret, scope: "email"
+ config.omniauth :facebook,
+ Rails.application.secrets.facebook_app_id,
+ Rails.application.secrets.facebook_app_secret,
+ scope: "email",
+ token_params: { parse: :json }
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
diff --git a/db/migrate/20180111045213_create_authorizations.rb b/db/migrate/20180111045213_create_authorizations.rb
index <HASH>..<HASH> 100644
--- a/db/migrate/20180111045213_create_authorizations.rb
+++ b/db/migrate/20180111045213_create_authorizations.rb
@@ -1,6 +1,6 @@
class CreateAuthorizations < ActiveRecord::Migration[5.1]
def change
- create_table :authorizations do |t|
+ create_table :pwb_authorizations do |t|
t.references :user, index: true
t.string :provider
t.string :uid
diff --git a/spec/dummy/db/schema.rb b/spec/dummy/db/schema.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy/db/schema.rb
+++ b/spec/dummy/db/schema.rb
@@ -15,15 +15,6 @@ ActiveRecord::Schema.define(version: 20180111045213) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
- create_table "authorizations", force: :cascade do |t|
- t.bigint "user_id"
- t.string "provider"
- t.string "uid"
- t.datetime "created_at", null: false
- t.datetime "updated_at", null: false
- t.index ["user_id"], name: "index_authorizations_on_user_id"
- end
-
create_table "property_web_scraper_import_hosts", id: :serial, force: :cascade do |t|
t.integer "flags", default: 0, null: false
t.string "scraper_name"
@@ -154,6 +145,15 @@ ActiveRecord::Schema.define(version: 20180111045213) do
t.string "theme_name"
end
+ create_table "pwb_authorizations", force: :cascade do |t|
+ t.bigint "user_id"
+ t.string "provider"
+ t.string "uid"
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["user_id"], name: "index_pwb_authorizations_on_user_id"
+ end
+
create_table "pwb_clients", id: :serial, force: :cascade do |t|
t.string "first_names"
t.string "last_names"
|
Fix issues with completing facebook auth
|
etewiah_property_web_builder
|
train
|
651caa931a09ca5d32ee4400ca9f23416964a8aa
|
diff --git a/lib/OpenLayers/Util.js b/lib/OpenLayers/Util.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers/Util.js
+++ b/lib/OpenLayers/Util.js
@@ -148,6 +148,7 @@ OpenLayers.Util.onImageLoadErrorColor = "pink";
OpenLayers.Util.onImageLoadError = function() {
this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
+ this.style.display = "";
};
|
When we set the background color for an erroring image, we also want to
*display* the image... otherwise that color never shows up.
git-svn-id: <URL>
|
openlayers_openlayers
|
train
|
f5819aaa3de658571915b7a63a15d5350e1913b2
|
diff --git a/plenum/server/node.py b/plenum/server/node.py
index <HASH>..<HASH> 100644
--- a/plenum/server/node.py
+++ b/plenum/server/node.py
@@ -3378,4 +3378,4 @@ class Node(HasActionQueue, Motor, Propagator, MessageProcessor, HasFileStorage,
def mark_request_as_executed(self, request: Request):
self.requests.mark_as_executed(request)
- self.authNr(request).clean_from_verified(request.key)
+ self.authNr(request.as_dict).clean_from_verified(request.key)
|
[INDY-<I>] fix verified_reqs cleaning
|
hyperledger_indy-plenum
|
train
|
d78115b590c81595cc2744da74f380e18b04ee77
|
diff --git a/example_test.go b/example_test.go
index <HASH>..<HASH> 100644
--- a/example_test.go
+++ b/example_test.go
@@ -19,7 +19,7 @@ func Example() {
// start the server and echo incoming messages back to the sender
s := neptulon.NewServer("127.0.0.1:3000")
- s.Middleware(func(ctx *neptulon.ReqCtx) error {
+ s.MiddlewareFunc(func(ctx *neptulon.ReqCtx) error {
var msg SampleMsg
if err := ctx.Params(&msg); err != nil {
return err
diff --git a/test/conn_helper.go b/test/conn_helper.go
index <HASH>..<HASH> 100644
--- a/test/conn_helper.go
+++ b/test/conn_helper.go
@@ -35,11 +35,6 @@ func NewConnHelper(t *testing.T, addr string) *ConnHelper {
return ch
}
-// Middleware registers middleware to handle incoming request messages.
-func (ch *ConnHelper) Middleware(middleware ...func(ctx *neptulon.ReqCtx) error) {
- ch.Conn.Middleware(middleware...)
-}
-
// Connect connects to a server.
func (ch *ConnHelper) Connect() *ConnHelper {
// retry connect in case we're operating on a very slow machine
diff --git a/test/external_client_test.go b/test/external_client_test.go
index <HASH>..<HASH> 100644
--- a/test/external_client_test.go
+++ b/test/external_client_test.go
@@ -19,13 +19,13 @@ var ext = flag.Bool("ext", false, "Run external client test case.")
// * Repeat ad infinitum, until {"method":"close", "params":"{"message": "..."}"} is received. Close message body is logged.
func TestExternalClient(t *testing.T) {
sh := NewServerHelper(t)
- sh.Middleware(middleware.Logger)
+ sh.Server.MiddlewareFunc(middleware.Logger)
var wg sync.WaitGroup
m := "Hello from Neptulon server!"
// handle 'echo' requests via the 'echo middleware'
srout := middleware.NewRouter()
- sh.Middleware(srout.Middleware)
+ sh.Server.Middleware(srout)
srout.Request("echo", func(ctx *neptulon.ReqCtx) error {
// send 'echo' request to client upon connection (blocks test if no response is received)
wg.Add(1)
@@ -73,11 +73,11 @@ func TestExternalClient(t *testing.T) {
// use internal conn implementation instead to test the test case itself
t.Log("Skipping external client integration test since -ext flag is not provided.")
ch := sh.GetConnHelper()
- ch.Middleware(middleware.Logger)
+ ch.Conn.MiddlewareFunc(middleware.Logger)
// handle 'echo' requests via the 'echo middleware'
crout := middleware.NewRouter()
- ch.Conn.Middleware(crout.Middleware)
+ ch.Conn.Middleware(crout)
crout.Request("echo", middleware.Echo)
defer ch.Connect().CloseWait()
diff --git a/test/message_test.go b/test/message_test.go
index <HASH>..<HASH> 100644
--- a/test/message_test.go
+++ b/test/message_test.go
@@ -29,7 +29,7 @@ func TestEchoWithoutTestHelpers(t *testing.T) {
time.Sleep(time.Millisecond * 10)
defer s.Close()
- s.Middleware(func(ctx *neptulon.ReqCtx) error {
+ s.MiddlewareFunc(func(ctx *neptulon.ReqCtx) error {
t.Log("Request received:", ctx.Method)
ctx.Res = "response-wow!"
return ctx.Next()
@@ -60,13 +60,13 @@ func TestEchoWithoutTestHelpers(t *testing.T) {
func TestEcho(t *testing.T) {
sh := NewServerHelper(t)
rout := middleware.NewRouter()
- sh.Middleware(middleware.Logger)
- sh.Middleware(rout.Middleware)
+ sh.Server.MiddlewareFunc(middleware.Logger)
+ sh.Server.Middleware(rout)
rout.Request("echo", middleware.Echo)
defer sh.Start().CloseWait()
ch := sh.GetConnHelper()
- ch.Middleware(middleware.Logger)
+ ch.Conn.MiddlewareFunc(middleware.Logger)
defer ch.Connect().CloseWait()
m := "Hello!"
diff --git a/test/server_helper.go b/test/server_helper.go
index <HASH>..<HASH> 100644
--- a/test/server_helper.go
+++ b/test/server_helper.go
@@ -65,11 +65,6 @@ func (sh *ServerHelper) UseTLS() *ServerHelper {
return sh
}
-// Middleware registers middleware to handle incoming request messages.
-func (sh *ServerHelper) Middleware(middleware ...func(ctx *neptulon.ReqCtx) error) {
- sh.Server.Middleware(middleware...)
-}
-
// Start starts the server.
func (sh *ServerHelper) Start() *ServerHelper {
// start the server immediately
|
fix tests and examples to use new middleware type
|
neptulon_neptulon
|
train
|
b319892b834d297c91d03b1a2a6e6874c69b899f
|
diff --git a/aws-sdk-resources-java-core/src/main/java/com/amazonaws/resources/internal/ActionUtils.java b/aws-sdk-resources-java-core/src/main/java/com/amazonaws/resources/internal/ActionUtils.java
index <HASH>..<HASH> 100644
--- a/aws-sdk-resources-java-core/src/main/java/com/amazonaws/resources/internal/ActionUtils.java
+++ b/aws-sdk-resources-java-core/src/main/java/com/amazonaws/resources/internal/ActionUtils.java
@@ -19,7 +19,6 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -319,9 +318,9 @@ final class ActionUtils {
int listSize = -1;
- for (PathSourceMapping m : mapping.getRequestParamMappings()) {
+ for (PathSourceMapping m : mapping.getResponseIdentifierMappings()) {
List<Object> values =
- ReflectionUtils.getAllByPath(request, m.getSource());
+ ReflectionUtils.getAllByPath(result, m.getSource());
if (listSize == -1) {
listSize = values.size();
@@ -334,16 +333,40 @@ final class ActionUtils {
ids.put(m.getTarget(), values);
}
- for (PathSourceMapping m : mapping.getResponseIdentifierMappings()) {
- List<Object> values =
- ReflectionUtils.getAllByPath(result, m.getSource());
-
- if (listSize == -1) {
- listSize = values.size();
- } else if (values.size() != listSize) {
- throw new IllegalStateException(
- "List size mismatch! " + listSize + " vs "
- + values.size());
+ for (PathSourceMapping m : mapping.getRequestParamMappings()) {
+ List<Object> values;
+
+ /*
+ * When the response contains multiple resources, the source of a
+ * request param mapping could be either single-valued (e.g. in
+ * Glacier.getVaults() action, the single-valued "AccountId" param
+ * is mapped to the "AccountId"s of all the returned vaults), or
+ * multi-valued (e.g. in EC2.Instance.createTags() action, multiple
+ * "Tag[].Key" parameters are mapped to the "Key"s of all the
+ * returned Tag resources.
+ */
+ if (m.isMultiValued()) {
+ values =
+ ReflectionUtils.getAllByPath(request, m.getSource());
+
+ if (listSize == -1) {
+ listSize = values.size();
+ } else if (values.size() != listSize) {
+ throw new IllegalStateException(
+ "List size mismatch! " + listSize + " vs "
+ + values.size());
+ }
+ }
+ else {
+ // If single valued, augment the value into a list of ids, which
+ // match the length of the ids extracted from response.
+ Object singleValue =
+ ReflectionUtils.getByPath(request, m.getSource());
+
+ values = new ArrayList<Object>(listSize);
+ for (int i = 0; i < listSize; i++ ) {
+ values.add(singleValue);
+ }
}
ids.put(m.getTarget(), values);
|
Fix issue when the request-param-mapping is single-valued while the response-resource-mapping is mutli-valued.
|
amazon-archives_aws-sdk-java-resources
|
train
|
75a875371b9b844ca22e5e45771b22197e132856
|
diff --git a/centinel/__init__.py b/centinel/__init__.py
index <HASH>..<HASH> 100644
--- a/centinel/__init__.py
+++ b/centinel/__init__.py
@@ -1,6 +1,6 @@
#!/usr/bin/python
__title__ = 'centinel'
-__version__ = '0.1.5.6'
+__version__ = '0.1.5.6.1'
import centinel.backend
import centinel.client
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ online information controls, and Internet censorship."""
setup(
name="centinel",
- version="0.1.5.6",
+ version="0.1.5.6.1",
author="ICLab Developers",
author_email="info@iclab.org",
description=DESCRIPTION,
|
bumped versio to <I>
|
iclab_centinel
|
train
|
59ffc2f46bce907c168072d4bf94f2ab305faf8b
|
diff --git a/reformulation-core/src/main/java/it/unibz/inf/ontop/owlrefplatform/core/unfolding/ExpressionEvaluator.java b/reformulation-core/src/main/java/it/unibz/inf/ontop/owlrefplatform/core/unfolding/ExpressionEvaluator.java
index <HASH>..<HASH> 100644
--- a/reformulation-core/src/main/java/it/unibz/inf/ontop/owlrefplatform/core/unfolding/ExpressionEvaluator.java
+++ b/reformulation-core/src/main/java/it/unibz/inf/ontop/owlrefplatform/core/unfolding/ExpressionEvaluator.java
@@ -653,7 +653,11 @@ public class ExpressionEvaluator {
} else {
teval1 = term.getTerm(0);
}
- } else {
+ }
+ else if (term.getTerm(0).equals(OBDAVocabulary.NULL)) {
+ return eq ? OBDAVocabulary.FALSE : OBDAVocabulary.TRUE;
+ }
+ else {
teval1 = eval(term.getTerm(0));
}
@@ -673,7 +677,11 @@ public class ExpressionEvaluator {
} else {
teval2 = term.getTerm(1);
}
- } else {
+ }
+ else if (term.getTerm(1).equals(OBDAVocabulary.NULL)) {
+ return eq ? OBDAVocabulary.FALSE : OBDAVocabulary.TRUE;
+ }
+ else {
teval2 = eval(term.getTerm(1));
}
|
EQ(NULL,x) is false (SQL EQ). Now handled by the ExpressionEvaluator.
|
ontop_ontop
|
train
|
bfb4630fec4f744e2dd0fce9e7428c0faa176964
|
diff --git a/pow_c.go b/pow_c.go
index <HASH>..<HASH> 100644
--- a/pow_c.go
+++ b/pow_c.go
@@ -27,7 +27,7 @@ SOFTWARE.
package giota
-// #cgo CFLAGS: -Wall
+// #cgo CFLAGS: -Wall -Wno-overflow
/*
#include <stdio.h>
#include <string.h>
|
Ignore c compiler warnings when building pow_c.go
A warning is shown for each definition like:
#define HBITS 0xFFFFFFFFFFFFFFFFL
They get annoying pretty quickly in a logic which is not an issue.
|
iotaledger_iota.go
|
train
|
e1f9cbf8c47f66412f9ec618cd5dcdde4acdeb99
|
diff --git a/src/contexts/__init__.py b/src/contexts/__init__.py
index <HASH>..<HASH> 100644
--- a/src/contexts/__init__.py
+++ b/src/contexts/__init__.py
@@ -18,6 +18,15 @@ def main():
def run(spec=None, reporter=None):
+ """
+ Polymorphic test-running function.
+
+ build_suite(class) - run the test class
+ build_suite(module) - run all the test classes in the module
+ build_suite(file_path:string) - run all the test classes found in the file
+ build_suite(folder_path:string) - run all the test classes found in the folder and subfolders
+ build_suite(package_path:string) - run all the test classes found in the package and subfolders
+ """
if reporter is None:
reporter = reporting.CapturingCLIReporter()
if spec is None:
diff --git a/src/contexts/builders.py b/src/contexts/builders.py
index <HASH>..<HASH> 100644
--- a/src/contexts/builders.py
+++ b/src/contexts/builders.py
@@ -7,14 +7,21 @@ from . import discovery
def build_suite(spec):
+ """
+ Polymorphic suite-building function.
+
+ build_suite(class) - return a suite containing the test class
+ build_suite(module) - return a suite containing all the test classes in the module
+ build_suite(file_path:string) - return a suite containing all the test classes found in the file
+ build_suite(folder_path:string) - return a suite composed of all the test files in the folder
+ build_suite(package_path:string) - return a suite composed of all the test files in the package
+ """
if isinstance(spec, types.ModuleType):
return build_suite_from_module(spec)
elif isinstance(spec, str) and os.path.isfile(spec):
return build_suite_from_file_path(spec)
elif isinstance(spec, str) and os.path.isdir(spec):
return build_suite_from_directory_path(spec)
- elif isinstance(spec, collections.Iterable):
- return Suite(spec)
elif isinstance(spec, type):
return Suite([spec])
diff --git a/test/core_tests.py b/test/core_tests.py
index <HASH>..<HASH> 100644
--- a/test/core_tests.py
+++ b/test/core_tests.py
@@ -305,35 +305,6 @@ class WhenASpecHasStaticmethods(object):
def it_should_run_the_staticmethods(self):
self.log.should.equal("arrange act assert teardown ")
-class WhenRunningMultipleSpecs(object):
- def context(self):
- class Spec1(object):
- was_run = False
- def it(self):
- self.__class__.was_run = True
- class Spec2(object):
- was_run = False
- def it(self):
- self.__class__.was_run = True
-
- self.suite = [Spec1, Spec2]
- self.reporter = MockReporter()
-
- def because_we_run_the_suite(self):
- contexts.run(self.suite, self.reporter)
-
- def it_should_run_both_tests(self):
- self.suite[0].was_run.should.be.true
- self.suite[1].was_run.should.be.true
-
- def it_should_call_ctx_started_twice(self):
- calls = [call for call in self.reporter.calls if call[0] == "context_started"]
- calls.should.have.length_of(2)
-
- def it_should_call_ctx_ended_twice(self):
- calls = [call for call in self.reporter.calls if call[0] == "context_ended"]
- calls.should.have.length_of(2)
-
class WhenWeRunSpecsWithAlternatelyNamedMethods(object):
@classmethod
def examples(self):
|
No longer accepting a list of test classes into run()
|
benjamin-hodgson_Contexts
|
train
|
0cb95cc7193fbb7c11fd60aa28620b56fbd521e1
|
diff --git a/src/Configuration/ConfigurationSet.php b/src/Configuration/ConfigurationSet.php
index <HASH>..<HASH> 100644
--- a/src/Configuration/ConfigurationSet.php
+++ b/src/Configuration/ConfigurationSet.php
@@ -9,16 +9,32 @@ class ConfigurationSet implements ConfigurationInterface
/**
* @var array
*/
- protected $classes;
+ protected $classes = [];
/**
* @param array $classes
*/
- public function __construct(array $classes)
+ public function __construct(array $classes = [])
{
- $this->validateClasses($classes);
+ foreach ($classes as $class) {
+ $this->add($class);
+ }
+ }
+
+ /**
+ * Add a new configuration class to the set
+ *
+ * @param string $class
+ *
+ * @return self
+ */
+ public function add($class)
+ {
+ $this->validate($class);
- $this->classes = $classes;
+ $this->classes[] = $class;
+
+ return $this;
}
/**
@@ -33,20 +49,21 @@ class ConfigurationSet implements ConfigurationInterface
}
/**
- * @param array $classes
- * @throws \DomainException if any classes cannot be loaded
+ * Checks that the given class is valid for configuration
+ *
+ * @param string $class
+ *
+ * @return void
+ *
+ * @throws \DomainException If the class is not of the expected type
*/
- protected function validateClasses(array $classes)
+ protected function validate($class)
{
- $invalid = array_filter(
- $classes,
- function ($class) {
- return !is_subclass_of($class, ConfigurationInterface::class);
- }
- );
- if ($invalid) {
- $message = 'Classes cannot be loaded or do not implement ConfigurationInterface: ' . implode(', ', $invalid);
- throw new \DomainException($message);
+ if (!is_subclass_of($class, ConfigurationInterface::class)) {
+ throw new \DomainException(sprintf(
+ 'Configuration class `%s` must implement ConfigurationInterface',
+ $class
+ ));
}
}
}
|
Modify configuration set to allow additions
Enables the user to add custom config to the default set.
|
equip_framework
|
train
|
c0874860cae20df4c3050b214d814d1ae69bff29
|
diff --git a/proto/wtools/abase_dom/l5/Common.js b/proto/wtools/abase_dom/l5/Common.js
index <HASH>..<HASH> 100644
--- a/proto/wtools/abase_dom/l5/Common.js
+++ b/proto/wtools/abase_dom/l5/Common.js
@@ -3421,7 +3421,7 @@ let Extension =
uiInitSimple,
uiShow,
- uiIsShowed
+ uiIsShowed,
_domBasel5Loaded : true
diff --git a/proto/wtools/abase_dom/l7/Blob.js b/proto/wtools/abase_dom/l7/Blob.js
index <HASH>..<HASH> 100644
--- a/proto/wtools/abase_dom/l7/Blob.js
+++ b/proto/wtools/abase_dom/l7/Blob.js
@@ -1,4 +1,5 @@
-( function() {
+( function()
+{
const _ = _global_.wTools;
_.dom = _.dom || Object.create( null );
@@ -11,25 +12,25 @@ window.saveAs = window.saveAs || window.webkitSaveAs || window.mozSaveAs || wind
let BrowserSupportedMimeTypes =
{
- 'image/jpeg': true,
- 'image/png': true,
- 'image/gif': true,
- 'image/svg+xml': true,
- 'image/bmp': true,
- 'image/x-windows-bmp': true,
- 'image/webp': true,
- 'audio/wav': true,
- 'audio/mpeg': true,
- 'audio/webm': true,
- 'audio/ogg': true,
- 'video/mpeg': true,
- 'video/webm': true,
- 'video/ogg': true,
- 'text/plain': true,
- 'text/html': true,
- 'text/xml': true,
- 'application/xhtml+xml': true,
- 'application/json': true
+ 'image/jpeg' : true,
+ 'image/png' : true,
+ 'image/gif' : true,
+ 'image/svg+xml' : true,
+ 'image/bmp' : true,
+ 'image/x-windows-bmp' : true,
+ 'image/webp' : true,
+ 'audio/wav' : true,
+ 'audio/mpeg' : true,
+ 'audio/webm' : true,
+ 'audio/ogg' : true,
+ 'video/mpeg' : true,
+ 'video/webm' : true,
+ 'video/ogg' : true,
+ 'text/plain' : true,
+ 'text/html' : true,
+ 'text/xml' : true,
+ 'application/xhtml+xml' : true,
+ 'application/json' : true
};
if( BlobBuilder && (window.saveAs || navigator.saveBlob) )
@@ -52,20 +53,23 @@ if( BlobBuilder && (window.saveAs || navigator.saveBlob) )
};
}
-else if (BlobBuilder && URL)
+else if( BlobBuilder && URL )
{
fileTextSave = function( data, name, mimetype )
{
- let blob, url, builder = new BlobBuilder();
+ let blob, url;
+ let builder = new BlobBuilder();
builder.append( data );
- if (!mimetype) mimetype = 'application/octet-stream';
- if( downloadNameSupport ) {
- blob = builder.getBlob(mimetype);
- url = URL.createObjectURL(blob);
- let link = document.createElement('a');
- link.setAttribute('href',url);
- link.setAttribute('download',name||'download.txt');
+ if( !mimetype )
+ mimetype = 'application/octet-stream';
+ if( downloadNameSupport )
+ {
+ blob = builder.getBlob( mimetype );
+ url = URL.createObjectURL( blob );
+ let link = document.createElement( 'a' );
+ link.setAttribute( 'href', url );
+ link.setAttribute( 'download', name || 'download.txt' );
let event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
@@ -92,11 +96,11 @@ else if( !/\bMSIE\b/.test(navigator.userAgent) )
fileTextSave = function( data, name, mimetype )
{
- if( !mimetype ) mimetype = 'application/octet-stream';
- if( BrowserSupportedMimeTypes[mimetype.split(';')[0]] === true )
- {
- mimetype = 'application/octet-stream';
- }
+ if( !mimetype )
+ mimetype = 'application/octet-stream';
+ if( BrowserSupportedMimeTypes[ mimetype.split( ';' )[ 0 ] ] === true )
+ mimetype = 'application/octet-stream';
+
window.open( 'data:' + mimetype + ',' + encodeURIComponent( data ), '_blank', '' );
}
|
Fix style of file `Blob.js`
|
Wandalen_wDomBase
|
train
|
ba9fd6cc46725bb5114e7991f955d630720ebd97
|
diff --git a/Pragma/ORM/Model.php b/Pragma/ORM/Model.php
index <HASH>..<HASH> 100644
--- a/Pragma/ORM/Model.php
+++ b/Pragma/ORM/Model.php
@@ -236,7 +236,7 @@ class Model extends QueryBuilder implements SerializableInterface{
//TODO : since we handle multiple columns in pk, check if this is still ok
public static function all($idkey = true){
- return static::forge()->get_objects($idkey);
+ return static::forge()->get_objects($idkey && ! is_array($this->primary_key) ? $this->primary_key : null);
}
//$bypass_ma = bypass_mass_assignment_control : the developper knows what he's doing
diff --git a/Pragma/ORM/QueryBuilder.php b/Pragma/ORM/QueryBuilder.php
index <HASH>..<HASH> 100644
--- a/Pragma/ORM/QueryBuilder.php
+++ b/Pragma/ORM/QueryBuilder.php
@@ -16,6 +16,9 @@ class QueryBuilder{
protected $joins = [];
protected $inclusions = [];
+ const ARRAYS = 1;
+ const OBJECTS = 2;
+
//in order to get an instance on which execute the query
public static function forge($classname = null){
if (!is_null($classname)) {
@@ -93,10 +96,24 @@ class QueryBuilder{
}
public function get_arrays($key = null, $multiple = false, $as_array_fallback = true, $debug = false){
+ return $this->build_arrays_of(self::ARRAYS, $key, $multiple, $as_array_fallback, $debug);
+ }
+
+ public function get_objects($key = null, $multiple = false, $as_array_fallback = true, $debug = false){
+ return $this->build_arrays_of(self::OBJECTS, $key, $multiple, $as_array_fallback, $debug);
+ }
+
+ private function build_arrays_of($type, $key = null, $multiple = false, $as_array_fallback = true, $debug = false){
+ if( ! in_array($type, [self::ARRAYS, self::OBJECTS])){
+ throw new \Exception("Unknown type of data : ".$type);
+ }
$db = DB::getDB();
$list = [];
- if(empty($this->select) && $as_array_fallback){
+ if($type==self::OBJECTS){
+ $this->select = [$this->table . '.*']; // force to load all fields to retrieve full object
+ }
+ else if(empty($this->select) && $as_array_fallback){
$o = new static();
$this->select(array_keys(array_intersect_key($o->as_array(), $o->describe())));
}
@@ -104,15 +121,24 @@ class QueryBuilder{
$rs = $this->get_resultset($debug, true);
while($data = $db->fetchrow($rs)){
+ switch($type){
+ case self::ARRAYS:
+ $val = $data;
+ break;
+ case self::OBJECTS:
+ $val = new static();
+ $val = $val->openWithFields($data);
+ break;
+ }
if(is_null($key) || ! isset($data[$key]) ){
- $list[] = $data;
+ $list[] = $val;
}
else{
if( ! $multiple ){
- $list[$data[$key]] = $data;
+ $list[$data[$key]] = $val;
}
else{
- $list[$data[$key]][] = $data;
+ $list[$data[$key]][] = $val;
}
}
}
@@ -127,56 +153,13 @@ class QueryBuilder{
throw new \Exception("Unknown relation ".$i["rel"]);
}
- $rel->load($list, 'arrays', is_null($i['overriding']) ? [] : $i['overriding']);
+ $rel->load($list, $type == self::ARRAYS ? 'arrays' : 'objects', is_null($i['overriding']) ? [] : $i['overriding']);
}
}
return $list;
}
- public function get_objects($idkey = true, $allowKeyOnId = true, $debug = false){
- $db = DB::getDB();
- $list = [];
-
- $this->select = [$this->table . '.*']; // force to load all fields to retrieve full object
-
- $rs = $this->get_resultset($debug);
-
- while($data = $db->fetchrow($rs)){
- $o = new static();
- $o = $o->openWithFields($data);
- if($idkey){
- $primaryKeys = $o->get_primary_key();
- if(is_array($primaryKeys)){
- // We assumed that the objects using pragma will have as primary key "id"
- if(in_array('id', $primaryKeys) !== false && isset($data['id']) && $allowKeyOnId){
- $list[$data['id']] = $o;
- }else{
- $list[] = $o;
- }
- }elseif(isset($data[$primaryKeys])){
- $list[$data[$primaryKeys]] = $o;
- }else{
- $list[] = $o;
- }
- }
- else{
- $list[] = $o;
- }
- }
-
- if( !empty($list) && !empty($this->inclusions) ){
- foreach($this->inclusions as $i){
- $rel = Relation::get(get_class($o), $i['rel']);
- if( is_null($rel) ){
- throw new \Exception("Unknown relation ".$i['rel']);
- }
- $rel->load($list, 'objects', is_null($i['overriding']) ? [] : $i['overriding']);
- }
- }
- return $list;
- }
-
public function first($debug = false){
$db = DB::getDB();
//force limit to 1 for optimization
|
QueryBuilder > Major update on get_objects allowing to specify the key of the array
no compatibility with previous versions
|
pragma-framework_core
|
train
|
6b40fed4e254ed41a7093b57182259dcefeee3b8
|
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index <HASH>..<HASH> 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -1452,8 +1452,8 @@ module ApplicationTests
test "raises with proper error message if no database configuration found" do
FileUtils.rm("#{app_path}/config/database.yml")
- app "development"
err = assert_raises RuntimeError do
+ app "development"
Rails.application.config.database_configuration
end
assert_match "config/database", err.message
|
Generating the app is where the exception is now raised
|
rails_rails
|
train
|
466c8d7608c8c60b52eeead79cf8656b36b3bddc
|
diff --git a/retry_test.go b/retry_test.go
index <HASH>..<HASH> 100644
--- a/retry_test.go
+++ b/retry_test.go
@@ -12,7 +12,7 @@ func TestRetry(t *testing.T) {
err := Retry(action)
- if nil != err {
+ if err != nil {
t.Error("expected a nil error")
}
}
@@ -71,7 +71,7 @@ func TestRetryRetriesUntilNoErrorReturned(t *testing.T) {
err := Retry(action)
- if nil != err {
+ if err != nil {
t.Error("expected a nil error")
}
|
Fixing some more old "Yoda conditionals"
|
Rican7_retry
|
train
|
8699a622a31a139d4a6094973f169af7a0806f91
|
diff --git a/src/Illuminate/Support/Facades/Cookie.php b/src/Illuminate/Support/Facades/Cookie.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Support/Facades/Cookie.php
+++ b/src/Illuminate/Support/Facades/Cookie.php
@@ -27,7 +27,7 @@ class Cookie extends Facade
*
* @param string $key
* @param mixed $default
- * @return string
+ * @return string|array|null
*/
public static function get($key = null, $default = null)
{
|
[<I>] Cookie::get() doc block fixed. (#<I>)
|
laravel_framework
|
train
|
0021d5776abfe1440fa7e16afdbe7d5451690ef6
|
diff --git a/templates/admin/export.php b/templates/admin/export.php
index <HASH>..<HASH> 100644
--- a/templates/admin/export.php
+++ b/templates/admin/export.php
@@ -108,25 +108,27 @@ if ( ! empty( $_GET['export_warning'] ) && ( get_option( 'pressbooks_email_valid
<form id="pb-export-form" action="<?php echo $export_form_url ?>" method="POST">
<fieldset>
- <legend><?php _e( 'Standard book formats', 'pressbooks' ); ?>:</legend>
- <?php if ( true == \PressBooks\Utility\check_prince_install() ) { ?>
- <input type="checkbox" id="pdf" name="export_formats[pdf]" value="1" /><label for="pdf"> <?php _e( 'PDF (for printing)', 'pressbooks' ); ?></label><br />
- <?php } ;?>
- <?php if ( \PressBooks\Modules\Export\Mpdf\Pdf::isInstalled() ) { ?>
- <input type="checkbox" id="mpdf" name="export_formats[mpdf]" value="1" /><label for="mpdf"> <?php _e( 'PDF (mPDF)', 'pressbooks' ); ?></label><br />
- <?php } ?>
- <input type="checkbox" id="epub" name="export_formats[epub]" value="1" /><label for="epub"> <?php _e( 'EPUB (for Nook, iBooks, Kobo etc.)', 'pressbooks' ); ?></label><br />
- <input type="checkbox" id="mobi" name="export_formats[mobi]" value="1" /><label for="mobi"> <?php _e( 'MOBI (for Kindle)', 'pressbooks' ); ?></label>
+ <legend><?php _e( 'Standard book formats', 'pressbooks' ); ?>:</legend>
+ <?php if ( true == \PressBooks\Utility\check_prince_install() ) { ?>
+ <input type="checkbox" id="pdf" name="export_formats[pdf]" value="1" /><label for="pdf"> <?php _e( 'PDF (for printing)', 'pressbooks' ); ?></label><br />
+ <?php } ;?>
+ <?php if ( \PressBooks\Modules\Export\Mpdf\Pdf::isInstalled() ) { ?>
+ <input type="checkbox" id="mpdf" name="export_formats[mpdf]" value="1" /><label for="mpdf"> <?php _e( 'PDF (mPDF)', 'pressbooks' ); ?></label><br />
+ <?php } ?>
+ <input type="checkbox" id="epub" name="export_formats[epub]" value="1" /><label for="epub"> <?php _e( 'EPUB (for Nook, iBooks, Kobo etc.)', 'pressbooks' ); ?></label><br />
+ <input type="checkbox" id="mobi" name="export_formats[mobi]" value="1" /><label for="mobi"> <?php _e( 'MOBI (for Kindle)', 'pressbooks' ); ?></label>
</fieldset>
<fieldset>
<legend>Exotic formats:</legend>
<input type="checkbox" id="epub3" name="export_formats[epub3]" value="1" /><label for="epub3"> <?php _e( 'EPUB 3 (Beta)', 'pressbooks' ); ?></label><br />
- <input type="checkbox" id="icml" name="export_formats[icml]" value="1" /><label for="icml"> <?php _e( 'ICML (for InDesign)', 'pressbooks' ); ?></label><br />
<input type="checkbox" id="xhtml" name="export_formats[xhtml]" value="1" /><label for="xhtml"> <?php _e( 'XHTML', 'pressbooks' ); ?></label><br />
+ <?php if ( true == \PressBooks\Utility\show_experimental_features() ) { ?><br/>
+ <input type="checkbox" id="icml" name="export_formats[icml]" value="1" /><label for="icml"> <?php _e( 'ICML (for InDesign)', 'pressbooks' ); ?></label><br />
+ <?php } ?>
<input type="checkbox" id="wxr" name="export_formats[wxr]" value="1" /><label for="wxr"> <?php _e( 'Pressbooks XML', 'pressbooks' ); ?></label><br />
<input type="checkbox" id="vanillawxr" name="export_formats[vanillawxr]" value="1" /><label for="vanillawxr"> <?php _e( 'WordPress XML', 'pressbooks' ); ?></label>
- <?php if ( true == \PressBooks\Utility\show_experimental_features() ) { ?><br/>
+ <?php if ( true == \PressBooks\Utility\show_experimental_features() ) { ?><br/>
<input type="checkbox" id="odt" name="export_formats[odt]" value="1" /><label for="odt"> <?php _e( 'ODT', 'pressbooks' ); ?></label>
<?php } ?>
</fieldset>
|
Make ICML an experimental format (closes #<I>).
|
pressbooks_pressbooks
|
train
|
3e8231befe8ab5e71e1036b8f5f719a2a087f853
|
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -608,6 +608,7 @@ QUnit.test('AltField and AltFormat tests', function( assert ) {
SelectedMonth: '05/2010',
Animation: 'none', // Disable animation to make sure opening and closing the menu is synchronous.
AltField: hiddenField,
+ ValidationErrorMessage: 'Invalid Date!',
AltFormat: 'yy-mm'
});
@@ -639,6 +640,23 @@ QUnit.test('AltField and AltFormat tests', function( assert ) {
assert.equal($(SecondaryAltField).val(), '', "The secondary field was cleared.");
+ field.MonthPicker('option', 'SelectedMonth', '06/2016');
+
+ assert.equal(field.val(), '06/2016', 'The main field was populated correctly using the SelectedMonth option.');
+ assert.equal($(SecondaryAltField).val(), '06/2016', "The secondary field was populated correctly using the SelectedMonth option.");
+
+ field.MonthPicker('option', 'SelectedMonth', null);
+
+ assert.equal(field.val(), '', 'The main field was cleared by passing null to the SelectedMonth option.');
+ assert.equal($(SecondaryAltField).val(), '', "The secondary field was cleared by passing null to the SelectedMonth option..");
+
+ assert.equal(field.MonthPicker('GetSelectedMonthYear'), null, 'GetSelectedMonthYear API call returned null when there was no date selected as expected.');
+
+ assert.equal($('#MonthPicker_Validation_MainAltField').css('display'), 'inline', '#MainAltField showed a validation message about a bad date.');
+
+ field.MonthPicker('option', 'SelectedMonth', '06/2016');
+
+ assert.ok($('#MonthPicker_Validation_MainAltField').is(':hidden'), '#MainAltField cleared the validation error message by setting the SelectedMonth option.');
});
|
AltField and SelectedMonth Tests Added
#<I> - Added tests for synching the altField when the SelectedMonth
option is set as well as clearing any validation message. Also added a
test for passing null to the SelectedMonth option.
|
KidSysco_jquery-ui-month-picker
|
train
|
85fc696a2d0e84f472058504f11f484d1ae4c02c
|
diff --git a/applications/jupyter-extension/nteract_on_jupyter/app/contents/file.js b/applications/jupyter-extension/nteract_on_jupyter/app/contents/file.js
index <HASH>..<HASH> 100644
--- a/applications/jupyter-extension/nteract_on_jupyter/app/contents/file.js
+++ b/applications/jupyter-extension/nteract_on_jupyter/app/contents/file.js
@@ -42,6 +42,7 @@ export class TextFile extends React.PureComponent<TextFileProps, null> {
<MonacoEditor
theme="light"
mode={this.props.content.mimetype}
+ focused={true}
options={{
lineNumbers: true,
cursorBlinkRate: 0,
diff --git a/packages/monaco-editor/src/index.js b/packages/monaco-editor/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/monaco-editor/src/index.js
+++ b/packages/monaco-editor/src/index.js
@@ -25,7 +25,8 @@ export type MonacoEditorProps = {
theme: string,
mode: string,
onChange: (value: string) => void,
- value: string
+ value: string,
+ focused: boolean
};
class MonacoEditor extends React.Component<MonacoEditorProps> {
@@ -33,7 +34,8 @@ class MonacoEditor extends React.Component<MonacoEditorProps> {
monacoContainer: ?HTMLElement;
static defaultProps = {
- onChange: null
+ onChange: null,
+ focused: false
};
constructor(props: MonacoEditorProps): void {
@@ -62,6 +64,10 @@ class MonacoEditor extends React.Component<MonacoEditorProps> {
autoIndent: true
});
+ if (this.props.focused) {
+ this.monaco.focus();
+ }
+
this.monaco.onDidChangeModelContent(
this.onDidChangeModelContent.bind(this)
);
|
Set focus on text editor when file is opened
|
nteract_nteract
|
train
|
f2ab87b6ac5e7d7a4c89328e33b85c8d5c0d3047
|
diff --git a/test/e2e/disruption.go b/test/e2e/disruption.go
index <HASH>..<HASH> 100644
--- a/test/e2e/disruption.go
+++ b/test/e2e/disruption.go
@@ -113,7 +113,8 @@ var _ = framework.KubeDescribe("DisruptionController", func() {
shouldDeny: true,
},
}
- for _, c := range evictionCases {
+ for i := range evictionCases {
+ c := evictionCases[i]
expectation := "should allow an eviction"
if c.shouldDeny {
expectation = "should not allow an eviction"
|
Stop referring to loop variable inside closure.
|
kubernetes_kubernetes
|
train
|
feab3e333103ffa54f946668c59648d678375cc3
|
diff --git a/lib/travis/model/repository.rb b/lib/travis/model/repository.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/model/repository.rb
+++ b/lib/travis/model/repository.rb
@@ -57,7 +57,7 @@ class Repository < ActiveRecord::Base
end
def by_member(login_name)
- User.where(:login => login_name).repositories
+ User.where(:login => login_name).first.repositories
end
def by_slug(slug)
|
oops, need to do .first as well
|
travis-ci_travis-core
|
train
|
b9b2c8241c25a548def5ebd5288849345ebb8c06
|
diff --git a/Oauth2.php b/Oauth2.php
index <HASH>..<HASH> 100644
--- a/Oauth2.php
+++ b/Oauth2.php
@@ -67,7 +67,7 @@ class Oauth2
//fetch profile of current user
$_SESSION["CurrentUser"] = $oProfile = json_decode($this->run_curl($profile_url, 'GET'));
//check to see if current user is in the list
- if(count($this->oCreds->Users) > 0){
+ if(isset($this->oCreds->Users)){
foreach($this->oCreds->Users as $sEmail){
if($sEmail == $oProfile->email)return $oProfile;
}
|
still trying to make it work whether the creds has a user in it or not
|
rhildred_oauth2
|
train
|
9b47cfe8d9e2d760bfdb23fe16462d671871a50a
|
diff --git a/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb b/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb
index <HASH>..<HASH> 100644
--- a/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb
+++ b/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb
@@ -43,11 +43,12 @@ module Commander
end
def handle_unknown_error!(e)
- # Some spaceship exception classes implement this method in order to share error information sent by Apple.
- # However, fastlane_core and spaceship can not know about each other's classes! To make this information
- # passing work, we use a bit of Ruby duck-typing to check whether the unknown exception type implements
- # the right method. If so, we'll present any returned error info in the manner of a user_error!
- error_info = e.respond_to?(:apple_provided_error_info) ? e.apple_provided_error_info : nil
+ # Some spaceship exception classes implement #preferred_error_info in order to share error info
+ # that we'd rather display instead of crashing with a stack trace. However, fastlane_core and
+ # spaceship can not know about each other's classes! To make this information passing work, we
+ # use a bit of Ruby duck-typing to check whether the unknown exception type implements the right
+ # method. If so, we'll present any returned error info in the manner of a user_error!
+ error_info = e.respond_to?(:preferred_error_info) ? e.preferred_error_info : nil
if error_info
message = error_info.unshift("Apple provided the following error info:").join("\n\t")
diff --git a/fastlane_core/spec/fastlane_runner_spec.rb b/fastlane_core/spec/fastlane_runner_spec.rb
index <HASH>..<HASH> 100644
--- a/fastlane_core/spec/fastlane_runner_spec.rb
+++ b/fastlane_core/spec/fastlane_runner_spec.rb
@@ -3,13 +3,13 @@ require 'spec_helper'
describe Commander::Runner do
describe '#handle_unknown_error' do
class CustomError < StandardError
- def apple_provided_error_info
+ def preferred_error_info
['Line 1', 'Line 2']
end
end
class NilReturningError < StandardError
- def apple_provided_error_info
+ def preferred_error_info
nil
end
end
@@ -20,7 +20,7 @@ describe Commander::Runner do
end.to raise_error(StandardError, '[!] my message'.red)
end
- it 'should reraise errors that return nil from #apple_provided_error_info' do
+ it 'should reraise errors that return nil from #preferred_error_info' do
expect do
Commander::Runner.new.handle_unknown_error!(NilReturningError.new('my message'))
end.to raise_error(StandardError, '[!] my message'.red)
diff --git a/spaceship/lib/spaceship/client.rb b/spaceship/lib/spaceship/client.rb
index <HASH>..<HASH> 100644
--- a/spaceship/lib/spaceship/client.rb
+++ b/spaceship/lib/spaceship/client.rb
@@ -28,15 +28,20 @@ module Spaceship
# /tmp/spaceship[time]_[pid].log by default
attr_accessor :logger
- # Invalid user credentials were provided
- class InvalidUserCredentialsError < StandardError
- def apple_provided_error_info
+ # Base class for errors that want to present their message as
+ # preferred error info for fastlane error handling. See:
+ # fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb
+ class BasicPreferredInfoError < StandardError
+ def preferred_error_info
message ? [message] : nil
end
end
+ # Invalid user credentials were provided
+ class InvalidUserCredentialsError < BasicPreferredInfoError; end
+
# Raised when no user credentials were passed at all
- class NoUserCredentialsError < StandardError; end
+ class NoUserCredentialsError < BasicPreferredInfoError; end
class UnexpectedResponse < StandardError
attr_reader :error_info
@@ -46,18 +51,18 @@ module Spaceship
@error_info = error_info
end
- def apple_provided_error_info
- return nil unless @error_info.is_a?(Hash) && @error_info['resultString']
+ def preferred_error_info
+ return nil unless @error_info.kind_of?(Hash) && @error_info['resultString']
[@error_info['resultString'], @error_info['userString']].compact.uniq
end
end
# Raised when 302 is received from portal request
- class AppleTimeoutError < StandardError; end
+ class AppleTimeoutError < BasicPreferredInfoError; end
# Raised when 401 is received from portal request
- class UnauthorizedAccessError < StandardError; end
+ class UnauthorizedAccessError < BasicPreferredInfoError; end
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
diff --git a/spaceship/lib/spaceship/tunes/tunes_client.rb b/spaceship/lib/spaceship/tunes/tunes_client.rb
index <HASH>..<HASH> 100644
--- a/spaceship/lib/spaceship/tunes/tunes_client.rb
+++ b/spaceship/lib/spaceship/tunes/tunes_client.rb
@@ -2,7 +2,7 @@ module Spaceship
# rubocop:disable Metrics/ClassLength
class TunesClient < Spaceship::Client
# ITunesConnectError is only thrown when iTunes Connect raises an exception
- class ITunesConnectError < StandardError
+ class ITunesConnectError < BasicPreferredInfoError
end
# raised if the server failed to save temporarily
|
Implement BasicPreferredInfoError and use it for most other client exceptions
|
fastlane_fastlane
|
train
|
7b3e9c98f2d329905965627f80b9835d4db6495c
|
diff --git a/app/controllers/rails_workflow/application_controller.rb b/app/controllers/rails_workflow/application_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/application_controller.rb
+++ b/app/controllers/rails_workflow/application_controller.rb
@@ -1,10 +1,11 @@
module RailsWorkflow
- class ApplicationController < ActionController::Base
+ class ApplicationController < ::ApplicationController
before_filter only: [:index, :show, :edit] do
RailsWorkflow::OperationTemplate.inheritance_column = nil
RailsWorkflow::Operation.inheritance_column = nil
RailsWorkflow::ProcessTemplate.inheritance_column = nil
end
+ # before_action :authenticate_user!
end
end
diff --git a/app/controllers/rails_workflow/errors_controller.rb b/app/controllers/rails_workflow/errors_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/errors_controller.rb
+++ b/app/controllers/rails_workflow/errors_controller.rb
@@ -1,5 +1,5 @@
module RailsWorkflow
- class ErrorsController < ActionController::Base
+ class ErrorsController < ApplicationController
def retry
process = RailsWorkflow::Process.find(permitted_params[:process_id])
diff --git a/app/controllers/rails_workflow/operation_templates_controller.rb b/app/controllers/rails_workflow/operation_templates_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/operation_templates_controller.rb
+++ b/app/controllers/rails_workflow/operation_templates_controller.rb
@@ -1,5 +1,5 @@
module RailsWorkflow
- class OperationTemplatesController < ::ActionController::Base
+ class OperationTemplatesController < ApplicationController
layout 'rails_workflow/application'
before_action :set_operation_template, only: [:show, :edit, :update, :destroy]
before_action :set_process_template
diff --git a/app/controllers/rails_workflow/operations_controller.rb b/app/controllers/rails_workflow/operations_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/operations_controller.rb
+++ b/app/controllers/rails_workflow/operations_controller.rb
@@ -1,5 +1,5 @@
module RailsWorkflow
- class OperationsController < ::ActionController::Base
+ class OperationsController < ApplicationController
layout 'rails_workflow/application'
respond_to :html
diff --git a/app/controllers/rails_workflow/process_templates_controller.rb b/app/controllers/rails_workflow/process_templates_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/process_templates_controller.rb
+++ b/app/controllers/rails_workflow/process_templates_controller.rb
@@ -1,5 +1,5 @@
module RailsWorkflow
- class ProcessTemplatesController < ::ActionController::Base
+ class ProcessTemplatesController < ApplicationController
layout 'rails_workflow/application'
respond_to :html, :json
diff --git a/app/controllers/rails_workflow/processes_controller.rb b/app/controllers/rails_workflow/processes_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rails_workflow/processes_controller.rb
+++ b/app/controllers/rails_workflow/processes_controller.rb
@@ -1,5 +1,5 @@
module RailsWorkflow
- class ProcessesController < ::ActionController::Base
+ class ProcessesController < ApplicationController
layout 'rails_workflow/application'
respond_to :html
before_action :set_process, only: [:show, :edit, :update, :destroy]
diff --git a/spec/controllers/rails_workflow/operation_templates_controller_spec.rb b/spec/controllers/rails_workflow/operation_templates_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/rails_workflow/operation_templates_controller_spec.rb
+++ b/spec/controllers/rails_workflow/operation_templates_controller_spec.rb
@@ -86,10 +86,7 @@ module RailsWorkflow
process_template_id: @template.id,
operation_template: valid_attributes
}, valid_session, use_route: :workflow
- }.to change(OperationTemplate, :count).by(1)
-
- last_operation = OperationTemplate.last
- expect(last_operation).to be_instance_of(RailsWorkflow::CustomOperationTemplate)
+ }.to change(RailsWorkflow::CustomOperationTemplate, :count).by(1)
end
it "assigns a newly created operation_template as @operation_template" do
diff --git a/spec/models/rails_workflow/operation_template_spec.rb b/spec/models/rails_workflow/operation_template_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/rails_workflow/operation_template_spec.rb
+++ b/spec/models/rails_workflow/operation_template_spec.rb
@@ -6,15 +6,14 @@ module RailsWorkflow
let(:template) { create :process_template }
it 'should create operation template of a given type' do
- operation_template = OperationTemplate.
+ expect{OperationTemplate.
create! (
{
title: 'First Test project',
process_template_id: template.id,
type: "RailsWorkflow::CustomOperationTemplate"
}
- )
- expect(operation_template).to be_instance_of(RailsWorkflow::CustomOperationTemplate)
+ )}.to change(RailsWorkflow::CustomOperationTemplate, :count).by(1)
end
it 'should return only independent operations' do
|
change controllers to inherit main application controller
|
madzhuga_rails_workflow
|
train
|
6b08e4d37d39313740a64718dbfd8bc2a8f33679
|
diff --git a/linkedlist/linkedlist.go b/linkedlist/linkedlist.go
index <HASH>..<HASH> 100644
--- a/linkedlist/linkedlist.go
+++ b/linkedlist/linkedlist.go
@@ -593,6 +593,8 @@ func (sd *storedData) Remove() error {
}
// Let the Go Garbage Collector do its job.
+ sd.key = nil
+ sd.value = nil
sd = nil
return nil
})
|
Update Delete() method to avoid memory leaks
|
xyproto_simplebolt
|
train
|
f404aab1a6bf9b1aba6c259b5e5eaf85eb340c06
|
diff --git a/Cache/Cache.php b/Cache/Cache.php
index <HASH>..<HASH> 100644
--- a/Cache/Cache.php
+++ b/Cache/Cache.php
@@ -145,7 +145,7 @@ class Cache extends Helper implements CacheInterface
$driver = &$config['driver'];
$config = &$config['config'];
- return new static::$driver[$driver]($config);
+ return new self::$driver[$driver]($config);
}
/**
|
fix usage of private Cache::$driver
|
PHPColibri_framework
|
train
|
be85e744c3b48f0ce5d6052fc463178778a939e6
|
diff --git a/easyhid/easyhid.py b/easyhid/easyhid.py
index <HASH>..<HASH> 100755
--- a/easyhid/easyhid.py
+++ b/easyhid/easyhid.py
@@ -8,6 +8,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import cffi
import ctypes.util
import platform
+import sys
ffi = cffi.FFI()
ffi.cdef("""
@@ -59,9 +60,16 @@ elif "Darwin" in platform.platform():
hidapi = ffi.dlopen(ctypes.util.find_library('hidapi'))
else:
try:
- hidapi = ffi.dlopen('hidapi-libusb')
+ hidapi = ffi.dlopen('hidapi-hidraw')
except:
- hidapi = ffi.dlopen(ctypes.util.find_library('hidapi-libusb'))
+ libname = ctypes.util.find_library('hidapi-hidraw')
+
+ if sys.version_info < (3, 6) and libname == None:
+ # Couldn't find lib, use hardcode value so AppImage works.
+ # Not need in >= 3.6 since ctypes.util.find_library will also
+ # check LD_LIBRARY_PATH in newer versions of python.
+ libname = 'libhidapi-hidraw.so.0'
+ hidapi = ffi.dlopen(libname)
def _c_to_py_str(val):
if val == ffi.NULL:
@@ -176,7 +184,7 @@ class HIDDevice(object):
data = [0] * size
cdata = ffi.new("unsigned char[]", data)
- bytes_read = 0
+ bytes_read = None
if timeout == None:
bytes_read = hidapi.hid_read(self._device, cdata, len(cdata))
@@ -187,7 +195,7 @@ class HIDDevice(object):
if bytes_read < 0:
raise HIDException("Failed to read from HID device: " + str(bytes_read))
elif bytes_read == 0:
- return []
+ return bytearray([])
else:
return bytearray(cdata)
diff --git a/easyhid/version.py b/easyhid/version.py
index <HASH>..<HASH> 100644
--- a/easyhid/version.py
+++ b/easyhid/version.py
@@ -1 +1 @@
-__version__ = '0.0.9'
+__version__ = '0.0.10'
|
change linux backend to hidraw for BT devices
|
ahtn_python-easyhid
|
train
|
008005e38c3c7cbba69191eac2429edf6b180fbb
|
diff --git a/src/astral/__init__.py b/src/astral/__init__.py
index <HASH>..<HASH> 100644
--- a/src/astral/__init__.py
+++ b/src/astral/__init__.py
@@ -30,12 +30,12 @@ For example ::
>>> from astral.geocoder import database, lookup
>>> db = database()
>>> location = lookup('London', db)
- >>> print('Information for %s' % location.name)
+ >>> print(f"Information for {location.name}")
Information for London
>>> timezone = location.timezone
>>> print('Timezone: %s' % timezone)
Timezone: Europe/London
- >>> print('Latitude: %.02f; Longitude: %.02f' % (location.latitude, location.longitude))
+ >>> print(f"Latitude: {location.latitude:.02f}; Longitude: {location.longitude:.02f}")
Latitude: 51.47; Longitude: -0.00
>>> from datetime import date
>>> import astral.sun
@@ -43,8 +43,8 @@ For example ::
>>> import pytz
>>> tzinfo = pytz.timezone(timezone)
>>> sun = astral.sun.sun(location, date=d, tzinfo=tzinfo)
- >>> print('Dawn: %s' % str(sun['dawn']))
- Dawn: 2009-04-22 05:12:56+01:00
+ >>> print(f"Dawn: {sun['dawn']}")
+ Dawn: 2009-04-22 05:12:32.529612+01:00
.. note::
|
Changed to use f-strings
|
sffjunkie_astral
|
train
|
9eac2edd509f021beac792fed6f884724be6fbf3
|
diff --git a/docs/guide/08-Logging.txt b/docs/guide/08-Logging.txt
index <HASH>..<HASH> 100644
--- a/docs/guide/08-Logging.txt
+++ b/docs/guide/08-Logging.txt
@@ -361,7 +361,7 @@ $allMethods = array(
'DebugPDOStatement::bindValue' // logs the value and type for each bind
);
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
-$config->setParameter('debugpdo.logging.methods', $allMethods);
+$config->setParameter('debugpdo.logging.methods', $allMethods, false);
}}}
By default, only the messages coming from `PropelPDO::exec`, `PropelPDO::query`, and `DebugPDOStatement::execute` are logged.
diff --git a/runtime/lib/config/PropelConfiguration.php b/runtime/lib/config/PropelConfiguration.php
index <HASH>..<HASH> 100644
--- a/runtime/lib/config/PropelConfiguration.php
+++ b/runtime/lib/config/PropelConfiguration.php
@@ -124,7 +124,7 @@ class PropelConfiguration implements ArrayAccess
* @param string $name Configuration item name (name.space.name)
* @param mixed $value Value to be stored
*/
- public function setParameter($name, $value)
+ public function setParameter($name, $value, $autoFlattenArrays = true)
{
$param = &$this->parameters;
$parts = explode('.', $name); //name.space.name
@@ -132,7 +132,7 @@ class PropelConfiguration implements ArrayAccess
$param = &$param[$part];
}
$param = $value;
- if (is_array($value)) {
+ if (is_array($value) && $autoFlattenArrays) {
// The list will need to be re-flattened.
$this->isFlattened = false;
} else {
diff --git a/test/testsuite/runtime/connection/PropelPDOTest.php b/test/testsuite/runtime/connection/PropelPDOTest.php
index <HASH>..<HASH> 100644
--- a/test/testsuite/runtime/connection/PropelPDOTest.php
+++ b/test/testsuite/runtime/connection/PropelPDOTest.php
@@ -408,7 +408,7 @@ class PropelPDOTest extends PHPUnit_Framework_TestCase
$con->setLogger($testLog);
$logEverything = array('PropelPDO::exec', 'PropelPDO::query', 'PropelPDO::beginTransaction', 'PropelPDO::commit', 'PropelPDO::rollBack', 'DebugPDOStatement::execute');
- Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->setParameter("debugpdo.logging.methods", $logEverything);
+ Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->setParameter("debugpdo.logging.methods", $logEverything, false);
$con->useDebug(true);
// test transaction log
|
[<I>] Fixed logging of methods (refs #<I>)
|
propelorm_Propel
|
train
|
5680c5ad5cb7b1e65cb9600b36a88be829a1ff75
|
diff --git a/perceval/backends/core/pagure.py b/perceval/backends/core/pagure.py
index <HASH>..<HASH> 100644
--- a/perceval/backends/core/pagure.py
+++ b/perceval/backends/core/pagure.py
@@ -67,7 +67,7 @@ class Pagure(Backend):
of connection problems
:param ssl_verify: enable/disable SSL verification
"""
- version = '0.1.0'
+ version = '0.1.1'
CATEGORIES = [CATEGORY_ISSUE]
@@ -295,7 +295,7 @@ class PagureClient(HttpClient):
try:
response = super().fetch(url, payload, headers)
except requests.exceptions.HTTPError as error:
- if error.response.status_code == 404 and error.response.reason == 'NOT FOUND':
+ if error.response.status_code == 404 and str(error.response.reason).upper() == 'NOT FOUND':
logger.warning("The issue tracker is disabled please enable the feature for the repository")
return None
else:
diff --git a/tests/test_pagure.py b/tests/test_pagure.py
index <HASH>..<HASH> 100644
--- a/tests/test_pagure.py
+++ b/tests/test_pagure.py
@@ -48,7 +48,7 @@ PAGURE_ISSUES_URL = PAGURE_REPO_URL + "/issues"
PAGURE_REPO_URL_DISABLED_URL = PAGURE_API_URL + "/Project-test-example"
PAGURE_ISSUES_DISABLED_URL = PAGURE_REPO_URL_DISABLED_URL + "/issues"
-PAGURE_NAMESPACE_REPO_URL = PAGURE_API_URL + "Test-group/Project-namespace-example"
+PAGURE_NAMESPACE_REPO_URL = PAGURE_API_URL + "/Test-group/Project-namespace-example"
PAGURE_NAMESPACE_ISSUES_URL = PAGURE_NAMESPACE_REPO_URL + "/issues"
@@ -155,7 +155,7 @@ class TestPagureBackend(unittest.TestCase):
body = read_file('data/pagure/pagure_empty_request')
httpretty.register_uri(httpretty.GET,
- PAGURE_ISSUES_URL,
+ PAGURE_ISSUES_DISABLED_URL,
body=body,
status=404,
)
@@ -164,7 +164,6 @@ class TestPagureBackend(unittest.TestCase):
with self.assertLogs(logger, level='WARN') as cm:
issues = [issues for issues in pagure.fetch(from_date=None, to_date=None)]
- print(cm.output[0])
self.assertEqual(cm.output[0], 'WARNING:perceval.backends.core.pagure:'
'The issue tracker is disabled please enable'
' the feature for the repository')
|
[pagure] Fix failing tests
This commit fixes failing tests
for Pagure backend.
|
chaoss_grimoirelab-perceval
|
train
|
04b0d9689207a32476b2477ba6529d1db466ded0
|
diff --git a/src/ORM/Table.php b/src/ORM/Table.php
index <HASH>..<HASH> 100644
--- a/src/ORM/Table.php
+++ b/src/ORM/Table.php
@@ -1787,7 +1787,7 @@ class Table implements RepositoryInterface, EventListenerInterface
));
}
foreach ($fields as $field) {
- $conditions[$this->alias() . '.' . $field] = array_shift($args);
+ $conditions[$this->aliasField($field)] = array_shift($args);
}
return $conditions;
};
|
Aliasing fields with built-in method
|
cakephp_cakephp
|
train
|
e9a8dd8f060afe31c10b46cbcb0603000d127817
|
diff --git a/src/base/error_mixin.js b/src/base/error_mixin.js
index <HASH>..<HASH> 100644
--- a/src/base/error_mixin.js
+++ b/src/base/error_mixin.js
@@ -9,25 +9,25 @@ const ErrorMixin = {
* @return {Object} Object with formatted error data including origin and scope
*/
createError(error) {
- !this.name && (this.name = this.constructor && this.constructor.type || 'errorMixin')
- if (!this.playerError) {
- Log.warn(this.name, 'PlayerError is not defined. Error: ', error)
- return error
- }
+ const scope = this.constructor && this.constructor.type || 'errorMixin'
+ const origin = this.name || scope
const defaultError = {
description: '',
level: PlayerError.Levels.FATAL,
- origin: this.name,
- scope: this.name,
+ origin,
+ scope,
raw: {},
}
const errorData = Object.assign({}, defaultError, error, {
- code: `${this.name}:${error && error.code || 'unknown'}`
+ code: `${origin}:${error && error.code || 'unknown'}`
})
- this.playerError.error(errorData)
+ if (this.playerError)
+ this.playerError.error(errorData)
+ else
+ Log.warn(origin, 'PlayerError is not defined. Error: ', errorData)
return errorData
}
|
fix(error_mixin): set scope as component type instead of name
|
clappr_clappr
|
train
|
1d1675fc991ffe155cca0735182f0203119bf771
|
diff --git a/lxd/cluster/membership.go b/lxd/cluster/membership.go
index <HASH>..<HASH> 100644
--- a/lxd/cluster/membership.go
+++ b/lxd/cluster/membership.go
@@ -20,6 +20,7 @@ import (
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/log15"
+ log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/version"
"github.com/pkg/errors"
@@ -596,18 +597,23 @@ func Rebalance(state *state.State, gateway *Gateway) (string, []db.RaftNode, err
return "", nodes, nil
}
+ address, err := node.ClusterAddress(state.Node)
+ if err != nil {
+ return "", nil, err
+ }
+
// Check if we have a spare node that we can promote to the missing role.
- address := candidates[0].Address
- logger.Infof("Found node %s whose role needs to be changed to %s", address, role)
+ candidateAddress := candidates[0].Address
+ logger.Info("Found cluster member whose role needs to be changed", log.Ctx{"candidateAddress": candidateAddress, "newRole": role, "address": address})
for i, node := range nodes {
- if node.Address == address {
+ if node.Address == candidateAddress {
nodes[i].Role = role
break
}
}
- return address, nodes, nil
+ return candidateAddress, nodes, nil
}
// Assign a new role to the local dqlite node.
|
lxd/cluster/membership: Improve logging in Rebalance
|
lxc_lxd
|
train
|
403454f5a781841f49eae044d0ba7216aea6d62e
|
diff --git a/library/src/main/java/de/mrapp/android/dialog/decorator/AnimateableDialogDecorator.java b/library/src/main/java/de/mrapp/android/dialog/decorator/AnimateableDialogDecorator.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/de/mrapp/android/dialog/decorator/AnimateableDialogDecorator.java
+++ b/library/src/main/java/de/mrapp/android/dialog/decorator/AnimateableDialogDecorator.java
@@ -13,6 +13,7 @@
*/
package de.mrapp.android.dialog.decorator;
+import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.os.Bundle;
import android.support.annotation.NonNull;
@@ -176,7 +177,8 @@ public class AnimateableDialogDecorator extends AbstractDialogDecorator<HeaderDi
ViewPropertyAnimator animator =
view.animate().setInterpolator(animation.getInterpolator())
.setDuration(Math.round(animation.getDuration() * durationScale))
- .setStartDelay(animation.getStartDelay()).setListener(listener);
+ .setStartDelay(animation.getStartDelay())
+ .setListener(createHideAnimationListener(view, listener));
float translationX = 0;
float translationY = 0;
@@ -227,6 +229,55 @@ public class AnimateableDialogDecorator extends AbstractDialogDecorator<HeaderDi
}
/**
+ * Creates and returns an animation listener, which allows to hide the animated view once the
+ * animation is finished.
+ *
+ * @param view
+ * The animated view as an instance of the class {@link View}. The view may not be null
+ * @param listener
+ * The listener, which should be notified, as an instance of the type {@link
+ * AnimatorListener} or null, if no listener should be notified
+ * @return The animation listener, which has been created, as an instance of the type {@link
+ * AnimatorListener}
+ */
+ private AnimatorListener createHideAnimationListener(@NonNull final View view,
+ @Nullable final AnimatorListener listener) {
+ return new AnimatorListener() {
+
+ @Override
+ public void onAnimationStart(final Animator animation) {
+ if (listener != null) {
+ listener.onAnimationStart(animation);
+ }
+ }
+
+ @Override
+ public void onAnimationEnd(final Animator animation) {
+ view.setVisibility(View.GONE);
+
+ if (listener != null) {
+ listener.onAnimationEnd(animation);
+ }
+ }
+
+ @Override
+ public void onAnimationCancel(final Animator animation) {
+ if (listener != null) {
+ listener.onAnimationCancel(animation);
+ }
+ }
+
+ @Override
+ public void onAnimationRepeat(final Animator animation) {
+ if (listener != null) {
+ listener.onAnimationRepeat(animation);
+ }
+ }
+
+ };
+ }
+
+ /**
* Creates a new decorator, which allows to modify the view hierarchy of an animateable dialog,
* which is designed according to Android 5's Material design guidelines even on pre-Lollipop
* devices.
|
A dialog's root view does now become hidden once the animation, which is used to hide the dialog, has finished.
|
michael-rapp_AndroidMaterialDialog
|
train
|
cfc6872df9c6e541df3c87ecbfad5dd9211f74d5
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -89,6 +89,7 @@ controller or added a new module you need to rename `feature` to `component`.
- **decidim-surveys**: Max choices selector not disabled when survey has already been answered [\#3133](https://github.com/decidim/decidim/pull/3133)
- **decidim-surveys**: Translated fields not disabled when survey has already been answered [\#3133](https://github.com/decidim/decidim/pull/3133)
- **decidim-admin**: Default managed user form displaying two buttons [\#3211](https://github.com/decidim/decidim/pull/3211)
+- **decidim-admin**: Highlighted banner image is not required if already present in the organization [\#3244](https://github.com/decidim/decidim/pull/3244)
- **decidim-proposals**: Keep the user group (if set) as default value of author field on forms [\#3247](https://github.com/decidim/decidim/pull/3247)
Please check [0.10-stable](https://github.com/decidim/decidim/blob/0.10-stable/CHANGELOG.md) for previous changes.
diff --git a/decidim-admin/app/forms/decidim/admin/organization_appearance_form.rb b/decidim-admin/app/forms/decidim/admin/organization_appearance_form.rb
index <HASH>..<HASH> 100644
--- a/decidim-admin/app/forms/decidim/admin/organization_appearance_form.rb
+++ b/decidim-admin/app/forms/decidim/admin/organization_appearance_form.rb
@@ -54,7 +54,7 @@ module Decidim
presence: true,
file_size: { less_than_or_equal_to: ->(_record) { Decidim.maximum_attachment_size } },
file_content_type: { allow: ["image/jpeg", "image/png"] },
- if: :highlighted_content_banner_enabled?
+ if: :highlighted_content_banner_image_is_changed?
validates :highlighted_content_banner_title,
translatable_presence: true,
@@ -81,6 +81,11 @@ module Decidim
def enable_omnipresent_banner?
enable_omnipresent_banner
end
+
+ def highlighted_content_banner_image_is_changed?
+ highlighted_content_banner_enabled? &&
+ current_organization.highlighted_content_banner_image.blank?
+ end
end
end
end
diff --git a/decidim-admin/spec/forms/organization_appearance_form_spec.rb b/decidim-admin/spec/forms/organization_appearance_form_spec.rb
index <HASH>..<HASH> 100644
--- a/decidim-admin/spec/forms/organization_appearance_form_spec.rb
+++ b/decidim-admin/spec/forms/organization_appearance_form_spec.rb
@@ -145,6 +145,13 @@ module Decidim
let(:highlighted_content_banner_image) { "" }
it { is_expected.not_to be_valid }
+
+ context "and the organization already has an image set" do
+ let(:organization) { create :organization, highlighted_content_banner_image: Decidim::Dev.test_file("city.jpeg", "image/jpeg") }
+ let(:highlighted_content_banner_image) { nil }
+
+ it { is_expected.to be_valid }
+ end
end
end
|
Do not require highlighted banner image if already present in organization (#<I>)
* Do not require highlighted banner image if already present in org
* Add changelog
* Rubocop autofixes
|
decidim_decidim
|
train
|
0a94a0f5b99af8bfa477c05bdda5de047f66b8ae
|
diff --git a/frontend/widgets/assets/src/js/combination.js b/frontend/widgets/assets/src/js/combination.js
index <HASH>..<HASH> 100755
--- a/frontend/widgets/assets/src/js/combination.js
+++ b/frontend/widgets/assets/src/js/combination.js
@@ -32,6 +32,8 @@ $(document).ready(function() {
success: function (data) {
data = JSON.parse(data);
+ if(!data) $('#add-to-cart-button').attr('disabled','disabled');
+ else $('#add-to-cart-button').removeAttr('disabled');
var price = (data.price) ? data.price : priceTag.data('default-value');
priceTag.text(price);
@@ -39,6 +41,7 @@ $(document).ready(function() {
$('img.zoomImg').attr('src', data.image);
},
error: function (data) {
+ alert('sdfg');
priceTag.text('Нет в наличии');
}
});
|
Adds disable attribute to product add-to-cart button.
|
black-lamp_blcms-shop
|
train
|
aed18395c960a18c0ab7e510598808e48236fdeb
|
diff --git a/wal/wal_bench_test.go b/wal/wal_bench_test.go
index <HASH>..<HASH> 100644
--- a/wal/wal_bench_test.go
+++ b/wal/wal_bench_test.go
@@ -53,6 +53,7 @@ func benchmarkWriteEntry(b *testing.B, size int, batch int) {
b.ResetTimer()
n := 0
+ b.SetBytes(int64(e.Size()))
for i := 0; i < b.N; i++ {
err := w.saveEntry(e)
if err != nil {
|
wal: report throughput in wal bench
|
etcd-io_etcd
|
train
|
aeb999389b0bff6db17566af2647a0a09f980cad
|
diff --git a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobCoordinationService.java b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobCoordinationService.java
index <HASH>..<HASH> 100644
--- a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobCoordinationService.java
+++ b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/JobCoordinationService.java
@@ -130,6 +130,7 @@ public class JobCoordinationService {
}
public void reset() {
+ assert !isMaster() : "this member is a master";
masterContexts.values().forEach(ctx -> ctx.setFinalResult(new CancellationException()));
masterContexts.clear();
}
diff --git a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/MasterContext.java b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/MasterContext.java
index <HASH>..<HASH> 100644
--- a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/MasterContext.java
+++ b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/MasterContext.java
@@ -610,7 +610,9 @@ public class MasterContext {
Collection<MemberInfo> successfulMembers = grouped.get(false).stream().map(Entry::getKey).collect(toList());
List<Entry<MemberInfo, Object>> failures = grouped.get(true);
- logger.fine(opName + " of " + jobIdString() + " has failures: " + failures);
+ if (!failures.isEmpty()) {
+ logger.fine(opName + " of " + jobIdString() + " has failures: " + failures);
+ }
TerminationMode mode = requestedTerminationMode;
if (mode == CANCEL) {
diff --git a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/execution/ExecutionContext.java b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/execution/ExecutionContext.java
index <HASH>..<HASH> 100644
--- a/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/execution/ExecutionContext.java
+++ b/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/execution/ExecutionContext.java
@@ -187,7 +187,7 @@ public class ExecutionContext {
// if cancelled before execution started, then assign the already completed future.
executionFuture = cancellationFuture;
}
- snapshotContext().cancel();
+ snapshotContext.cancel();
return executionFuture;
}
}
diff --git a/hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/SplitBrainTest.java b/hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/SplitBrainTest.java
index <HASH>..<HASH> 100644
--- a/hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/SplitBrainTest.java
+++ b/hazelcast-jet-core/src/test/java/com/hazelcast/jet/core/SplitBrainTest.java
@@ -106,7 +106,7 @@ public class SplitBrainTest extends JetSplitBrainTestSupport {
});
assertTrueAllTheTime(() -> {
- assertEquals(NOT_RUNNING, service2.getJobCoordinationService().getJobStatus(jobId));
+ assertStatusNotRunningOrStarting(service2.getJobCoordinationService().getJobStatus(jobId));
}, 20);
};
@@ -373,9 +373,10 @@ public class SplitBrainTest extends JetSplitBrainTestSupport {
Job jobRef2 = secondSubCluster[0].getJob(jobRef[0].getId());
assertNotNull("jobRef1", jobRef1);
assertNotNull("jobRef2", jobRef2);
- assertTrueEventually(() -> assertEquals("job not running on subcluster 1", RUNNING, jobRef1.getStatus()), 10);
- assertTrueEventually(() -> assertEquals("job not running on subcluster 2", RUNNING, jobRef2.getStatus()), 10);
- assertEquals("initCount", clusterSize * 2, MockPS.initCount.get());
+ assertTrueEventually(() -> assertEquals("job not running on subcluster 1", RUNNING, jobRef1.getStatus()));
+ assertTrueEventually(() -> assertEquals("job not running on subcluster 2", RUNNING, jobRef2.getStatus()));
+ // we need assert-eventually here because we might observe RUNNING state from an execution before the split
+ assertTrueEventually(() -> assertEquals("initCount", clusterSize * 2, MockPS.initCount.get()));
};
Consumer<JetInstance[]> afterMerge = instances -> {
|
Split brain test fixes (#<I>)
|
hazelcast_hazelcast
|
train
|
d4fb3eba91e8902417a751412a0e6d80662ca219
|
diff --git a/gpapi/googleplay.py b/gpapi/googleplay.py
index <HASH>..<HASH> 100644
--- a/gpapi/googleplay.py
+++ b/gpapi/googleplay.py
@@ -8,7 +8,6 @@ from Crypto.Cipher import PKCS1_OAEP
from clint.textui import progress
import requests
-import sys
import base64
import itertools
@@ -178,10 +177,9 @@ class GooglePlayAPI(object):
ac2dmToken = params["auth"]
elif "error" in params:
if "NeedsBrowser" in params["error"]:
- print("\nsecurity check is needed, try to visit\n"
- "https://accounts.google.com/b/0/DisplayUnlockCaptcha\n"
- "if you use 2FA it is recommended to setup an app specific password\n")
- sys.exit(1)
+ raise LoginError("Security check is needed, try to visit "
+ "https://accounts.google.com/b/0/DisplayUnlockCaptcha "
+ "to unlock, or setup an app-specific password")
raise LoginError("server says: " + params["error"])
else:
raise LoginError("Auth token not found.")
|
Fix #<I>, raise excpetion rather than sys.exit()
|
NoMore201_googleplay-api
|
train
|
af077513808341f2b7e73ecd4abf2ff1ea81e180
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,6 +1,10 @@
class SessionsController < ApplicationController
def destroy
cookies.delete(request.env['COSIGN_SERVICE']) if request.env['COSIGN_SERVICE']
+
+ # make any local additions here (e.g. expiring local sessions, etc.)
+ # adapted from here: http://cosign.git.sourceforge.net/git/gitweb.cgi?p=cosign/cosign;a=blob;f=scripts/logout/logout.php;h=3779248c754001bfa4ea8e1224028be2b978f3ec;hb=HEAD
+
redirect_to ScholarSphere::Application.config.logout_url
end
end
|
Added comments fixes #<I>
|
samvera_hyrax
|
train
|
6bd65ef75308d518de794b3953c0f816e77690b5
|
diff --git a/main/core/Entity/Model/CodeTrait.php b/main/core/Entity/Model/CodeTrait.php
index <HASH>..<HASH> 100644
--- a/main/core/Entity/Model/CodeTrait.php
+++ b/main/core/Entity/Model/CodeTrait.php
@@ -30,11 +30,11 @@ trait CodeTrait
/**
* Sets code.
*
- * @param $uuid
+ * @param $code
*/
- public function setCode($uuid)
+ public function setCode($code)
{
- $this->code = code;
+ $this->code = $code;
}
//default is same than uuid
|
[CoreBundle model typo (#<I>)
* typo
cc too fast
* Update CodeTrait.php
|
claroline_Distribution
|
train
|
be8cbfc3212b747bfd4c8f9768948403521dee09
|
diff --git a/lib/super_resources/nesting.rb b/lib/super_resources/nesting.rb
index <HASH>..<HASH> 100644
--- a/lib/super_resources/nesting.rb
+++ b/lib/super_resources/nesting.rb
@@ -105,7 +105,7 @@ module SuperResources
end
def path_parameters
- request.env['action_dispatch.request.path_parameters']
+ request.env['action_dispatch.request.path_parameters'].symbolize_keys
end
end
end
|
Symbolize keys for hash supplied to #match_route
|
habanerohq_super_resources
|
train
|
ed844ede487778fc14da6c669f1fe105ab2c42fe
|
diff --git a/lib/hutch/broker.rb b/lib/hutch/broker.rb
index <HASH>..<HASH> 100644
--- a/lib/hutch/broker.rb
+++ b/lib/hutch/broker.rb
@@ -125,10 +125,18 @@ module Hutch
end
end
- # Each subscriber is run in a thread. This effectively calls Thread#join
- # on each of the subscriber threads.
- def wait_on_threads
- @channel.work_pool.join
+ # Each subscriber is run in a thread. This calls Thread#join on each of the
+ # subscriber threads.
+ def wait_on_threads(timeout)
+ # HACK: work_pool.join doesn't allow a timeout to be passed in, so we
+ # use instance_variable_get to gain access to the threadpool, and
+ # manuall call thread.join with a timeout
+ threads = work_pool_threads
+
+ # Thread#join returns nil when the timeout is hit. If any return nil,
+ # the threads didn't all join so we return false.
+ per_thread_timeout = timeout.to_f / threads.length
+ threads.all? { |thread| !thread.join(per_thread_timeout).nil? }
end
def stop
@@ -154,6 +162,11 @@ module Hutch
private
+ def work_pool_threads
+ # TODO: fix bunny so we don't need to do this
+ @channel.work_pool.instance_variable_get(:@threads)
+ end
+
def generate_id
SecureRandom.uuid
end
diff --git a/lib/hutch/cli.rb b/lib/hutch/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/hutch/cli.rb
+++ b/lib/hutch/cli.rb
@@ -77,8 +77,6 @@ module Hutch
def start_work_loop
Hutch.connect
@worker = Hutch::Worker.new(Hutch.broker, Hutch.consumers)
- # Set up signal handlers for graceful shutdown
- register_signal_handlers
@worker.run
:success
rescue ConnectionError, AuthenticationError, WorkerSetupError => ex
@@ -148,17 +146,6 @@ module Hutch
end
end.parse!
end
-
- # Register handlers for SIG{QUIT,TERM,INT} to shut down the worker
- # gracefully. Forceful shutdowns are very bad!
- def register_signal_handlers
- %w(QUIT TERM INT).map(&:to_sym).each do |sig|
- trap(sig) do
- Hutch.logger.info "caught sig#{sig.downcase}, stopping hutch..."
- @worker.stop
- end
- end
- end
end
end
diff --git a/lib/hutch/worker.rb b/lib/hutch/worker.rb
index <HASH>..<HASH> 100644
--- a/lib/hutch/worker.rb
+++ b/lib/hutch/worker.rb
@@ -18,8 +18,13 @@ module Hutch
# never returns.
def run
setup_queues
- # handle errors
- @broker.wait_on_threads
+
+ # Set up signal handlers for graceful shutdown
+ register_signal_handlers
+
+ # Take a break from Thread#join every 0.1 seconds to check if we've
+ # been sent any signals
+ handle_signals until @broker.wait_on_threads(0.1)
rescue Bunny::PreconditionFailed => ex
logger.error ex.message
raise WorkerSetupError.new('could not create queue due to a type ' +
@@ -27,6 +32,27 @@ module Hutch
'the existing queue and try again')
end
+ # Register handlers for SIG{QUIT,TERM,INT} to shut down the worker
+ # gracefully. Forceful shutdowns are very bad!
+ def register_signal_handlers
+ Thread.main[:signal_queue] = []
+ %w(QUIT TERM INT).map(&:to_sym).each do |sig|
+ # This needs to be reentrant, so we queue up signals to be handled
+ # in the run loop, rather than acting on signals here
+ trap(sig) do
+ Thread.main[:signal_queue] << sig
+ end
+ end
+ end
+
+ # Handle any pending signals
+ def handle_signals
+ if sig = Thread.main[:signal_queue].shift
+ logger.info "caught sig#{sig.downcase}, stopping hutch..."
+ @broker.stop
+ end
+ end
+
# Stop a running worker by killing all subscriber threads.
def stop
@broker.stop
diff --git a/spec/hutch/broker_spec.rb b/spec/hutch/broker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/hutch/broker_spec.rb
+++ b/spec/hutch/broker_spec.rb
@@ -120,6 +120,21 @@ describe Hutch::Broker do
end
end
+ describe '#wait_on_threads' do
+ let(:thread) { double('Thread') }
+ before { broker.stub(work_pool_threads: threads) }
+
+ context 'when all threads finish within the timeout' do
+ let(:threads) { [double(join: thread), double(join: thread)] }
+ specify { expect(broker.wait_on_threads(1)).to be_true }
+ end
+
+ context 'when timeout expires for one thread' do
+ let(:threads) { [double(join: thread), double(join: nil)] }
+ specify { expect(broker.wait_on_threads(1)).to be_false }
+ end
+ end
+
describe '#publish' do
context 'with a valid connection' do
before { broker.set_up_amqp_connection }
|
Handle signals in a queue, fixes #<I>
|
gocardless_hutch
|
train
|
7ab30f6341d034557d86af4a571993e3e191be4f
|
diff --git a/_docs/2-Configuration.md b/_docs/2-Configuration.md
index <HASH>..<HASH> 100644
--- a/_docs/2-Configuration.md
+++ b/_docs/2-Configuration.md
@@ -63,6 +63,16 @@ return [
| localized-routes | Allows to register all translatable routes. |
| translation-redirect | Allows to translate the route attributes by using the translation event. |
+## Ignored URI
+
+```php
+ 'ignored-uri' => [
+ //
+ ],
+```
+
+You can set a list of uris to ignore from localization checks.
+
## Locales
```php
diff --git a/config/localization.php b/config/localization.php
index <HASH>..<HASH> 100644
--- a/config/localization.php
+++ b/config/localization.php
@@ -31,6 +31,15 @@ return [
],
/* -----------------------------------------------------------------
+ | Ignored URI from localization
+ | -----------------------------------------------------------------
+ */
+
+ 'ignored-uri' => [
+ //
+ ],
+
+ /* -----------------------------------------------------------------
| Locales
| -----------------------------------------------------------------
*/
diff --git a/src/Middleware/Middleware.php b/src/Middleware/Middleware.php
index <HASH>..<HASH> 100644
--- a/src/Middleware/Middleware.php
+++ b/src/Middleware/Middleware.php
@@ -44,6 +44,7 @@ abstract class Middleware extends BaseMiddleware
public function __construct(Localization $localization)
{
$this->localization = $localization;
+ $this->except = config('localization.ignored-uri', []);
}
/* -----------------------------------------------------------------
|
Updating config file with a new feature: ignored-uri
|
ARCANEDEV_Localization
|
train
|
7de514c8cd4de43c1efd6fcef86cddc3e98a44dd
|
diff --git a/opentrons/instruments/pipette.py b/opentrons/instruments/pipette.py
index <HASH>..<HASH> 100644
--- a/opentrons/instruments/pipette.py
+++ b/opentrons/instruments/pipette.py
@@ -860,9 +860,10 @@ class Pipette(Instrument):
tip_plunge = 6
- for _ in range(3):
- self.robot.move_head(z=tip_plunge, mode='relative')
- self.robot.move_head(z=-tip_plunge, mode='relative')
+ self.robot.move_head(z=tip_plunge, mode='relative')
+ self.robot.move_head(z=-tip_plunge - 1, mode='relative')
+ self.robot.move_head(z=tip_plunge + 1, mode='relative')
+ self.robot.move_head(z=-tip_plunge, mode='relative')
_description = "Picking up tip from {0}".format(
(humanize_location(location) if location else '<In Place>')
|
adding extra 1mm to pick_up_tip to help make seal
|
Opentrons_opentrons
|
train
|
105ac150580af0a1a64bb5e0417fc57b2a0e49bb
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -223,7 +223,8 @@ devel_hadoop = devel_minreq + hive + hdfs + webhdfs + kerberos
devel_all = (sendgrid + devel + all_dbs + doc + samba + s3 + slack + crypto + oracle +
docker + ssh + kubernetes + celery + azure_blob_storage + redis + gcp_api +
datadog + zendesk + jdbc + ldap + kerberos + password + webhdfs + jenkins +
- druid + pinot + segment + snowflake + elasticsearch + azure_data_lake, atlas)
+ druid + pinot + segment + snowflake + elasticsearch + azure_data_lake +
+ atlas)
# Snakebite & Google Cloud Dataflow are not Python 3 compatible :'(
if PY3:
|
[AIRFLOW-<I>] Fix setup.py not to install snakebite on Python3
setup.py has a logic to avoid installing
snakebite on Python3, but it doesn't work.
This is because the variable devel_all is
now a tuple of lists. This PR fixes
that variable to be a flat list and
makes the logic work as expected.
Closes #<I> from sekikn/AIRFLOW-<I>
|
apache_airflow
|
train
|
0cb26ed19eced889bd0889a5043bc8be9d5ad73a
|
diff --git a/frontend_src/vstutils/fields/fk/deep-fk/DeepFKField.js b/frontend_src/vstutils/fields/fk/deep-fk/DeepFKField.js
index <HASH>..<HASH> 100644
--- a/frontend_src/vstutils/fields/fk/deep-fk/DeepFKField.js
+++ b/frontend_src/vstutils/fields/fk/deep-fk/DeepFKField.js
@@ -17,6 +17,7 @@ class DeepFKField extends FKField {
querysets: this.getAllQuerysets(this.constructor.app.getCurrentViewPath()),
});
return queryset
+ .clone({ prefetchEnabled: false })
.filter({ offset, limit: this.limit })
.items()
.then((instances) => {
diff --git a/frontend_src/vstutils/fields/fk/deep-fk/DeepFKFieldContentEditable.vue b/frontend_src/vstutils/fields/fk/deep-fk/DeepFKFieldContentEditable.vue
index <HASH>..<HASH> 100644
--- a/frontend_src/vstutils/fields/fk/deep-fk/DeepFKFieldContentEditable.vue
+++ b/frontend_src/vstutils/fields/fk/deep-fk/DeepFKFieldContentEditable.vue
@@ -27,7 +27,7 @@
</h5>
<LiquorTree
v-if="loaded"
- class="tree1"
+ ref="tree"
:options="treeOptions"
:filter="treeFilter"
:data="treeData"
@@ -66,9 +66,30 @@
this.field.makeRequest().then((results) => {
this.treeData = this.field.createTreeData(results);
this.loaded = true;
+
+ if (this.value) {
+ this.setValue(
+ results.find((instance) => this.field.getValueFieldValue(instance) === this.value),
+ );
+ }
+ this.$nextTick().then(() => {
+ this.selectOnLoad();
+ });
});
},
methods: {
+ selectOnLoad() {
+ if (!this.value) return;
+ this.selectedNode = this.$refs.tree
+ .findAll(this.field.getViewFieldValue(this.value))
+ .find((node) => node.id === this.field.getValueFieldValue(this.value));
+ this.selectedNode.select();
+ let node = this.selectedNode;
+ while (node.parent) {
+ node = node.parent;
+ node.expand();
+ }
+ },
selected(node) {
if (!this.onlyLastChild || !node.children.length) {
this.setValue(node.data.instance);
diff --git a/vstutils/api/fields.py b/vstutils/api/fields.py
index <HASH>..<HASH> 100644
--- a/vstutils/api/fields.py
+++ b/vstutils/api/fields.py
@@ -524,10 +524,11 @@ class FkModelField(FkField):
class DeepFkField(FkModelField):
"""
- Extends :class:`.FkModelField`, but displays as tree on frontend
- :param only_last_child: if True then only allows a value to be selected if it has no children
+ Extends :class:`.FkModelField`, but displays as tree on frontend.
+
+ :param only_last_child: if True then only allows a value to be selected if it has no children. Default is `False`
:type only_last_child: bool
- :param parent_field_name: name of parent field in model
+ :param parent_field_name: name of parent field in model. Default is `parent`
:type parent_field_name: str
"""
def __init__(self, only_last_child: bool = False, parent_field_name='parent', **kwargs):
|
FIX: DeepFkDield disabling prefetch and show value on load.
|
vstconsulting_vstutils
|
train
|
bb9e45281ad50a09aac0c4d4707fbb020010f9b5
|
diff --git a/History.md b/History.md
index <HASH>..<HASH> 100644
--- a/History.md
+++ b/History.md
@@ -35,6 +35,7 @@
- Added better iterators and changed some behaviour of previous ones to make them more ruby-like. New iterators are #map, #map!, #each, #recode and #collect.
- Added #vector_sum and #vector_mean.
- Added #to_gsl to convert to GSL::Matrix.
+ - Added #has_missing_data? and #missing_values_rows.
* Changes
- Changes Vector#nil_positions to Vector#missing_positions so that future changes for accomodating different values for missing data can be made easily.
- Changed History.txt to History.md
diff --git a/lib/daru/dataframe.rb b/lib/daru/dataframe.rb
index <HASH>..<HASH> 100644
--- a/lib/daru/dataframe.rb
+++ b/lib/daru/dataframe.rb
@@ -633,6 +633,26 @@ module Daru
df
end
+ # Return a vector with the number of missing values in each row.
+ #
+ # == Arguments
+ #
+ # * +missing_values+ - An Array of the values that should be
+ # treated as 'missing'. The default missing value is *nil*.
+ def missing_values_rows missing_values=[nil]
+ number_of_missing = []
+ each_row do |row|
+ row.missing_values = missing_values
+ number_of_missing << row.missing_positions.size
+ end
+
+ Daru::Vector.new number_of_missing, index: @index, name: "#{@name}_missing_rows".to_sym
+ end
+
+ def has_missing_data?
+ !!@data.any? { |v| v.has_missing_data? }
+ end
+
# Return a nested hash using vector names as keys and an array constructed of
# hashes with other values. If block provided, is used to provide the
# values, with parameters +row+ of dataset, +current+ last hash on
diff --git a/spec/dataframe_spec.rb b/spec/dataframe_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/dataframe_spec.rb
+++ b/spec/dataframe_spec.rb
@@ -1633,11 +1633,11 @@ describe Daru::DataFrame do
context "has_missing_data?" do
before do
- @a1 = Daru::Vector.new [1, nil, 3, 4, 5, nil]
- @a2 = Daru::Vector.new [10, nil, 20, 20, 20, 30]
- @b1 = Daru::Vector.new [nil, nil, 1, 1, 1, 2]
- @b2 = Daru::Vector.new [2, 2, 2, nil, 2, 3]
- @c = Daru::Vector.new [nil, 2, 4, 2, 2, 2]
+ a1 = Daru::Vector.new [1, nil, 3, 4, 5, nil]
+ a2 = Daru::Vector.new [10, nil, 20, 20, 20, 30]
+ b1 = Daru::Vector.new [nil, nil, 1, 1, 1, 2]
+ b2 = Daru::Vector.new [2, 2, 2, nil, 2, 3]
+ c = Daru::Vector.new [nil, 2, 4, 2, 2, 2]
@df = Daru::DataFrame.new({ :a1 => a1, :a2 => a2, :b1 => b1, :b2 => b2, :c => c })
end
|
added has_missing_data? and #missing_values_rows to DataFrame
|
SciRuby_daru
|
train
|
ca2dd242c443f5fca64c27005fbfe45ac06488f2
|
diff --git a/elasticsearch/helpers/__init__.py b/elasticsearch/helpers/__init__.py
index <HASH>..<HASH> 100644
--- a/elasticsearch/helpers/__init__.py
+++ b/elasticsearch/helpers/__init__.py
@@ -237,7 +237,7 @@ def parallel_bulk(client, actions, thread_count=4, chunk_size=500,
pool.join()
def scan(client, query=None, scroll='5m', raise_on_error=True,
- preserve_order=False, size=1000, request_timeout=None, **kwargs):
+ preserve_order=False, size=1000, request_timeout=None, clear_scroll=True, **kwargs):
"""
Simple abstraction on top of the
:meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that
@@ -261,6 +261,9 @@ def scan(client, query=None, scroll='5m', raise_on_error=True,
unpredictable results, use with caution.
:arg size: size (per shard) of the batch send at each iteration.
:arg request_timeout: explicit timeout for each call to ``scan``
+ :arg clear_scroll: explicitly calls delete on the scroll id via the clear
+ scroll API at the end of the method on completion or error, defaults
+ to true.
Any additional keyword arguments will be passed to the initial
:meth:`~elasticsearch.Elasticsearch.search` call::
@@ -313,7 +316,7 @@ def scan(client, query=None, scroll='5m', raise_on_error=True,
if scroll_id is None or not resp['hits']['hits']:
break
finally:
- if scroll_id:
+ if scroll_id and clear_scroll:
client.clear_scroll(body={'scroll_id': [scroll_id]}, ignore=(404, ))
def reindex(client, source_index, target_index, query=None, target_client=None,
|
optionally don't explicitly delete scrolls in helper (#<I>)
|
elastic_elasticsearch-py
|
train
|
ff116a28a143f6dc2b7f55d1c8217f823747587c
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -249,6 +249,8 @@ export const sessionStoreBuilder = () => ({
}
this.cookies = this.cookies || cookies
+ this.httpLib = this.httpLib || this.$axios
+
setTimeout(() => {
// always start by a keepalive to fetch latest session info on page load
dispatch('keepalive')
|
fix: missing httpLib in some cases
|
koumoul-dev_sd-vue
|
train
|
09c329a485c8cf43a40b2c51f1df64cbef736cbc
|
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
index <HASH>..<HASH> 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
@@ -299,8 +299,6 @@ public class JpaControllerManagement implements ControllerManagement {
case CANCELED:
case WARNING:
case RUNNING:
- handleIntermediateFeedback(mergedAction, mergedTarget);
- break;
default:
break;
}
@@ -312,16 +310,6 @@ public class JpaControllerManagement implements ControllerManagement {
return actionRepository.save(mergedAction);
}
- private void handleIntermediateFeedback(final JpaAction mergedAction, final JpaTarget mergedTarget) {
- // we change the target state only if the action is still running
- // otherwise this is considered as late feedback that does not have
- // an impact on the state anymore.
- if (mergedAction.isActive()) {
- DeploymentHelper.updateTargetInfo(mergedTarget, TargetUpdateStatus.PENDING, false, targetInfoRepository,
- entityManager);
- }
- }
-
private void handleErrorOnAction(final JpaAction mergedAction, final JpaTarget mergedTarget) {
mergedAction.setActive(false);
mergedAction.setStatus(Status.ERROR);
@@ -349,15 +337,17 @@ public class JpaControllerManagement implements ControllerManagement {
action.setStatus(Status.FINISHED);
final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo();
final JpaDistributionSet ds = (JpaDistributionSet) entityManager.merge(action.getDistributionSet());
+
targetInfo.setInstalledDistributionSet(ds);
- if (target.getAssignedDistributionSet() != null && targetInfo.getInstalledDistributionSet() != null && target
- .getAssignedDistributionSet().getId().equals(targetInfo.getInstalledDistributionSet().getId())) {
+ targetInfo.setInstallationDate(System.currentTimeMillis());
+
+ // check if the assigned set is equal no to the installed set (not
+ // necessarily the case as another update might be pending already).
+ if (target.getAssignedDistributionSet() != null && target.getAssignedDistributionSet().getId()
+ .equals(targetInfo.getInstalledDistributionSet().getId())) {
targetInfo.setUpdateStatus(TargetUpdateStatus.IN_SYNC);
- targetInfo.setInstallationDate(System.currentTimeMillis());
- } else {
- targetInfo.setUpdateStatus(TargetUpdateStatus.PENDING);
- targetInfo.setInstallationDate(System.currentTimeMillis());
}
+
targetInfoRepository.save(targetInfo);
entityManager.detach(ds);
}
|
Removed unnecessary target info startus persistence.
|
eclipse_hawkbit
|
train
|
e0c519e850ca957c45fd0cec2edcd679070ed1d5
|
diff --git a/lib/adhearsion/initializer.rb b/lib/adhearsion/initializer.rb
index <HASH>..<HASH> 100644
--- a/lib/adhearsion/initializer.rb
+++ b/lib/adhearsion/initializer.rb
@@ -223,7 +223,6 @@ module Adhearsion
def daemonize!
logger.info "Daemonizing now!"
- logger.debug "Creating PID file #{pid_file}"
Adhearsion::CustomDaemonizer.daemonize resolve_log_file_path do |pid|
create_pid_file pid
end
@@ -270,6 +269,8 @@ module Adhearsion
def create_pid_file(pid = nil)
return unless pid_file
+ logger.debug "Creating PID file #{pid_file}"
+
File.open pid_file, 'w' do |file|
file.puts pid || ::Process.pid
end
|
[CS] Log pidfile creation whenever it happens
|
adhearsion_adhearsion
|
train
|
6f6906fe917fd45ea88a70efbea60ecbdd08608a
|
diff --git a/webvtt/__init__.py b/webvtt/__init__.py
index <HASH>..<HASH> 100644
--- a/webvtt/__init__.py
+++ b/webvtt/__init__.py
@@ -1 +1,3 @@
-from .parser import WebVTTParser
\ No newline at end of file
+from .parser import WebVTTParser
+from .segmenter import WebVTTSegmenter
+from .generic import Caption
\ No newline at end of file
|
Add imports of the different classes to the module init
|
glut23_webvtt-py
|
train
|
1272d6767b17e06c32319750dbbc4e852d483926
|
diff --git a/scripts/babel-relay-plugin/src/getBabelRelayPlugin.js b/scripts/babel-relay-plugin/src/getBabelRelayPlugin.js
index <HASH>..<HASH> 100644
--- a/scripts/babel-relay-plugin/src/getBabelRelayPlugin.js
+++ b/scripts/babel-relay-plugin/src/getBabelRelayPlugin.js
@@ -55,6 +55,10 @@ function getBabelRelayPlugin(
var Plugin = babel.Plugin;
var t = babel.types;
+ var warning = options && options.suppressWarnings ?
+ function() {} :
+ console.warn.bind(console);
+
return new Plugin('relay-query', {
visitor: {
/**
@@ -132,11 +136,11 @@ function getBabelRelayPlugin(
validationErrors.forEach(function(validationError) {
errorMessages = errorMessages || [];
errorMessages.push(validationError.message);
- console.warn(
+ warning(
'\n-- GraphQL Validation Error -- %s --\n',
path.basename(filename)
);
- console.warn(
+ warning(
'Error: ' + validationError.message + '\n' +
'File: ' + filename + '\n' +
'Source:'
@@ -146,19 +150,19 @@ function getBabelRelayPlugin(
var prefix = '> ';
var highlight = repeat(' ', location.column - 1) + '^^^';
if (preview) {
- console.warn(prefix);
- console.warn(prefix + preview);
- console.warn(prefix + highlight);
+ warning(prefix);
+ warning(prefix + preview);
+ warning(prefix + highlight);
}
});
});
} else {
errorMessages = [error.message];
- console.warn(
+ warning(
'\n-- Relay Transform Error -- %s --\n',
path.basename(filename)
);
- console.warn(
+ warning(
'Error: ' + error.message + '\n' +
'File: ' + filename + '\n'
);
diff --git a/scripts/babel-relay-plugin/src/transformGraphQL.js b/scripts/babel-relay-plugin/src/transformGraphQL.js
index <HASH>..<HASH> 100644
--- a/scripts/babel-relay-plugin/src/transformGraphQL.js
+++ b/scripts/babel-relay-plugin/src/transformGraphQL.js
@@ -36,7 +36,10 @@ function getSchema(schemaPath) {
}
function transformGraphQL(schemaPath, source, filename) {
- var plugin = getBabelRelayPlugin(getSchema(schemaPath));
+ var plugin = getBabelRelayPlugin(getSchema(schemaPath), {
+ abortOnError: false,
+ suppressWarnings: true,
+ });
return babel.transform(source, {
compact: false,
filename: filename,
|
Relay: Suppress Warnings in Tests / Fixture Generator
|
facebook_relay
|
train
|
0cad84ec0042b27c6d181bef103fe9d87bda5e6c
|
diff --git a/aws/data_source_aws_apigatewayv2_api_test.go b/aws/data_source_aws_apigatewayv2_api_test.go
index <HASH>..<HASH> 100644
--- a/aws/data_source_aws_apigatewayv2_api_test.go
+++ b/aws/data_source_aws_apigatewayv2_api_test.go
@@ -4,6 +4,7 @@ import (
"fmt"
"testing"
+ "github.com/aws/aws-sdk-go/service/apigatewayv2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)
@@ -15,6 +16,7 @@ func TestAccAWSAPIGatewayV2ApiDataSource_Http(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
+ ErrorCheck: testAccErrorCheck(t, apigatewayv2.EndpointsID),
Providers: testAccProviders,
CheckDestroy: nil,
Steps: []resource.TestStep{
@@ -54,6 +56,7 @@ func TestAccAWSAPIGatewayV2ApiDataSource_WebSocket(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
+ ErrorCheck: testAccErrorCheck(t, apigatewayv2.EndpointsID),
Providers: testAccProviders,
CheckDestroy: nil,
Steps: []resource.TestStep{
|
tests/ds/apigatewayv2_api: Add ErrorCheck
|
terraform-providers_terraform-provider-aws
|
train
|
0d3ee9f8eb0239085d7d84def88ba7701b4880bf
|
diff --git a/_scripts/check-release.js b/_scripts/check-release.js
index <HASH>..<HASH> 100755
--- a/_scripts/check-release.js
+++ b/_scripts/check-release.js
@@ -103,16 +103,20 @@ conventionalChangelog({
}
var package = commit.scope;
+ var toPush = null;
if (commit.type === 'fix') {
status[package].increment = Math.max(status[package].increment, 1);
- status[package].commits.push(commit);
+ toPush = commit;
}
if (commit.type === 'feat') {
status[package].increment = Math.max(status[package].increment, 2);
- status[package].commits.push(commit);
+ toPush = commit;
}
if (isCommitBreakingChange(commit)) {
status[package].increment = Math.max(status[package].increment, 3);
+ toPush = commit;
+ }
+ if (toPush) {
status[package].commits.push(commit);
}
if (commit.type === 'release') {
|
chore(META): fix check-release redundant info
Should not show same commit twice.
|
cyclejs_cyclejs
|
train
|
cd82ee238bef1d3d6ef9c6ac7efa48be779035e7
|
diff --git a/test/tree-tests/down-key-module.js b/test/tree-tests/down-key-module.js
index <HASH>..<HASH> 100644
--- a/test/tree-tests/down-key-module.js
+++ b/test/tree-tests/down-key-module.js
@@ -37,7 +37,7 @@ define(function keyboardNavigationModuleFactory (require) {
});
- QUnit.skip('when focus is on open empty branch, moves focus down to next sibling', function respondsToKeyboardInput (assert) {
+ QUnit.test('when focus is on open empty branch, moves focus down to next sibling', function respondsToKeyboardInput (assert) {
assert.expect(2);
this.$tree.on('initialized.fu.tree', function triggerDiscloseFolder () {
diff --git a/test/tree-tests/up-key-module.js b/test/tree-tests/up-key-module.js
index <HASH>..<HASH> 100644
--- a/test/tree-tests/up-key-module.js
+++ b/test/tree-tests/up-key-module.js
@@ -1,10 +1,32 @@
define(function keyboardNavigationModuleFactory (require) {
var $ = require('jquery');
+ var emptyFolderData = require('./data/emptyFolder');
return function upKeyModule (QUnit) {
QUnit.module( 'should respond to up key', {}, function testUpKeyPresses () {
- QUnit.skip('when focus is on node below sibling node, moves focus up to sibling', function loadTree (assert) {
+ QUnit.test('when focus is on node below sibling node, moves focus up to sibling', function loadTree (assert) {
+ assert.expect(2);
+ this.$tree.on('initialized.fu.tree', function triggerDownArrow () {
+ var $initialBranch = $(this.$tree.find('li:not(".hidden")').get(1));
+ var $previousBranch = $(this.$tree.find('li:not(".hidden")').get(0));
+
+ $initialBranch.attr('tabindex', 0);
+ $initialBranch.focus();
+
+ this.$tree.on('keyboardNavigated.fu.tree', function testDownArrowResult () {
+ assert.equal($(document.activeElement).attr('id'), $previousBranch.attr('id'), 'previous sibling now has focus');
+ });
+
+ assert.equal($(document.activeElement).attr('id'), $initialBranch.attr('id'), 'initial branch has focus');
+
+ var pressUpArrow = this.getKeyDown('up', $initialBranch);
+ $initialBranch.trigger(pressUpArrow);
+ }.bind(this));
+
+ this.$tree.tree({
+ dataSource: this.dataSource
+ });
});
QUnit.skip('when focus is below open sibling, moves focus into last focusable child of sibling', function loadTree (assert) {
@@ -14,6 +36,37 @@ define(function keyboardNavigationModuleFactory (require) {
QUnit.skip('when focus is in first child of open branch, moves focus onto parent', function respondsToKeyboardInput (assert) {
});
+
+ QUnit.test('when focus is on node below open empty branch, moves focus onto empty branch', function loadTree (assert) {
+ assert.expect(4);
+ assert.notOk(emptyFolderData[0].children.length, 'empty branch has no children');
+
+ this.$tree.on('initialized.fu.tree', function triggerDiscloseFolder () {
+ var $initialBranch = $(this.$tree.find('li:not(".hidden")').get(1));
+ var $emptyBranch = $(this.$tree.find('li:not(".hidden")').get(0));
+
+ this.$tree.on('disclosedFolder.fu.tree', function triggerDownArrow () {
+ assert.ok($emptyBranch.hasClass('tree-open'), 'empty branch is open');
+ $initialBranch.attr('tabindex', 0);
+ $initialBranch.focus();
+
+ this.$tree.on('keyboardNavigated.fu.tree', function testDownArrowResult () {
+ assert.equal($(document.activeElement).attr('id'), $emptyBranch.attr('id'), 'after up pressed, empty branch now has focus');
+ });
+
+ assert.equal($(document.activeElement).attr('id'), $initialBranch.attr('id'), 'branch below empty open branch has focus');
+
+ var pressDownArrow = this.getKeyDown('up', $initialBranch);
+ $initialBranch.trigger(pressDownArrow);
+ }.bind(this));
+
+ this.$tree.tree('discloseFolder', $emptyBranch);
+ }.bind(this));
+
+ this.$tree.tree({
+ staticData: emptyFolderData
+ });
+ });
});
};
});
|
(GH<I>) adds unit tests for empty branch keyboard nav on tree
|
ExactTarget_fuelux
|
train
|
8e688bb12835950949c46224f3d3f6049672617d
|
diff --git a/pkg/models/derivatives/derivatives_test.go b/pkg/models/derivatives/derivatives_test.go
index <HASH>..<HASH> 100644
--- a/pkg/models/derivatives/derivatives_test.go
+++ b/pkg/models/derivatives/derivatives_test.go
@@ -12,7 +12,7 @@ func TestNewDerivativeStatusFromWsRaw(t *testing.T) {
t.Run("insufficient arguments", func(t *testing.T) {
payload := []interface{}{float64(1591614631576)}
- d, err := derivatives.NewDerivativeStatusFromWsRaw("tBTCF0:USTF0", payload)
+ d, err := derivatives.FromWsRaw("tBTCF0:USTF0", payload)
require.NotNil(t, err)
require.Nil(t, d)
})
@@ -39,7 +39,7 @@ func TestNewDerivativeStatusFromWsRaw(t *testing.T) {
3813.72957182,
}
- d, err := derivatives.NewDerivativeStatusFromWsRaw("tBTCF0:USTF0", payload)
+ d, err := derivatives.FromWsRaw("tBTCF0:USTF0", payload)
require.Nil(t, err)
expected := &derivatives.DerivativeStatus{
@@ -49,6 +49,7 @@ func TestNewDerivativeStatusFromWsRaw(t *testing.T) {
SpotPrice: 9275.3,
InsuranceFundBalance: 1.39147227686063e+06,
FundingAccrued: -0.00011968,
+ FundingStep: 3144,
MarkPrice: 9276.06,
OpenInterest: 3813.72957182,
}
@@ -60,7 +61,7 @@ func TestNewDerivativeStatusFromRaw(t *testing.T) {
t.Run("insufficient arguments", func(t *testing.T) {
payload := []interface{}{"tBTCF0:USTF0"}
- d, err := derivatives.NewDerivativeStatusFromRaw(payload)
+ d, err := derivatives.FromRaw(payload)
require.NotNil(t, err)
require.Nil(t, d)
})
@@ -88,7 +89,7 @@ func TestNewDerivativeStatusFromRaw(t *testing.T) {
3813.72957182,
}
- d, err := derivatives.NewDerivativeStatusFromRaw(payload)
+ d, err := derivatives.FromRaw(payload)
require.Nil(t, err)
expected := &derivatives.DerivativeStatus{
@@ -98,9 +99,97 @@ func TestNewDerivativeStatusFromRaw(t *testing.T) {
SpotPrice: 9275.3,
InsuranceFundBalance: 1.39147227686063e+06,
FundingAccrued: -0.00011968,
+ FundingStep: 3144,
MarkPrice: 9276.06,
OpenInterest: 3813.72957182,
}
assert.Equal(t, expected, d)
})
}
+
+func TestSnapshotFromRaw(t *testing.T) {
+ t.Run("invalid arguments", func(t *testing.T) {
+ payload := [][]interface{}{{"tBTCF0:USTF0"}}
+ ss, err := derivatives.SnapshotFromRaw(payload)
+ require.NotNil(t, err)
+ require.Nil(t, ss)
+ })
+
+ t.Run("valid arguments", func(t *testing.T) {
+ payload := [][]interface{}{
+ {
+ "tBTCF0:USTF0",
+ float64(1591614631576),
+ nil,
+ 9271.1234567,
+ 9275.3,
+ nil,
+ 1391472.27686063,
+ nil,
+ 1594656000000,
+ -0.00011968,
+ 3144,
+ nil,
+ 0,
+ nil,
+ nil,
+ 9276.06,
+ nil,
+ nil,
+ 3813.72957182,
+ },
+ {
+ "tBTCF0:USTF0",
+ float64(1591614631576),
+ nil,
+ 9271.1234567,
+ 9275.3,
+ nil,
+ 1391472.27686063,
+ nil,
+ 1594656000000,
+ -0.00011968,
+ 3200,
+ nil,
+ 0,
+ nil,
+ nil,
+ 9276.06,
+ nil,
+ nil,
+ 3813.72957182,
+ },
+ }
+ ss, err := derivatives.SnapshotFromRaw(payload)
+ require.Nil(t, err)
+
+ expected := &derivatives.DerivativeStatusSnapshot{
+ Snapshot: []*derivatives.DerivativeStatus{
+ {
+ Symbol: "tBTCF0:USTF0",
+ MTS: 1591614631576,
+ Price: 9271.1234567,
+ SpotPrice: 9275.3,
+ InsuranceFundBalance: 1.39147227686063e+06,
+ FundingAccrued: -0.00011968,
+ FundingStep: 3144,
+ MarkPrice: 9276.06,
+ OpenInterest: 3813.72957182,
+ },
+ {
+ Symbol: "tBTCF0:USTF0",
+ MTS: 1591614631576,
+ Price: 9271.1234567,
+ SpotPrice: 9275.3,
+ InsuranceFundBalance: 1.39147227686063e+06,
+ FundingAccrued: -0.00011968,
+ FundingStep: 3200,
+ MarkPrice: 9276.06,
+ OpenInterest: 3813.72957182,
+ },
+ },
+ }
+
+ assert.Equal(t, expected, ss)
+ })
+}
|
adding more tests to cover snapshot functionaity for derivatives status
|
bitfinexcom_bitfinex-api-go
|
train
|
83284318927837d7dd0ffa3f099530311c083577
|
diff --git a/xdot.py b/xdot.py
index <HASH>..<HASH> 100755
--- a/xdot.py
+++ b/xdot.py
@@ -504,6 +504,14 @@ class Graph(Shape):
return None
+BOLD = 1
+ITALIC = 2
+UNDERLINE = 4
+SUPERSCRIPT = 8
+SUBSCRIPT = 16
+STRIKE_THROUGH = 32
+
+
class XDotAttrParser:
"""Parser for xdot drawing attributes.
See also:
@@ -609,7 +617,7 @@ class XDotAttrParser:
a = 1.0
return r, g, b, a
- sys.stderr.write("unknown color '%s'\n" % c)
+ sys.stderr.write("warning: unknown color '%s'\n" % c)
return None
def parse(self):
@@ -644,6 +652,9 @@ class XDotAttrParser:
w = s.read_float()
t = s.read_text()
self.handle_text(x, y, j, w, t)
+ elif op == "t":
+ f = s.read_int()
+ self.handle_font_characteristics(f)
elif op == "E":
x0, y0 = s.read_point()
w = s.read_float()
@@ -676,8 +687,8 @@ class XDotAttrParser:
path = s.read_text()
self.handle_image(x0, y0, w, h, path)
else:
- sys.stderr.write("unknown xdot opcode '%s'\n" % op)
- break
+ sys.stderr.write("error: unknown xdot opcode '%s'\n" % op)
+ sys.exit(1)
return self.shapes
@@ -705,6 +716,11 @@ class XDotAttrParser:
self.pen.fontsize = size
self.pen.fontname = name
+ def handle_font_characteristics(self, flags):
+ # TODO
+ if flags != 0:
+ sys.stderr.write("warning: font characteristics not supported yet\n" % op)
+
def handle_text(self, x, y, j, w, t):
self.shapes.append(TextShape(self.pen, x, y, j, w, t))
|
Parse new 't' opcode for font characteristics (from xdot version <I>)
|
jrfonseca_xdot.py
|
train
|
922c7b57f569055b98d48d59677e2019e55e3e16
|
diff --git a/cmd/data-scanner.go b/cmd/data-scanner.go
index <HASH>..<HASH> 100644
--- a/cmd/data-scanner.go
+++ b/cmd/data-scanner.go
@@ -44,7 +44,7 @@ import (
const (
dataScannerSleepPerFolder = time.Millisecond // Time to wait between folders.
- dataScannerStartDelay = 1 * time.Minute // Time to wait on startup and between cycles.
+ dataScannerStartDelay = 5 * time.Minute // Time to wait on startup and between cycles.
dataUsageUpdateDirCycles = 16 // Visit all folders every n cycles.
healDeleteDangling = true
diff --git a/cmd/storage-rest-client.go b/cmd/storage-rest-client.go
index <HASH>..<HASH> 100644
--- a/cmd/storage-rest-client.go
+++ b/cmd/storage-rest-client.go
@@ -337,8 +337,10 @@ func (client *storageRESTClient) CreateFile(ctx context.Context, volume, path st
values.Set(storageRESTFilePath, path)
values.Set(storageRESTLength, strconv.Itoa(int(size)))
respBody, err := client.call(ctx, storageRESTMethodCreateFile, values, ioutil.NopCloser(reader), size)
- defer http.DrainBody(respBody)
- return err
+ if err != nil {
+ return err
+ }
+ return waitForHTTPStream(respBody, ioutil.Discard)
}
func (client *storageRESTClient) WriteMetadata(ctx context.Context, volume, path string, fi FileInfo) error {
diff --git a/cmd/storage-rest-server.go b/cmd/storage-rest-server.go
index <HASH>..<HASH> 100644
--- a/cmd/storage-rest-server.go
+++ b/cmd/storage-rest-server.go
@@ -287,10 +287,10 @@ func (s *storageRESTServer) CreateFileHandler(w http.ResponseWriter, r *http.Req
s.writeErrorResponse(w, err)
return
}
- err = s.storage.CreateFile(r.Context(), volume, filePath, int64(fileSize), r.Body)
- if err != nil {
- s.writeErrorResponse(w, err)
- }
+
+ done := keepHTTPResponseAlive(w)
+ done(s.storage.CreateFile(r.Context(), volume, filePath, int64(fileSize), r.Body))
+ w.(http.Flusher).Flush()
}
// DeleteVersion delete updated metadata.
|
xl: CreateFile shouldn't prematurely timeout (#<I>)
For large objects taking more than '3 minutes' response
times in a single PUT operation can timeout prematurely
as 'ResponseHeader' timeout hits for 3 minutes. Avoid
this by keeping the connection active during CreateFile
phase.
|
minio_minio
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.