hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
435303c647f69cd4099aca0d6e2cd18194a13eb6
|
diff --git a/pkg/cloudprovider/providers/gce/gce.go b/pkg/cloudprovider/providers/gce/gce.go
index <HASH>..<HASH> 100644
--- a/pkg/cloudprovider/providers/gce/gce.go
+++ b/pkg/cloudprovider/providers/gce/gce.go
@@ -84,6 +84,7 @@ type GCECloud struct {
localZone string // The zone in which we are running
managedZones []string // List of zones we are spanning (for multi-AZ clusters, primarily when running on master)
networkURL string
+ subnetworkURL string
nodeTags []string // List of tags to use on firewall rules for load balancers
nodeInstancePrefix string // If non-"", an advisory prefix for all nodes in the cluster
useMetadataServer bool
@@ -96,6 +97,7 @@ type Config struct {
TokenBody string `gcfg:"token-body"`
ProjectID string `gcfg:"project-id"`
NetworkName string `gcfg:"network-name"`
+ SubnetworkName string `gcfg:"subnetwork-name"`
NodeTags []string `gcfg:"node-tags"`
NodeInstancePrefix string `gcfg:"node-instance-prefix"`
Multizone bool `gcfg:"multizone"`
@@ -132,6 +134,7 @@ func newGCECloud(config io.Reader) (*GCECloud, error) {
return nil, err
}
networkURL := gceNetworkURL(projectID, networkName)
+ subnetworkURL := ""
// By default, Kubernetes clusters only run against one zone
managedZones := []string{zone}
@@ -156,6 +159,13 @@ func newGCECloud(config io.Reader) (*GCECloud, error) {
networkURL = gceNetworkURL(cfg.Global.ProjectID, cfg.Global.NetworkName)
}
}
+ if cfg.Global.SubnetworkName != "" {
+ if strings.Contains(cfg.Global.SubnetworkName, "/") {
+ subnetworkURL = cfg.Global.SubnetworkName
+ } else {
+ subnetworkURL = gceSubnetworkURL(cfg.Global.ProjectID, region, cfg.Global.SubnetworkName)
+ }
+ }
if cfg.Global.TokenURL != "" {
tokenSource = NewAltTokenSource(cfg.Global.TokenURL, cfg.Global.TokenBody)
}
@@ -166,15 +176,15 @@ func newGCECloud(config io.Reader) (*GCECloud, error) {
}
}
- return CreateGCECloud(projectID, region, zone, managedZones, networkURL, nodeTags,
- nodeInstancePrefix, tokenSource, true /* useMetadataServer */)
+ return CreateGCECloud(projectID, region, zone, managedZones, networkURL, subnetworkURL,
+ nodeTags, nodeInstancePrefix, tokenSource, true /* useMetadataServer */)
}
// Creates a GCECloud object using the specified parameters.
// If no networkUrl is specified, loads networkName via rest call.
// If no tokenSource is specified, uses oauth2.DefaultTokenSource.
// If managedZones is nil / empty all zones in the region will be managed.
-func CreateGCECloud(projectID, region, zone string, managedZones []string, networkURL string, nodeTags []string,
+func CreateGCECloud(projectID, region, zone string, managedZones []string, networkURL, subnetworkURL string, nodeTags []string,
nodeInstancePrefix string, tokenSource oauth2.TokenSource, useMetadataServer bool) (*GCECloud, error) {
client, err := newOauthClient(tokenSource)
@@ -227,6 +237,7 @@ func CreateGCECloud(projectID, region, zone string, managedZones []string, netwo
localZone: zone,
managedZones: managedZones,
networkURL: networkURL,
+ subnetworkURL: subnetworkURL,
nodeTags: nodeTags,
nodeInstancePrefix: nodeInstancePrefix,
useMetadataServer: useMetadataServer,
@@ -287,6 +298,10 @@ func gceNetworkURL(project, network string) string {
return fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s", project, network)
}
+func gceSubnetworkURL(project, region, subnetwork string) string {
+ return fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/subnetworks/%s", project, region, subnetwork)
+}
+
func getNetworkNameViaMetadata() (string, error) {
result, err := metadata.Get("instance/network-interfaces/0/network")
if err != nil {
|
Add subnetworkURL to GCE provider
|
kubernetes_kubernetes
|
train
|
1f8abeea89f28fada001866c43fbbf95b50c4023
|
diff --git a/classes/phing/system/io/FileSystem.php b/classes/phing/system/io/FileSystem.php
index <HASH>..<HASH> 100644
--- a/classes/phing/system/io/FileSystem.php
+++ b/classes/phing/system/io/FileSystem.php
@@ -410,7 +410,7 @@ abstract class FileSystem {
function chmod($pathname, $mode) {
$str_mode = decoct($mode); // Show octal in messages.
if (false === @chmod($pathname, $mode)) {// FAILED.
- $msg = "FileSystem::chmod() FAILED. Cannot chmod $pathname. Mode $str_mode. $php_errormsg";
+ $msg = "FileSystem::chmod() FAILED. Cannot chmod $pathname. Mode $str_mode." . (isset($php_errormsg) ? ' ' . $php_errormsg : "");
throw new Exception($msg);
}
}
|
Fixing undefined var notices from Filesystem::chmod()
|
phingofficial_phing
|
train
|
c2bc1778127dba440682ccbe5215d538929bcf70
|
diff --git a/flowlogs_reader/flowlogs_reader.py b/flowlogs_reader/flowlogs_reader.py
index <HASH>..<HASH> 100644
--- a/flowlogs_reader/flowlogs_reader.py
+++ b/flowlogs_reader/flowlogs_reader.py
@@ -269,7 +269,7 @@ class FlowLogsReader(BaseReader):
fields = self._get_fields(
self.region_name, self.log_group_name, ec2_client=ec2_client
)
- self.fields = fields
+ self.fields = tuple(f.replace('-', '_') for f in fields)
self.start_ms = timegm(self.start_time.utctimetuple()) * 1000
self.end_ms = timegm(self.end_time.utctimetuple()) * 1000
diff --git a/tests/test_flowlogs_reader.py b/tests/test_flowlogs_reader.py
index <HASH>..<HASH> 100644
--- a/tests/test_flowlogs_reader.py
+++ b/tests/test_flowlogs_reader.py
@@ -251,7 +251,7 @@ class FlowLogsReaderTestCase(TestCase):
ec2_client = mock_client.return_value
ec2_client.describe_flow_logs.return_value = {
'FlowLogs': [
- {'LogFormat': '${srcaddr} ${dstaddr} ${start} ${end}'}
+ {'LogFormat': '${srcaddr} ${dstaddr} ${start} ${log-status}'}
]
}
reader = FlowLogsReader(
@@ -259,7 +259,9 @@ class FlowLogsReaderTestCase(TestCase):
boto_client=cwl_client,
fields=None,
)
- self.assertEqual(reader.fields, ('srcaddr', 'dstaddr', 'start', 'end'))
+ self.assertEqual(
+ reader.fields, ('srcaddr', 'dstaddr', 'start', 'log_status')
+ )
ec2_client.describe_flow_logs.assert_called_once_with(
Filters=[{'Name': 'log-group-name', 'Values': ['some_group']}]
)
|
Ensure fields with dashes get printed
|
obsrvbl_flowlogs-reader
|
train
|
4325ec81a327f1b35b0780468ef4b4bd0e0ebc00
|
diff --git a/src/views/dashboard/index.php b/src/views/dashboard/index.php
index <HASH>..<HASH> 100644
--- a/src/views/dashboard/index.php
+++ b/src/views/dashboard/index.php
@@ -167,7 +167,7 @@ $user = Yii::$app->user;
</div>
<?php endif ?>
- <?php if (Yii::getAlias('@part', false) && $user->can('stock.read')) : ?>
+ <?php if (Yii::getAlias('@part', false) && $user->can('part.read')) : ?>
<div class="col-lg-3 col-md-6 col-sm-12 col-xs-12">
<?php $box = SmallBox::begin([
'boxTitle' => Yii::t('hipanel:stock', 'Parts'),
@@ -194,7 +194,7 @@ $user = Yii::$app->user;
</div>
<?php endif ?>
- <?php if (Yii::getAlias('@model', false) && $user->can('stock.read')) : ?>
+ <?php if (Yii::getAlias('@model', false) && $user->can('model.read')) : ?>
<div class="col-lg-3 col-md-6 col-sm-12 col-xs-12">
<?php $box = SmallBox::begin([
'boxTitle' => Yii::t('hipanel:stock', 'Models'),
|
fixed rbac checks for stock in dashboard
|
hiqdev_hipanel-module-dashboard
|
train
|
0a2891d398ec9dd2096d69f81f086e848cd3e2f3
|
diff --git a/spec/lib/guard/setuper_spec.rb b/spec/lib/guard/setuper_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/guard/setuper_spec.rb
+++ b/spec/lib/guard/setuper_spec.rb
@@ -14,6 +14,7 @@ describe Guard::Setuper do
allow(Guard::Jobs::Sleep).to receive(:new).and_return(sleep_interactor)
end
+ # TODO: setup has too many responsibilities
describe ".setup" do
subject { Guard.setup(options) }
@@ -587,6 +588,7 @@ describe Guard::Setuper do
end
end
+ # shouldn't be in specs - whatever it uses should be mocked out
describe "._debug_command_execution" do
subject { Guard.setup }
|
add dev comments (setuper)
|
guard_guard
|
train
|
8784de74624018dd744ff485b1ffd6f0f28ec29c
|
diff --git a/pythonforandroid/bootstraps/sdl2/__init__.py b/pythonforandroid/bootstraps/sdl2/__init__.py
index <HASH>..<HASH> 100644
--- a/pythonforandroid/bootstraps/sdl2/__init__.py
+++ b/pythonforandroid/bootstraps/sdl2/__init__.py
@@ -7,7 +7,7 @@ import sh
class SDL2Bootstrap(Bootstrap):
name = 'sdl2'
- recipe_depends = ['sdl2']
+ recipe_depends = ['sdl2', ('python2', 'python3crystax')]
def run_distribute(self):
info_main('# Creating Android project from build and {} bootstrap'.format(
|
Added python to sdl2 bootstrap depends
|
kivy_python-for-android
|
train
|
f055617058a5a920b6079470738a02479b7b42e7
|
diff --git a/openpnm/algorithms/__init__.py b/openpnm/algorithms/__init__.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/__init__.py
+++ b/openpnm/algorithms/__init__.py
@@ -8,26 +8,39 @@ The ``algorithms`` module contains classes for conducting transport simulations
on pore networks.
"""
+
from .GenericAlgorithm import GenericAlgorithm
from .GenericTransport import GenericTransport
+
from .ReactiveTransport import ReactiveTransport
from .TransientReactiveTransport import TransientReactiveTransport
+
from .StokesFlow import StokesFlow
from .NonNewtonianStokesFlow import NonNewtonianStokesFlow
+
from .FickianDiffusion import FickianDiffusion
from .TransientFickianDiffusion import TransientFickianDiffusion
+
from .AdvectionDiffusion import AdvectionDiffusion
from .TransientAdvectionDiffusion import TransientAdvectionDiffusion
+
from .FourierConduction import FourierConduction
from .OhmicConduction import OhmicConduction
+
from .OrdinaryPercolation import OrdinaryPercolation
from .InvasionPercolation import InvasionPercolation
from .MixedInvasionPercolation import MixedInvasionPercolation
from .MixedInvasionPercolationCoop import MixedInvasionPercolationCoop
+
from .Porosimetry import Porosimetry
-from .NernstPlanck import NernstPlanck
-from .TransientNernstPlanck import TransientNernstPlanck
+
from .IonicConduction import IonicConduction
from .TransientIonicConduction import TransientIonicConduction
+
+from .NernstPlanck import NernstPlanck
+from .TransientNernstPlanck import TransientNernstPlanck
+
from .NernstPlanckMultiphysics import NernstPlanckMultiphysics
from .TransientNernstPlanckMultiphysics import TransientNernstPlanckMultiphysics
+
+from . import metrics
diff --git a/openpnm/algorithms/metrics/GenericMetric.py b/openpnm/algorithms/metrics/GenericMetric.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/metrics/GenericMetric.py
+++ b/openpnm/algorithms/metrics/GenericMetric.py
@@ -7,7 +7,6 @@ logger = logging.getLogger(__name__)
class GenericMetric(Base):
r"""
-
"""
def __init__(self, network=None, project=None, settings={}, **kwargs):
|
Added metrics import to algorithms' __init__ file
|
PMEAL_OpenPNM
|
train
|
13a522bfb2e15f3f6e5b023bd280e36bbdfb0403
|
diff --git a/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/internal/MFPAnalyticsActivityLifecycleListener.java b/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/internal/MFPAnalyticsActivityLifecycleListener.java
index <HASH>..<HASH> 100644
--- a/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/internal/MFPAnalyticsActivityLifecycleListener.java
+++ b/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/internal/MFPAnalyticsActivityLifecycleListener.java
@@ -112,7 +112,7 @@ public class MFPAnalyticsActivityLifecycleListener {
JSONObject metadata = new JSONObject();
try {
metadata.put(BMSAnalytics.CATEGORY, APP_SESSION_CATEGORY);
- metadata.put("timestamp", appUseStartTimestamp);
+ metadata.put(BMSAnalytics.TIMESTAMP_KEY, appUseStartTimestamp);
metadata.put(BMSAnalytics.APP_SESSION_ID_KEY, appSessionID);
} catch (JSONException e) {
// should not happen
|
Change metadata timestamp key to what Server expects
|
ibm-bluemix-mobile-services_bms-clientsdk-android-analytics
|
train
|
ece2700bcb23912d52fb48245ee531b4dd329c29
|
diff --git a/lib/react-native.web.js b/lib/react-native.web.js
index <HASH>..<HASH> 100644
--- a/lib/react-native.web.js
+++ b/lib/react-native.web.js
@@ -1,3 +1,3 @@
/* eslint-disable import/no-unresolved */
-export * from 'react-native-web/dist/cjs';
+export * from 'react-native-web';
|
fix: avoid exporting via unreliable path
|
oblador_react-native-vector-icons
|
train
|
13532c1ba335bbd7ea4e7657a9bf87eaf2977326
|
diff --git a/lib/github_cli/commands/gists.rb b/lib/github_cli/commands/gists.rb
index <HASH>..<HASH> 100644
--- a/lib/github_cli/commands/gists.rb
+++ b/lib/github_cli/commands/gists.rb
@@ -6,20 +6,19 @@ module GithubCLI
namespace :gist
desc 'list', 'List all gists'
- method_option :user, :type => :string, :aliases => ["-u"],
- :desc => 'List a <user> gists',
- :banner => '<user>'
- method_option :starred, :type => :boolean, :aliases => ["-s"],
- :default => false,
- :desc => 'List the authenticated users starred gists'
+ option :user, :type => :string, :aliases => ["-u"], :banner => '<user>',
+ :desc => 'List a <user> gists'
+ option :starred, :type => :boolean, :aliases => ["-s"], :default => false,
+ :desc => 'List the authenticated users starred gists'
+ option :since, :type => :string, :banner => "timestamp",
+ :desc => "a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ "
def list
if options[:starred]
Gist.starred options[:params], options[:format]
else
- if options[:user]
- options[:params]['user'] = options[:user]
- end
- Gist.all options[:params], options[:format]
+ params = options[:params].dup
+ params['user'] = options[:user] if options[:user]
+ Gist.all params, options[:format]
end
end
@@ -28,6 +27,10 @@ module GithubCLI
Gist.get id, options[:params], options[:format]
end
+ option :public, :type => :boolean, :default => false
+ option :desc, :type => :string
+ option :files, :type => :hash, :banner => "file1.txt:",
+ :desc => "Files that make up this gist. The key of which should be a required string filename and the value another required hash with parameters"
desc 'create', 'Create a gist'
long_desc <<-DESC
Create a gist
@@ -40,9 +43,16 @@ module GithubCLI
content - Required string - File contents.
DESC
def create
- Gist.create options[:params], options[:format]
+ params = options[:params].dup
+ params['description'] = options[:desc] if options[:desc]
+ params['public'] = options[:public] || false
+ params['files'] = options[:files] if options[:files]
+ Gist.create params, options[:format]
end
+ option :desc, :type => :string
+ option :files, :type => :hash, :banner => "file1.txt:",
+ :desc => "Files that make up this gist. The key of which should be a required string filename and the value another required hash with parameters"
desc 'edit <id>', 'Edit a gist'
long_desc <<-DESC
Edit a gist
@@ -55,7 +65,10 @@ module GithubCLI
filename - Optional string - New name for this file.\n
DESC
def edit(id)
- Gist.edit id, options[:params], options[:format]
+ params = options[:params].dup
+ params['description'] = options[:desc] if options[:desc]
+ params['files'] = options[:files] if options[:files]
+ Gist.edit id, params, options[:format]
end
desc 'star <id>', 'Star a gist'
|
Add gist commands specific options.
|
piotrmurach_github_cli
|
train
|
d10883de84770bf2f3b742bc017e8d2ea888a01d
|
diff --git a/lib/l10n-en_GB.js b/lib/l10n-en_GB.js
index <HASH>..<HASH> 100644
--- a/lib/l10n-en_GB.js
+++ b/lib/l10n-en_GB.js
@@ -40,13 +40,13 @@ exports.messages = {
, "headers.dl.this-link": "Link href and text differ for This Version."
, "headers.dl.this-date": "Mismatch between document date and This Version link."
, "headers.dl.no-date": "Cannot find document date."
-, "headers.dl.this-syntax": "Wrong syntax for This Version link. Use a 'https' link."
+, "headers.dl.this-syntax": "Wrong syntax for This Version link."
, "headers.dl.latest-link": "Link href and text differ for Latest Version."
, "headers.dl.this-latest-shortname": "<em>Shortnames</em> differ between This and Latest Versions."
-, "headers.dl.latest-syntax": "Wrong syntax for Latest Version link. Use a 'https' link."
+, "headers.dl.latest-syntax": "Wrong syntax for Latest Version link."
, "headers.dl.previous-link": "Link href and text differ for Previous Version."
, "headers.dl.this-previous-shortname": "<em>Shortnames</em> differ between This and Previous Versions."
-, "headers.dl.previous-syntax": "Wrong syntax for Previous Version link. Use a 'https' link."
+, "headers.dl.previous-syntax": "Wrong syntax for Previous Version link."
, "headers.dl.rescinds": "Rescinds this Recommendation is missing."
, "headers.dl.rescinds-not-needed": "Rescinds this Recommendation is included but does not seem necessary."
, "headers.dl.latest-rescinds-order": "Latest Version must be before Rescinds this Recommendation."
diff --git a/lib/rules/headers/dl.js b/lib/rules/headers/dl.js
index <HASH>..<HASH> 100644
--- a/lib/rules/headers/dl.js
+++ b/lib/rules/headers/dl.js
@@ -11,11 +11,26 @@ var PowerPromise = require('promise')
;
const self = {
- name: 'headers.dl'
-, section: 'front-matter'
- // @TODO: fine-tune, assigning different rules to particular errors below.
-, rule: 'docIDFormat'
-};
+ name: 'headers.dl'
+ , section: 'front-matter'
+ , rule: 'docIDFormat'
+ }
+, thisError = {
+ name: 'headers.dl'
+ , section: 'front-matter'
+ , rule: 'docIDThisVersion'
+}
+, latestError = {
+ name: 'headers.dl'
+ , section: 'front-matter'
+ , rule: 'docIDLatestVersion'
+}
+, previousError = {
+ name: 'headers.dl'
+ , section: 'front-matter'
+ , rule: 'docIDOrder'
+}
+;
exports.check = function (sr, done) {
@@ -89,7 +104,7 @@ exports.check = function (sr, done) {
}
else sr.warning(self, 'no-date');
}
- else sr.error(self, "this-syntax");
+ else sr.error(thisError, "this-syntax");
}
var sn;
@@ -106,7 +121,7 @@ exports.check = function (sr, done) {
latestURI = $linkLate.text();
if (sn !== shortname) sr.error(self, "this-latest-shortname");
}
- else sr.error(self, "latest-syntax");
+ else sr.error(latestError, "latest-syntax");
}
if (dts.Previous) {
@@ -126,7 +141,7 @@ exports.check = function (sr, done) {
});
}
}
- else sr.error(self, "previous-syntax");
+ else sr.error(previousError, "previous-syntax");
}
if (dts.Rescinds) {
|
Better messages for 'headers.dl'; more accurate rule descriptions.
(The error isn't necessarily that it ain't HTTPS).
Fixes #<I>.
|
w3c_specberus
|
train
|
7c90308b32097064a14d46e1631bb1de8735b7d2
|
diff --git a/test/lint.js b/test/lint.js
index <HASH>..<HASH> 100644
--- a/test/lint.js
+++ b/test/lint.js
@@ -4,6 +4,7 @@ var {testStyle} = require('./test-style');
var {testSchema} = require('./test-schema');
var {testVersions} = require('./test-versions');
var hasErrors, hasStyleErrors, hasSchemaErrors, hasVersionErrors = false;
+var filesWithErrors = {};
function load(...files) {
for (let file of files) {
@@ -19,10 +20,12 @@ function load(...files) {
} else {
hasSchemaErrors = testSchema(file);
hasStyleErrors = testStyle(file);
- hasVersionErrors = testVersions(file);
+ hasVersionErrors = testVersions(file);
}
if (hasStyleErrors || hasSchemaErrors || hasVersionErrors) {
hasErrors = true;
+ fileName = file.replace(path.resolve(__dirname, '..') + path.sep, '');
+ filesWithErrors[fileName] = file;
}
}
@@ -56,5 +59,13 @@ if (process.argv[2]) {
}
if (hasErrors) {
+ console.log("");
+ console.log(`Problems in ${Object.keys(filesWithErrors).length} files:`);
+ for (let file in filesWithErrors) {
+ console.log(file);
+ testSchema(filesWithErrors[file]);
+ testStyle(filesWithErrors[file]);
+ testVersions(filesWithErrors[file]);
+ }
process.exit(1);
}
|
Modify lint.js to output any errors at the end of the run. (#<I>)
|
mdn_browser-compat-data
|
train
|
a6b5b5f8c0458904ddf5ba8bc3815d7929f14a32
|
diff --git a/azure-toolkit-libs/azure-toolkit-sqlserver-lib/src/main/java/com/microsoft/azure/toolkit/lib/sqlserver/service/impl/SqlServer.java b/azure-toolkit-libs/azure-toolkit-sqlserver-lib/src/main/java/com/microsoft/azure/toolkit/lib/sqlserver/service/impl/SqlServer.java
index <HASH>..<HASH> 100644
--- a/azure-toolkit-libs/azure-toolkit-sqlserver-lib/src/main/java/com/microsoft/azure/toolkit/lib/sqlserver/service/impl/SqlServer.java
+++ b/azure-toolkit-libs/azure-toolkit-sqlserver-lib/src/main/java/com/microsoft/azure/toolkit/lib/sqlserver/service/impl/SqlServer.java
@@ -7,9 +7,9 @@ package com.microsoft.azure.toolkit.lib.sqlserver.service.impl;
import com.azure.core.management.exception.ManagementException;
import com.azure.resourcemanager.resources.fluentcore.arm.ResourceId;
import com.azure.resourcemanager.sql.SqlServerManager;
+import com.microsoft.azure.toolkit.lib.common.database.JdbcUrl;
import com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException;
import com.microsoft.azure.toolkit.lib.common.model.Region;
-import com.microsoft.azure.toolkit.lib.common.database.JdbcUrl;
import com.microsoft.azure.toolkit.lib.common.utils.NetUtils;
import com.microsoft.azure.toolkit.lib.sqlserver.model.SqlDatabaseEntity;
import com.microsoft.azure.toolkit.lib.sqlserver.model.SqlFirewallRuleEntity;
@@ -194,10 +194,10 @@ public class SqlServer implements ISqlServer {
private String getPublicIp(final com.azure.resourcemanager.sql.models.SqlServer sqlServerInner) {
// try to get public IP by ping SQL Server
- String username = SqlServer.this.entity.getAdministratorLoginName() + "@" + SqlServer.this.entity.getName();
+ String username = sqlServerInner.administratorLogin() + "@" + sqlServerInner.name();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- DriverManager.getConnection(JdbcUrl.sqlserver(SqlServer.this.sqlServerInner.fullyQualifiedDomainName()).toString(), username, null);
+ DriverManager.getConnection(JdbcUrl.sqlserver(sqlServerInner.fullyQualifiedDomainName()).toString(), username, null);
} catch (SQLException e) {
String ip = NetUtils.parseIpAddressFromMessage(e.getMessage());
if (StringUtils.isNotBlank(ip)) {
|
Fix NPE issue on allow access from local machine during sql server creation.
|
Microsoft_azure-maven-plugins
|
train
|
dd8959a554ef08d113aa6dfefb5673f6a1532025
|
diff --git a/views/partials/social-share.blade.php b/views/partials/social-share.blade.php
index <HASH>..<HASH> 100644
--- a/views/partials/social-share.blade.php
+++ b/views/partials/social-share.blade.php
@@ -1,18 +1,18 @@
<ul class="share share-social share-social-icon-md share-horizontal share-no-labels hidden-print inline-block">
<li>
- <a class="share-social-facebook" data-action="share-popup" href="https://www.facebook.com/sharer/sharer.php?u={!! urlencode(wp_get_shortlink()) !!}" data-tooltip="<?php _e('Share on', 'municipio'); ?> Facebook">
+ <a class="share-social-facebook" data-action="share-popup" href="https://www.facebook.com/sharer/sharer.php?u={!! urlencode(get_permalink()) !!}" data-tooltip="<?php _e('Share on', 'municipio'); ?> Facebook">
<i class="pricon pricon-facebook"></i>
<span><?php _e('Share on', 'municipio'); ?> Facebook</span>
</a>
</li>
<li>
- <a class="share-social-twitter" data-action="share-popup" href="http://twitter.com/share?url={!! urlencode(wp_get_shortlink()) !!}" data-tooltip="<?php _e('Share on', 'municipio'); ?> Twitter">
+ <a class="share-social-twitter" data-action="share-popup" href="http://twitter.com/share?url={!! urlencode(get_permalink()) !!}" data-tooltip="<?php _e('Share on', 'municipio'); ?> Twitter">
<i class="pricon pricon-twitter"></i>
<span><?php _e('Share on', 'municipio'); ?> Twitter</span>
</a>
</li>
<li>
- <a class="share-social-linkedin" data-action="share-popup" href="https://www.linkedin.com/shareArticle?mini=true&url={!! urlencode(wp_get_shortlink()) !!}&title={{ urlencode(get_the_title()) }}" data-tooltip="<?php _e('Share on', 'municipio'); ?> LinkedIn">
+ <a class="share-social-linkedin" data-action="share-popup" href="https://www.linkedin.com/shareArticle?mini=true&url={!! urlencode(get_permalink()) !!}&title={{ urlencode(get_the_title()) }}" data-tooltip="<?php _e('Share on', 'municipio'); ?> LinkedIn">
<i class="pricon pricon-linkedin"></i>
<span><?php _e('Share on', 'municipio'); ?> LinkedIn</span>
</a>
|
Use full url instead of shortlink
|
helsingborg-stad_Municipio
|
train
|
38f34f5eb49dfd02dca29664f67b15a3a56149b6
|
diff --git a/src/utils/createStyles.js b/src/utils/createStyles.js
index <HASH>..<HASH> 100644
--- a/src/utils/createStyles.js
+++ b/src/utils/createStyles.js
@@ -174,12 +174,12 @@ module.exports = (vr: any, options: any) => {
const { maxWidth } = modularScale
const { scale } = modularScale
- const h1 = vr.adjustFontSizeTo(`${ms(4/4, scale) * baseFontSize}px`)
- const h2 = vr.adjustFontSizeTo(`${ms(3/4, scale) * baseFontSize}px`)
- const h3 = vr.adjustFontSizeTo(`${ms(2/4, scale) * baseFontSize}px`)
- const h4 = vr.adjustFontSizeTo(`${ms(1/4, scale) * baseFontSize}px`)
- const h5 = vr.adjustFontSizeTo(`${ms(0/4, scale) * baseFontSize}px`)
- const h6 = vr.adjustFontSizeTo(`${ms(-1/4, scale) * baseFontSize}px`)
+ const h1 = vr.adjustFontSizeTo(`${ms(5/5, scale) * baseFontSize}px`)
+ const h2 = vr.adjustFontSizeTo(`${ms(4/5, scale) * baseFontSize}px`)
+ const h3 = vr.adjustFontSizeTo(`${ms(3/5, scale) * baseFontSize}px`)
+ const h4 = vr.adjustFontSizeTo(`${ms(2/5, scale) * baseFontSize}px`)
+ const h5 = vr.adjustFontSizeTo(`${ms(1/5, scale) * baseFontSize}px`)
+ const h6 = vr.adjustFontSizeTo(`${ms(0/5, scale) * baseFontSize}px`)
let media
if (maxWidth) {
|
Change number of 'notes' (n) in scale to 5
I'd misread <URL>
|
KyleAMathews_typography.js
|
train
|
da56f4c28aff86e2e26fcc54aa29fb091d5d4a07
|
diff --git a/bin/jira.py b/bin/jira.py
index <HASH>..<HASH> 100755
--- a/bin/jira.py
+++ b/bin/jira.py
@@ -213,12 +213,14 @@ Thank you very much,
def __get_issues_from_jira(self):
version_id = self.version_info['id']
project_id = self.project_info['id']
- request_url = "https://issues.jboss.org/secure/ReleaseNote.jspa?projectId=%s&version=%s&styleName=Text" % (project_id,version_id)
+ request_url = "https://issues.jboss.org/ReleaseNote.jspa?projectId=%s&version=%s&styleName=Text" % (project_id,version_id)
+ # print "*** JIRA issue list request: %s" % request_url
# make the HTML request ...
socket = urllib.urlopen(request_url)
html_response = socket.read()
socket.close()
# parse the HTML to extract find the relevant lines ...
+ print "*** HTML response: %s" % html_response
issue_type = ''
issue_exp = re.compile('\[(.*?)\]\s\-\s(.*)$')
for line in html_response.splitlines():
@@ -239,7 +241,8 @@ Thank you very much,
def __get_contributions_from_jira(self):
version_id = self.version_info['id']
project_id = self.project_info['id']
- request_url = "%ssecure/ConfigureReport.jspa?versions=%s&ctype=R&ctype=A&ctype=C&ccompany=A&selectedProjectId=%s&reportKey=org.jboss.labs.jira.plugin.patch-contributions-report-plugin:involvedInReleaseReport&Next=Next" % (self.jira_url,version_id,project_id)
+ request_url = "%sConfigureReport.jspa?versions=%s&ctype=R&ctype=A&ctype=C&ccompany=A&selectedProjectId=%s&reportKey=org.jboss.labs.jira.plugin.patch-contributions-report-plugin:involvedInReleaseReport&Next=Next" % (self.jira_url,version_id,project_id)
+ # print "*** JIRA contributions request: %s" % request_url
# make the HTML request ...
socket = urllib.urlopen(request_url)
html_response = socket.read()
@@ -316,10 +319,14 @@ def main():
project_key = 'MODE'
project_name = 'ModeShape'
project_id = '12310930'
- version = '2.5.0.Beta1'
+ version = '3.0.0.Alpha1'
jira = Jira(jira_url,project_key,project_id,project_name,version)
jira.fetch_release_info()
- print jira.get_release_notes_in_markdown()
+ contributor_emails = jira.get_contributor_emails()
+ print contributor_emails
+ html_content = jira.get_contribution_html("joe.smith@bcc_bogus.com")
+ print html_content
+ #print jira.get_release_notes_in_markdown()
#print jira.project_info()
#print jira.version_info()
#print jira.issues_by_email()
diff --git a/bin/release.py b/bin/release.py
index <HASH>..<HASH> 100755
--- a/bin/release.py
+++ b/bin/release.py
@@ -204,12 +204,6 @@ def copy_artifacts_to_archive_location(archive_path,version):
if os.path.exists(from_path):
copy_folder(from_path,os.path.join(docs_path,'xref'))
- # Copy the readme files into the downloads area and the docs area...
- for readme in ['release.html','release.txt']:
- from_path = os.path.join('target',readme)
- shutil.copy(from_path,os.path.join(docs_path,readme))
- shutil.copy(from_path,os.path.join(archive_path,readme))
-
# Copy the Reference Guide and Getting Started Guide ...
formats = ['html','html_single','pdf']
guides = ['reference','gettingstarted']
@@ -223,6 +217,20 @@ def copy_artifacts_to_archive_location(archive_path,version):
os.makedirs(to_path)
copy_folder(from_path,os.path.join(to_path,format))
+
+def copy_release_notes_to_archive_location(archive_path,version):
+ try:
+ os.makedirs(archive_path)
+ except:
+ pass
+
+ # Copy the release notes into the archive area...
+ for readme in ['release.html','release.txt']:
+ from_path = os.path.join('target',readme)
+ shutil.copy(from_path,os.path.join(docs_path,readme))
+ shutil.copy(from_path,os.path.join(archive_path,readme))
+
+
def copy_folder( from_path, to_path ):
if os.path.exists(to_path):
shutil.rmtree(to_path)
@@ -414,7 +422,8 @@ def release():
print "archive_path = '%s'" % archive_path
prettyprint("Step 5: Copying build artifacts and documentation to archive '%s'" % (archive_path), Levels.INFO)
#ALPHA1 copy_artifacts_to_archive_location(archive_path,version)
-#ALPHA1 prettyprint("Step 5: Complete", Levels.INFO)
+ copy_release_notes_to_archive_location(archive_path,version);
+ prettyprint("Step 5: Complete", Levels.INFO)
# Step 6: Generate contribution emails
prettyprint("Step 6: Generating contribution emails using JIRA and placing in '%s'" % (archive_path), Levels.INFO)
|
MODE-<I> Corrected build script to handle recent changes to JIRA
|
ModeShape_modeshape
|
train
|
adf98416a27f9e3ade34bd4a69162e47777ad046
|
diff --git a/browser_test/input_trigger_test.js b/browser_test/input_trigger_test.js
index <HASH>..<HASH> 100644
--- a/browser_test/input_trigger_test.js
+++ b/browser_test/input_trigger_test.js
@@ -1,6 +1,7 @@
define(["mocha/mocha", "chai", "jquery", "wed/domlistener",
- "wed/input_trigger", "wed/wed", "wed/key"],
-function (mocha, chai, $, domlistener, input_trigger, wed, key) {
+ "wed/input_trigger", "wed/wed", "wed/key", "wed/key_constants"],
+function (mocha, chai, $, domlistener, input_trigger, wed, key,
+ key_constants) {
var assert = chai.assert;
var Listener = domlistener.Listener;
var InputTrigger = input_trigger.InputTrigger;
@@ -157,6 +158,43 @@ describe("InputTrigger", function () {
assert.equal(seen, 0);
});
+ it("does not triggers on modifications of text when they key is " +
+ "not a text input key", function () {
+ var input_trigger = new InputTrigger(editor, ".p");
+ var seen = 0;
+ var DELETE = key_constants.DELETE;
+ input_trigger.addKeyHandler(DELETE, function (type, $el) {
+ seen++;
+ });
+
+ var $p = editor.$tree_root.find(".p").last();
+ var text = $p.get(0).lastChild;
+ // Make sure we're looking at the right thing.
+ assert.equal(text.nodeValue, " blah.");
+
+ // Initiate the change.
+ text.nodeValue = " blah...";
+ editor._syncDisplay();
+ assert.equal(seen, 0);
+ });
+
+ it("does not triggers on additions of text when they key is " +
+ "not a text input key", function () {
+ var input_trigger = new InputTrigger(editor, ".p");
+ var seen = 0;
+ var DELETE = key_constants.DELETE;
+ input_trigger.addKeyHandler(DELETE, function (type, $el) {
+ seen++;
+ });
+
+ var $p = editor.$tree_root.find(".p").last();
+ var text = document.createTextNode("...");
+ $p.append(text);
+ editor._syncDisplay();
+ assert.equal(seen, 0);
+ });
+
+
});
});
diff --git a/lib/wed/input_trigger.js b/lib/wed/input_trigger.js
index <HASH>..<HASH> 100644
--- a/lib/wed/input_trigger.js
+++ b/lib/wed/input_trigger.js
@@ -80,6 +80,8 @@ function InputTrigger(editor, selector) {
util.eventHandler(this._keydownHandler.bind(this)));
}
+var ignored_keys = key_constants.EDITING_KEYS;
+
/**
* <p>Adds a key handler to the object. The handler will be called
* as:</p>
@@ -162,7 +164,7 @@ InputTrigger.prototype._childrenChanged = function ($root, $added, $removed,
if (text.length === 0)
return;
- this._key_to_handler.forEach(function (key, handlers) {
+ this._text_input_key_to_handler.forEach(function (key, handlers) {
if (key.anyModifier())
return; // We care only about text input
@@ -178,7 +180,6 @@ InputTrigger.prototype._childrenChanged = function ($root, $added, $removed,
});
};
-var ignored_keys = key_constants.EDITING_KEYS;
InputTrigger.prototype._textChanged = function ($root, $el, old_value) {
this._text_input_key_to_handler.forEach(function (key, handlers) {
var ch = String.fromCharCode(key.which);
|
Fixed a bug which would cause spurious triggering of the handlers on non-text-input keys.
|
mangalam-research_wed
|
train
|
2e26bb6dc1003de842d61055da917edb78f0d34f
|
diff --git a/src/main/java/com/github/hypfvieh/util/SystemUtil.java b/src/main/java/com/github/hypfvieh/util/SystemUtil.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/hypfvieh/util/SystemUtil.java
+++ b/src/main/java/com/github/hypfvieh/util/SystemUtil.java
@@ -4,11 +4,15 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.management.ManagementFactory;
+import java.net.URL;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.Enumeration;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -267,4 +271,34 @@ public final class SystemUtil {
String pre = (_use1000BytesPerMb ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (_use1000BytesPerMb ? "" : "i");
return String.format("%.1f %sB", _bytes / Math.pow(unit, exp), pre);
}
+
+ /**
+ * Read the JARs manifest and try to get the current program version from it.
+ * @return version or null
+ */
+ public static String getApplicationVersionFromJar(Class<?> _class, String _default) {
+ try {
+ Enumeration<URL> resources = _class.getClassLoader().getResources("META-INF/MANIFEST.MF");
+ while (resources.hasMoreElements()) {
+
+ Manifest manifest = new Manifest(resources.nextElement().openStream());
+ Attributes attribs = manifest.getMainAttributes();
+ String ver = attribs.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
+ if (ver == null) {
+ return _default;
+ }
+
+ String rev = attribs.getValue("Implementation-Revision");
+ if (rev != null) {
+ ver += "-r" + rev;
+ }
+ return ver;
+
+ }
+ } catch (IOException _ex) {
+ }
+
+ return _default;
+
+ }
}
|
Added method to read version information from manifest
|
hypfvieh_java-utils
|
train
|
9d024478f75d3c7397b3a981448eef9d22cffeda
|
diff --git a/lib/chef/resource/user/windows_user.rb b/lib/chef/resource/user/windows_user.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/resource/user/windows_user.rb
+++ b/lib/chef/resource/user/windows_user.rb
@@ -28,7 +28,7 @@ class Chef
property :full_name, String,
description: "The full name of the user.",
- introduced: "14.5"
+ introduced: "14.6"
end
end
end
diff --git a/lib/chef/resource/zypper_package.rb b/lib/chef/resource/zypper_package.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/resource/zypper_package.rb
+++ b/lib/chef/resource/zypper_package.rb
@@ -38,7 +38,7 @@ class Chef
property :global_options, [ String, Array ],
description: "One (or more) additional options that are passed to the package resource other than options to the command.",
coerce: proc { |x| x.is_a?(String) ? x.shellsplit : x },
- introduced: "14.5"
+ introduced: "14.6"
end
end
end
|
Fixed introduced version to <I> for newly added properties in zypper_package and windows_user resource as it got released in <I>.
|
chef_chef
|
train
|
8be9498c4f6831333cb3c11f0c0921741609e7da
|
diff --git a/src/main/java/com/networknt/schema/JsonSchemaFactory.java b/src/main/java/com/networknt/schema/JsonSchemaFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/networknt/schema/JsonSchemaFactory.java
+++ b/src/main/java/com/networknt/schema/JsonSchemaFactory.java
@@ -187,24 +187,10 @@ public class JsonSchemaFactory {
}
}
- public JsonSchema getSchema(URL schemaUrl, String schema, SchemaValidatorsConfig config) {
- try {
- final JsonNode schemaNode = mapper.readTree(schema);
- return newJsonSchema(schemaUrl, schemaNode, config);
- } catch (IOException ioe) {
- logger.error("Failed to load json schema!", ioe);
- throw new JsonSchemaException(ioe);
- }
- }
-
public JsonSchema getSchema(String schema) {
- return getSchema(null, schema, null);
+ return getSchema(schema, null);
}
- public JsonSchema getSchema(URL schemaUrl, String schema) {
- return getSchema(schemaUrl, schema, null);
- }
-
public JsonSchema getSchema(InputStream schemaStream, SchemaValidatorsConfig config) {
try {
final JsonNode schemaNode = mapper.readTree(schemaStream);
@@ -215,24 +201,10 @@ public class JsonSchemaFactory {
}
}
- public JsonSchema getSchema(URL schemaUrl, InputStream schemaStream, SchemaValidatorsConfig config) {
- try {
- final JsonNode schemaNode = mapper.readTree(schemaStream);
- return newJsonSchema(schemaUrl, schemaNode, config);
- } catch (IOException ioe) {
- logger.error("Failed to load json schema!", ioe);
- throw new JsonSchemaException(ioe);
- }
- }
-
public JsonSchema getSchema(InputStream schemaStream) {
- return getSchema(null, schemaStream, null);
+ return getSchema(schemaStream, null);
}
- public JsonSchema getSchema(URL schemaUrl, InputStream schemaStream) {
- return getSchema(schemaUrl, schemaStream, null);
- }
-
public JsonSchema getSchema(URL schemaURL, SchemaValidatorsConfig config) {
try {
InputStream inputStream = null;
@@ -271,14 +243,6 @@ public class JsonSchemaFactory {
public JsonSchema getSchema(JsonNode jsonNode) {
return newJsonSchema(null, jsonNode, null);
}
-
- public JsonSchema getSchema(URL schemaUrl, JsonNode jsonNode, SchemaValidatorsConfig config) {
- return newJsonSchema(schemaUrl, jsonNode, config);
- }
-
- public JsonSchema getSchema(URL schemaUrl, JsonNode jsonNode) {
- return newJsonSchema(schemaUrl, jsonNode, null);
- }
private boolean idMatchesSourceUrl(JsonMetaSchema metaSchema, JsonNode schema, URL schemaUrl) {
|
Removed the factory methods that I added previously. Someone could get the same behavior by supplying a schemaUrl and utilizing a custom URLFetcher.
|
networknt_json-schema-validator
|
train
|
8391e5f01c62a55c5634df888ef9d0d8af6c1465
|
diff --git a/AegeanTools/fitting.py b/AegeanTools/fitting.py
index <HASH>..<HASH> 100644
--- a/AegeanTools/fitting.py
+++ b/AegeanTools/fitting.py
@@ -76,11 +76,9 @@ def Bmatrix(C):
# this version of finding the square root of the inverse matrix
# suggested by Cath Trott
L, Q = eigh(C)
- if not all(L > 0):
- log.warn("At least one eigenvalue is negative, this may cause problems!")
- log.warn("Forcing eigenvalues to be positive...")
- log.debug("L = {0}".format(L))
- L = np.abs(L)
+ # force very small eigenvalues to have some minimum non-zero value
+ minL = 1e-9*L[-1]
+ L[L < minL] = minL
S = np.diag(1 / np.sqrt(L))
B = Q.dot(S)
return B
|
properly deal with negative eigenvalues in the B matrix
|
PaulHancock_Aegean
|
train
|
62e62d522012fc7c3dc872ad98391770fb8badb6
|
diff --git a/src/Maker/MakeFunctionalTest.php b/src/Maker/MakeFunctionalTest.php
index <HASH>..<HASH> 100644
--- a/src/Maker/MakeFunctionalTest.php
+++ b/src/Maker/MakeFunctionalTest.php
@@ -84,11 +84,5 @@ class MakeFunctionalTest extends AbstractMaker
true,
true
);
- $dependencies->addClassDependency(
- PantherTestCaseTrait::class,
- 'panther',
- false,
- true
- );
}
}
|
Removed Panther dependency from the functional test maker
|
symfony_maker-bundle
|
train
|
8d205d887b24f4b46deb1311090d4c79d5d20102
|
diff --git a/tests/test_common.py b/tests/test_common.py
index <HASH>..<HASH> 100644
--- a/tests/test_common.py
+++ b/tests/test_common.py
@@ -365,15 +365,13 @@ def test_set_active_scalar_name():
grid.set_active_scalar_name = point_keys[0]
-# @pytest.mark.skipif(py2, reason="Unexplained error for python2.7")
-# def test_rename_scalar_point():
-# point_keys = list(grid.point_arrays.keys())
-# old_name = point_keys[0]
-# grid.set_active_scalar(old_name, 'point')
-# new_name = 'point changed'
-# grid.rename_scalar(old_name, new_name)
-# assert new_name in grid.point_arrays
-# grid._point_scalar() # errors if active array is not found
+def test_rename_scalar_point():
+ point_keys = list(grid.point_arrays.keys())
+ old_name = point_keys[0]
+ new_name = 'point changed'
+ grid.set_active_scalar(old_name, preference='point')
+ grid.rename_scalar(old_name, new_name, preference='point')
+ assert new_name in grid.point_arrays
def test_rename_scalar_cell():
|
Update rename_scalar test
|
vtkiorg_vtki
|
train
|
813de31a387199c3f7939dc7846cae51ab0538a1
|
diff --git a/rb/spec/integration/selenium/webdriver/element_spec.rb b/rb/spec/integration/selenium/webdriver/element_spec.rb
index <HASH>..<HASH> 100644
--- a/rb/spec/integration/selenium/webdriver/element_spec.rb
+++ b/rb/spec/integration/selenium/webdriver/element_spec.rb
@@ -62,7 +62,8 @@ module Selenium
end
# https://github.com/mozilla/geckodriver/issues/245
- it 'should send key presses chords', except: {browser: %i[firefox firefox_nightly safari safari_preview]} do
+ # https://bugs.chromium.org/p/chromedriver/issues/detail?id=3999
+ it 'should send key presses chords', except: {browser: %i[chrome firefox firefox_nightly safari safari_preview]} do
driver.navigate.to url_for('javascriptPage.html')
key_reporter = driver.find_element(id: 'keyReporter')
|
Disable send chords keys test for Chrome
|
SeleniumHQ_selenium
|
train
|
c2f52319ee7c7c626a9cf00a864b9b56177d3174
|
diff --git a/src/com/yahoo/ml/tf/TFSparkNode.py b/src/com/yahoo/ml/tf/TFSparkNode.py
index <HASH>..<HASH> 100755
--- a/src/com/yahoo/ml/tf/TFSparkNode.py
+++ b/src/com/yahoo/ml/tf/TFSparkNode.py
@@ -316,6 +316,9 @@ def run(fn, tf_args, cluster_meta, tensorboard, queues, background):
tb_proc = subprocess.Popen([pypath, "%s/tensorboard"%pydir, "--logdir=%s"%logdir, "--port=%d"%tb_port, "--debug"])
else:
# system-installed Python & tensorboard
+ python_path = os.environ['PYTHONPATH'].split(":")
+ for path in python_path:
+ os.environ['PATH'] = os.environ['PATH'] + os.pathsep + os.path.dirname(path)
tb_proc = subprocess.Popen(["tensorboard", "--logdir=%s"%logdir, "--port=%d"%tb_port, "--debug"])
tb_pid = tb_proc.pid
|
Fix if user didn't set `PYSPARK_PYTHON` at executor env
|
yahoo_TensorFlowOnSpark
|
train
|
234475e6a6763d386b2d73fcf45368c84ea99722
|
diff --git a/src/errorLog.js b/src/errorLog.js
index <HASH>..<HASH> 100644
--- a/src/errorLog.js
+++ b/src/errorLog.js
@@ -6,6 +6,6 @@ module.exports = function(name) {
return function(error) {
gutil.log(name, 'error', gutil.colors.red(error.message));
- }
+ };
};
diff --git a/src/pipes/less.js b/src/pipes/less.js
index <HASH>..<HASH> 100644
--- a/src/pipes/less.js
+++ b/src/pipes/less.js
@@ -10,7 +10,7 @@ function lessBasePipe(gulp) {
return gulp
.src('src/index.less')
.pipe(less())
- .on('error', errorLog('Less'))
+ .on('error', errorLog('Less'));
}
function lessDevPipe(gulp) {
diff --git a/src/tasks/css.js b/src/tasks/css.js
index <HASH>..<HASH> 100644
--- a/src/tasks/css.js
+++ b/src/tasks/css.js
@@ -4,7 +4,6 @@ function cssTask(gulp) {
gulp.task('css', ['bower'], function(doneCallback) {
- var less = require('gulp-less');
var lessPipe = require('../pipes/less');
var watchLog = require('../watchLog');
var config = require('../internalOptions');
diff --git a/src/tasks/test.js b/src/tasks/test.js
index <HASH>..<HASH> 100644
--- a/src/tasks/test.js
+++ b/src/tasks/test.js
@@ -22,7 +22,7 @@ function testTask(gulp) {
}));
if (internalOptions.singleRun) {
- return stream
+ return stream;
}
});
diff --git a/src/tasks/webserver.js b/src/tasks/webserver.js
index <HASH>..<HASH> 100644
--- a/src/tasks/webserver.js
+++ b/src/tasks/webserver.js
@@ -15,6 +15,6 @@ function taskWebserver(gulp) {
}));
});
-};
+}
module.exports = taskWebserver;
diff --git a/src/watchLog.js b/src/watchLog.js
index <HASH>..<HASH> 100644
--- a/src/watchLog.js
+++ b/src/watchLog.js
@@ -12,5 +12,5 @@ module.exports = function(name, gulp, glob, pipe) {
})
.on('change', function(event) {
gutil.log('Starting', gutil.colors.cyan(name), 'file', event.path, 'changed');
- })
+ });
};
|
improvments according to jshint
|
refilljs_refill-angular
|
train
|
76961505bedfc84693f07853f02786a667356b32
|
diff --git a/Loader/BundleLoader.php b/Loader/BundleLoader.php
index <HASH>..<HASH> 100755
--- a/Loader/BundleLoader.php
+++ b/Loader/BundleLoader.php
@@ -92,6 +92,7 @@ class BundleLoader
\Bazinga\Bundle\JsTranslationBundle\BazingaJsTranslationBundle::class,
\Liip\ImagineBundle\LiipImagineBundle::class,
\Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle::class,
+ \Cache\AdapterBundle\CacheAdapterBundle::class,
\WellCommerce\Bundle\AppBundle\WellCommerceAppBundle::class,
];
|
Cached datasets, second level cache
|
WellCommerce_CouponBundle
|
train
|
10b88ceaa0035502453a53fad6c0b3a4958490bd
|
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java
+++ b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java
@@ -348,12 +348,12 @@ public class WebSocket08FrameDecoder extends ReplayingDecoder<WebSocket08FrameDe
private void checkUTF8String(Channel channel, byte[] bytes) throws CorruptedFrameException {
try {
-
- StringBuilder sb = new StringBuilder("UTF8 " + bytes.length + " bytes: ");
- for (byte b : bytes) {
- sb.append(Integer.toHexString(b)).append(" ");
- }
- logger.debug(sb.toString());
+ // StringBuilder sb = new StringBuilder("UTF8 " + bytes.length +
+ // " bytes: ");
+ // for (byte b : bytes) {
+ // sb.append(Integer.toHexString(b)).append(" ");
+ // }
+ // logger.debug(sb.toString());
if (fragmentedFramesText == null) {
fragmentedFramesText = new UTF8Output(bytes);
|
AutoBahn tests 9 working. All done :-)
|
netty_netty
|
train
|
76066dc779204338cfd294edc23affcaa085795a
|
diff --git a/AppiumLibrary/keywords/_android_utils.py b/AppiumLibrary/keywords/_android_utils.py
index <HASH>..<HASH> 100644
--- a/AppiumLibrary/keywords/_android_utils.py
+++ b/AppiumLibrary/keywords/_android_utils.py
@@ -155,4 +155,16 @@ class _AndroidUtilsKeywords(KeywordGroup):
"""
driver = self._current_application()
driver.install_app(app_path)
- return driver.is_app_installed(app_package)
\ No newline at end of file
+ return driver.is_app_installed(app_package)
+
+ def set_location(self, latitude, longitude, altitude=10):
+ """ Set location
+
+ - _latitute_
+ - _longitude_
+ - _altitude_ = 10 [optional]
+
+ Android only
+ """
+ driver = self._current_application()
+ driver.set_location(latitude,longitude,altitude)
|
Add a Set Location keyword
Add a keyword to set the location of the device. For Android only.
|
serhatbolsu_robotframework-appiumlibrary
|
train
|
2d10526ccc57d719729f65070c0d0aecbb70b2c2
|
diff --git a/src/createApp.js b/src/createApp.js
index <HASH>..<HASH> 100644
--- a/src/createApp.js
+++ b/src/createApp.js
@@ -73,7 +73,6 @@ class BaseApp {
const store = this._getStore();
const state$ = new Subject();
- // @TODO: take care of this leak
this._storeSubscription = store.subscribe(() => {
state$.next(store.getState());
});
|
remove TODO for leak that is already taken care of (#<I>)
|
frintjs_frint
|
train
|
aefd09d0d6047ed8ed37cba4d991a4dff7cf009e
|
diff --git a/src/Form/Field/Select.php b/src/Form/Field/Select.php
index <HASH>..<HASH> 100644
--- a/src/Form/Field/Select.php
+++ b/src/Form/Field/Select.php
@@ -46,7 +46,7 @@ class Select extends Field
if (is_string($options)) {
// reload selected
if (class_exists($options) && in_array('Illuminate\Database\Eloquent\Model', class_parents($options))) {
- return $this->selected(...func_get_args());
+ return $this->model(...func_get_args());
}
return $this->loadRemoteOptions(...func_get_args());
@@ -191,14 +191,14 @@ EOT;
* Load options from current selected resource(s).
*
* @param Illuminate\Database\Eloquent\Model $model
- * @param string $textField
* @param string $idField
+ * @param string $textField
*
* @return $this
*/
- protected function selected($model, $textField = 'name', $idField = 'id')
+ public function model($model, $idField = 'id', $textField = 'name')
{
- $this->options = function ($resource) use ($model, $textField, $idField) {
+ $this->options = function ($resource) use ($model, $idField, $textField) {
if (null == $resource) {
return [];
}
|
changed method name in Form/Field/Select from selected to model and now is public, fixed argument order in model method.
|
z-song_laravel-admin
|
train
|
cbfc8bf125e83bfb9b1cfecd21152a2a7e59de79
|
diff --git a/controller/src/main/java/io/pravega/controller/fault/SegmentMonitorLeader.java b/controller/src/main/java/io/pravega/controller/fault/SegmentMonitorLeader.java
index <HASH>..<HASH> 100644
--- a/controller/src/main/java/io/pravega/controller/fault/SegmentMonitorLeader.java
+++ b/controller/src/main/java/io/pravega/controller/fault/SegmentMonitorLeader.java
@@ -9,7 +9,6 @@
*/
package io.pravega.controller.fault;
-import io.pravega.common.TimeoutTimer;
import io.pravega.common.cluster.Cluster;
import io.pravega.common.cluster.ClusterType;
import io.pravega.common.cluster.Host;
@@ -46,9 +45,6 @@ class SegmentMonitorLeader implements LeaderSelectorListener {
//The pravega cluster which this host controller manages.
private Cluster pravegaServiceCluster = null;
- //The timer to ensure we maintain a minimum interval between expensive rebalance operations.
- private TimeoutTimer timeoutTimer = null;
-
//The minimum interval between any two rebalance operations. The minimum duration is not guaranteed when leadership
//moves across controllers. Since this is uncommon and there are no significant side-effects to it, we don't
//handle this scenario.
@@ -143,12 +139,13 @@ class SegmentMonitorLeader implements LeaderSelectorListener {
}
hostsChange.acquire();
- log.debug("Received rebalance event");
+ log.info("Received rebalance event");
- //Wait here until the rebalance timer is zero so that we honor the minimum rebalance interval.
+ // Wait here until rebalance can be performed.
waitForRebalance();
- //Clear all events that has been received until this point.
+ // Clear all events that has been received until this point since this will be included in the current
+ // rebalance operation.
hostsChange.drainPermits();
triggerRebalance();
} catch (InterruptedException e) {
@@ -171,14 +168,14 @@ class SegmentMonitorLeader implements LeaderSelectorListener {
}
/**
- * Blocks until the rebalance timer is zero so that we honor the minimum rebalance interval.
+ * Blocks until the rebalance interval. This wait serves multiple purposes:
+ * -- Ensure rebalance does not happen in quick succession since its a costly cluster level operation.
+ * -- Clubs multiple host events into one to reduce rebalance operations. For example:
+ * Fresh cluster start, cluster/multi-host/host restarts, etc.
*/
private void waitForRebalance() throws InterruptedException {
- if (timeoutTimer != null && timeoutTimer.getRemaining().getSeconds() > 0) {
- log.info("Waiting for {} seconds before attempting to rebalance",
- timeoutTimer.getRemaining().getSeconds());
- Thread.sleep(timeoutTimer.getRemaining().getSeconds() * 1000);
- }
+ log.info("Waiting for {} seconds before attempting to rebalance", minRebalanceInterval.getSeconds());
+ Thread.sleep(minRebalanceInterval.toMillis());
}
private void triggerRebalance() throws IOException {
@@ -189,9 +186,6 @@ class SegmentMonitorLeader implements LeaderSelectorListener {
hostStore.updateHostContainersMap(newMapping);
} catch (Exception e) {
throw new IOException(e);
- } finally {
- //Reset the rebalance timer.
- timeoutTimer = new TimeoutTimer(minRebalanceInterval);
}
}
diff --git a/controller/src/test/java/io/pravega/controller/fault/SegmentContainerMonitorTest.java b/controller/src/test/java/io/pravega/controller/fault/SegmentContainerMonitorTest.java
index <HASH>..<HASH> 100644
--- a/controller/src/test/java/io/pravega/controller/fault/SegmentContainerMonitorTest.java
+++ b/controller/src/test/java/io/pravega/controller/fault/SegmentContainerMonitorTest.java
@@ -124,7 +124,7 @@ public class SegmentContainerMonitorTest {
}
SegmentContainerMonitor monitor = new SegmentContainerMonitor(new MockHostControllerStore(), zkClient,
- new UniformContainerBalancer(), 5);
+ new UniformContainerBalancer(), 2);
monitor.startAsync().awaitRunning();
assertEquals(hostStore.getContainerCount(), Config.HOST_STORE_CONTAINER_COUNT);
|
Issue <I>: SegmentContainerMonitor: handle multiple host events (#<I>)
* Using timeout heuristics to club multiple host events which happen in quick succession into one
rebalance operation. This handle cases like node restart, fresh cluster start, multi-host
start/failures, etc.
|
pravega_pravega
|
train
|
7bad20851349cafe2c256b9b17f4f6c2b2e91dcc
|
diff --git a/rpc/amqp-rpc.go b/rpc/amqp-rpc.go
index <HASH>..<HASH> 100644
--- a/rpc/amqp-rpc.go
+++ b/rpc/amqp-rpc.go
@@ -476,7 +476,7 @@ type AmqpRPCCLient struct {
timeout time.Duration
log *blog.AuditLogger
- mu sync.Mutex
+ mu sync.RWMutex
pending map[string]chan []byte
}
@@ -513,9 +513,9 @@ func NewAmqpRPCClient(clientQueuePrefix, serverQueue string, channel *amqp.Chann
for msg := range msgs {
// XXX-JWS: jws.Sign(privKey, body)
corrID := msg.CorrelationId
- rpc.mu.Lock()
+ rpc.mu.RLock()
responseChan, present := rpc.pending[corrID]
- rpc.mu.Unlock()
+ rpc.mu.RUnlock()
rpc.log.Debug(fmt.Sprintf(" [c<][%s] response %s(%s) [%s]", clientQueue, msg.Type, core.B64enc(msg.Body), corrID))
if !present {
|
Use RW lock for reading from pending map
|
letsencrypt_boulder
|
train
|
d966b65568491c2572b1db162519c3931ccd9f71
|
diff --git a/common/models/resources/Category.php b/common/models/resources/Category.php
index <HASH>..<HASH> 100755
--- a/common/models/resources/Category.php
+++ b/common/models/resources/Category.php
@@ -241,7 +241,7 @@ class Category extends \cmsgears\core\common\models\hierarchy\NestedSetModel {
*/
public static function getFeaturedByType( $type ) {
- return self::find()->where( 'type=:type AND featured=1', [ ':type' => $type ] )->orderBy( [ 'name' => SORT_ASC ] )->all();
+ return self::find()->where( 'type=:type AND featured=1', [ ':type' => $type ] )->orderBy( [ 'order' => SORT_ASC ] )->all();
}
// Create -----------------
|
Resolved category order issue.
|
cmsgears_module-core
|
train
|
4ac7c123b88b23d3ac7527960507287962dc97b3
|
diff --git a/wily/__main__.py b/wily/__main__.py
index <HASH>..<HASH> 100644
--- a/wily/__main__.py
+++ b/wily/__main__.py
@@ -1,3 +1,9 @@
+"""
+Main command line
+
+TODO : Prompt the user for the specific metric in the graph and report commands?
+"""
+
import click
from wily import logger
from wily.cache import exists
diff --git a/wily/cache.py b/wily/cache.py
index <HASH>..<HASH> 100644
--- a/wily/cache.py
+++ b/wily/cache.py
@@ -1,5 +1,9 @@
"""
A module for working with the .wily/ cache directory
+
+TODO: Implement `clean` command, currently fails. Needs to do `rm -rf .wily` equivalent
+TODO: Version .wily/ cache folders?
+TODO: Validate that if wily config specifies alternative directory that all commands work
"""
import pathlib
diff --git a/wily/commands/build.py b/wily/commands/build.py
index <HASH>..<HASH> 100644
--- a/wily/commands/build.py
+++ b/wily/commands/build.py
@@ -1,5 +1,7 @@
"""
Builds a cache based on a source-control history
+
+TODO : Compare with existing files and cache results, currently just overwrites
"""
from progress.bar import Bar
diff --git a/wily/commands/graph.py b/wily/commands/graph.py
index <HASH>..<HASH> 100644
--- a/wily/commands/graph.py
+++ b/wily/commands/graph.py
@@ -1,3 +1,10 @@
+"""
+Draw graph in HTML for a specific metric
+
+
+TODO: Make X-axis relative to the timestamp of the commit
+TODO: Somehow link to the rev-hash?
+"""
from wily import logger, format_date
import tabulate
import pathlib
diff --git a/wily/commands/index.py b/wily/commands/index.py
index <HASH>..<HASH> 100644
--- a/wily/commands/index.py
+++ b/wily/commands/index.py
@@ -1,3 +1,9 @@
+"""
+Print information about the wily cache and what is in the index
+
+TODO : Optional flag to include commit messages in table
+
+"""
from wily import logger, format_date
import tabulate
import wily.cache as cache
diff --git a/wily/commands/list_metrics.py b/wily/commands/list_metrics.py
index <HASH>..<HASH> 100644
--- a/wily/commands/list_metrics.py
+++ b/wily/commands/list_metrics.py
@@ -1,3 +1,9 @@
+"""
+List available metrics across all providers
+
+TODO : Only show metrics for the operators that the cache has?
+"""
+
from wily.operators import ALL_OPERATORS
from wily.config import DEFAULT_GRID_STYLE
import tabulate
diff --git a/wily/commands/report.py b/wily/commands/report.py
index <HASH>..<HASH> 100644
--- a/wily/commands/report.py
+++ b/wily/commands/report.py
@@ -1,3 +1,9 @@
+"""
+TODO : Implement a limit on the number of records returned
+TODO : Fix float-rendering and rounding
+TODO : Fix str-type rendering
+TODO : Better error handling of wonky builds
+"""
from wily import logger, format_date
import tabulate
import pathlib
diff --git a/wily/config.py b/wily/config.py
index <HASH>..<HASH> 100644
--- a/wily/config.py
+++ b/wily/config.py
@@ -1,6 +1,8 @@
"""
Configuration of wily
+TODO : Handle operator settings
+TODO : Allow configuration of cache path (incase it needs to go in another folder)
"""
import configparser
diff --git a/wily/operators/cyclomatic.py b/wily/operators/cyclomatic.py
index <HASH>..<HASH> 100644
--- a/wily/operators/cyclomatic.py
+++ b/wily/operators/cyclomatic.py
@@ -1,3 +1,11 @@
+"""
+Cyclomatic complexity metric for each function/method
+
+Provided by the radon library
+
+TODO : Figure out how to deal with the list metrics for functions?
+"""
+
import radon.cli.harvest as harvesters
from radon.cli import Config
import radon
@@ -17,7 +25,6 @@ class CyclomaticComplexityOperator(BaseOperator):
"order": radon.complexity.SCORE,
}
- # TODO : Figure out how to deal with the list metrics for functions?
metrics = ()
def __init__(self, config):
|
braindump all the features/fixes/known issues
|
tonybaloney_wily
|
train
|
0a013f821bd6da8376c40c1ce0e6ea156e77165e
|
diff --git a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
index <HASH>..<HASH> 100644
--- a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
+++ b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
@@ -76,7 +76,7 @@ abstract class ArchiveConductor extends SessionWorker<Session>
ArchiveConductor(final Aeron aeron, final Archive.Context ctx)
{
- super("archive-conductor", ctx.errorHandler());
+ super("archive-conductor", ctx.countedErrorHandler());
this.aeron = aeron;
this.ctx = ctx;
|
[Java] Make use of CountedErrorHandler within session workers.
|
real-logic_aeron
|
train
|
5f5bc901f2cd9e923d6863b2e8ad7781f2d9cd69
|
diff --git a/cuisinart.js b/cuisinart.js
index <HASH>..<HASH> 100644
--- a/cuisinart.js
+++ b/cuisinart.js
@@ -84,14 +84,18 @@ var printUsage = function(command){
var hasCallback = function(fn){
// check if the following are true:
// 1. we have a named argument
- // 2. we call, apply, or invoke a variable by that name in the method body
+ // one of:
+ // 2a. we call, apply, or invoke a variable by that name in the method body
+ // 2b. we pass a variable of that name as an argument to another function.
// This gives us a good estimate if the function is async or not.
var fnString = fn.toString();
var argMatches = fnString.match(/^function \((?:.*[,\s]+)?([\w]+)\){/);
if(!argMatches) return false;
+ fnString = fnString.replace(argMatches[0],'');
var lastArg = argMatches[1];
- var cbPattern = new RegExp(';?[\\s\\S]*' + lastArg + '\\.?(call|apply)?\\([^\\)]*\\)[\\s\\S]*;?');
- return cbPattern.test(fnString);
+ var cbPattern = new RegExp(';?[\\s\\S]*' + lastArg + '\\.?(call|apply|bind)?\\([^\\)]*\\)[\\s\\S]*;?');
+ var argPattern = new RegExp('\\w(\\(|\\([^\\)]+[,\\s])'+lastArg+'([,\\s][^\\)]+\\)|\\))');
+ return cbPattern.test(fnString) || argPattern.test(fnString);
};
var unmatchedArgs = function(){
|
validate callbacks if called as arguments to another method
|
misejs_cuisinart
|
train
|
8ebe9b5b9a3f3ed4c616c407ccdaf5008929fbb9
|
diff --git a/lib/netsuite/records/invoice.rb b/lib/netsuite/records/invoice.rb
index <HASH>..<HASH> 100644
--- a/lib/netsuite/records/invoice.rb
+++ b/lib/netsuite/records/invoice.rb
@@ -19,7 +19,7 @@ module NetSuite
:handling_tax_2_rate, :handling_tax_code, :is_taxable, :item_cost_disc_amount, :item_cost_disc_print,
:item_cost_disc_rate, :item_cost_disc_tax_1_amt, :item_cost_disc_taxable, :item_cost_discount, :item_cost_list,
:item_cost_tax_code, :item_cost_tax_rate_1, :item_cost_tax_rate_2, :item_list, :job, :last_modified_date,
- :lead_source, :linked_tracking_numbers, :memo, :message, :message_sel, :on_credit_hold, :opportunity,
+ :linked_tracking_numbers, :memo, :message, :message_sel, :on_credit_hold, :opportunity,
:other_ref_num, :partners_list, :promo_code, :rev_rec_end_date,
:rev_rec_on_rev_commitment, :rev_rec_schedule, :rev_rec_start_date, :revenue_status, :sales_effective_date,
:sales_group, :sales_team_list, :ship_address, :ship_date, :ship_group_list,
@@ -40,7 +40,7 @@ module NetSuite
record_refs :account, :bill_address_list, :custom_form, :department, :entity, :klass, :partner,
:posting_period, :ship_address_list, :terms, :location, :sales_rep, :tax_item, :created_from,
- :ship_method
+ :ship_method, :lead_source
attr_reader :internal_id
attr_accessor :external_id
|
Moving lead_source on invoice to record ref type
|
NetSweet_netsuite
|
train
|
00764fedd352d02a614aefe0831339ea1f44bbd9
|
diff --git a/file/class.filesystemfile.php b/file/class.filesystemfile.php
index <HASH>..<HASH> 100644
--- a/file/class.filesystemfile.php
+++ b/file/class.filesystemfile.php
@@ -4,7 +4,7 @@
*
* @author Gregor Kofler
*
- * @version 0.3.10 2012-09-24
+ * @version 0.3.11 2012-10-26
*
* @todo properly deal with 10.04 Ubuntu bug (PHP 5.3.2)
*/
@@ -144,6 +144,10 @@ class FilesystemFile {
$oldpath = $this->folder->getPath().$from;
$newpath = $this->folder->getPath().$to;
+ if(file_exists($newpath)) {
+ throw new FilesystemFileException("Rename from '$oldpath' to '$newpath' failed. '$newpath' already exists.", FilesystemFileException::FILE_RENAME_FAILED);
+ }
+
if(@rename($oldpath, $newpath)) {
self::$instances[$newpath] = $this;
unset(self::$instances[$oldpath]);
|
FilesystemFile::rename() doesn't overwrite existing files.
Change-Id: I<I>a2a<I>a<I>b<I>fbff<I>bc<I>d7f
|
Vectrex_vxPHP
|
train
|
6f4c205a0a6372016f5de610ba772927b150707f
|
diff --git a/lib/chef/provisioning/aws_driver/driver.rb b/lib/chef/provisioning/aws_driver/driver.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provisioning/aws_driver/driver.rb
+++ b/lib/chef/provisioning/aws_driver/driver.rb
@@ -987,10 +987,27 @@ EOD
def create_winrm_transport(machine_spec, machine_options, instance)
remote_host = determine_remote_host(machine_spec, instance)
+ username = machine_options[:winrm_username] || 'Administrator'
+ # default to http for now, should upgrade to https when knife support self-signed
+ transport_type = machine_options[:winrm_transport] || 'http'
+ type = case transport_type
+ when 'http'
+ :plaintext
+ when 'https'
+ :ssl
+ end
+ if machine_spec.reference[:winrm_port]
+ port = machine_spec.reference[:winrm_port]
+ else #default port
+ port = case transport_type
+ when 'http'
+ '5985'
+ when 'https'
+ '5986'
+ end
+ end
+ endpoint = "#{transport_type}://#{remote_host}:#{port}/wsman"
- port = machine_spec.reference['winrm_port'] || 5985
- endpoint = "http://#{remote_host}:#{port}/wsman"
- type = :plaintext
pem_bytes = get_private_key(instance.key_name)
# TODO plaintext password = bad
|
cleanup winrm user, transport, port, endpoint opts
|
chef_chef-provisioning-aws
|
train
|
3f9565e6383da544bf110f37585800182df5227b
|
diff --git a/lib/Doctrine/Sequence/Firebird.php b/lib/Doctrine/Sequence/Firebird.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Sequence/Firebird.php
+++ b/lib/Doctrine/Sequence/Firebird.php
@@ -32,5 +32,72 @@ Doctrine::autoload('Doctrine_Sequence');
*/
class Doctrine_Sequence_Firebird extends Doctrine_Sequence
{
-
+ /**
+ * Returns the next free id of a sequence
+ *
+ * @param string $seqName name of the sequence
+ * @param bool when true missing sequences are automatic created
+ *
+ * @return integer next id in the given sequence
+ */
+ public function nextID($seqName, $ondemand = true)
+ {
+ $sequence_name = $this->getSequenceName($seq_name);
+ $query = 'SELECT GEN_ID('.$sequence_name.', 1) as the_value FROM RDB$DATABASE';
+ $this->expectError('*');
+ $result = $this->queryOne($query, 'integer');
+ $this->popExpect();
+ if (PEAR::isError($result)) {
+ if ($ondemand) {
+ $this->loadModule('Manager', null, true);
+ // Since we are creating the sequence on demand
+ // we know the first id = 1 so initialize the
+ // sequence at 2
+ $result = $this->manager->createSequence($seq_name, 2);
+ if (PEAR::isError($result)) {
+ return $this->raiseError($result, null, null,
+ 'on demand sequence could not be created', __FUNCTION__);
+ } else {
+ // First ID of a newly created sequence is 1
+ // return 1;
+ // BUT generators are not always reset, so return the actual value
+ return $this->currID($seq_name);
+ }
+ }
+ }
+ return $result;
+ }
+ /**
+ * Returns the autoincrement ID if supported or $id or fetches the current
+ * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
+ *
+ * @param string name of the table into which a new row was inserted
+ * @param string name of the field into which a new row was inserted
+ */
+ public function lastInsertID($table = null, $field = null)
+ {
+ throw new Doctrine_Sequence_Exception('method not implemented');
+ }
+ /**
+ * Returns the current id of a sequence
+ *
+ * @param string $seqName name of the sequence
+ *
+ * @return integer current id in the given sequence
+ */
+ public function currID($seqName)
+ {
+ $sequence_name = $this->getSequenceName($seq_name);
+ $query = 'SELECT GEN_ID('.$sequence_name.', 0) as the_value FROM RDB$DATABASE';
+ $value = $this->queryOne($query);
+ if (PEAR::isError($value)) {
+ return $this->raiseError($result, null, null,
+ 'Unable to select from ' . $seq_name, __FUNCTION__);
+ }
+ if (!is_numeric($value)) {
+ return $this->raiseError(MDB2_ERROR, null, null,
+ 'could not find value in sequence table', __FUNCTION__);
+ }
+ return $value;
+ }
}
|
ported interbase sequence functionality, still needs refactoring
|
doctrine_orm
|
train
|
73dc19e4983eb4be4e29d24db5ea077260cbc562
|
diff --git a/core/server/api/canary/members.js b/core/server/api/canary/members.js
index <HASH>..<HASH> 100644
--- a/core/server/api/canary/members.js
+++ b/core/server/api/canary/members.js
@@ -429,42 +429,6 @@ module.exports = {
}
},
- validateImport: {
- permissions: {
- method: 'add'
- },
- headers: {},
- async query(frame) {
- const importedMembers = frame.data.members;
-
- await Promise.map(importedMembers, (async (entry) => {
- if (entry.stripe_customer_id) {
- if (!membersService.config.isStripeConnected()) {
- throw new errors.ValidationError({
- message: i18n.t('errors.api.members.stripeNotConnected.message', {
- id: entry.stripe_customer_id
- }),
- context: i18n.t('errors.api.members.stripeNotConnected.context'),
- help: i18n.t('errors.api.members.stripeNotConnected.help')
- });
- }
-
- try {
- await membersService.api.members.getStripeCustomer(entry.stripe_customer_id);
- } catch (error) {
- throw new errors.ValidationError({
- message: `Member not imported. ${error.message}`,
- context: i18n.t('errors.api.members.stripeCustomerNotFound.context'),
- help: i18n.t('errors.api.members.stripeCustomerNotFound.help')
- });
- }
- }
- }));
-
- return null;
- }
- },
-
importCSV: {
statusCode: 201,
permissions: {
diff --git a/core/server/web/api/canary/admin/routes.js b/core/server/web/api/canary/admin/routes.js
index <HASH>..<HASH> 100644
--- a/core/server/web/api/canary/admin/routes.js
+++ b/core/server/web/api/canary/admin/routes.js
@@ -93,7 +93,6 @@ module.exports = function apiRoutes() {
router.get('/members/stats', shared.middlewares.labs.members, mw.authAdminApi, http(apiCanary.members.stats));
- router.post('/members/upload/validate', shared.middlewares.labs.members, mw.authAdminApi, http(apiCanary.members.validateImport));
router.get('/members/upload', shared.middlewares.labs.members, mw.authAdminApi, http(apiCanary.members.exportCSV));
router.post('/members/upload',
shared.middlewares.labs.members,
diff --git a/test/api-acceptance/admin/members_spec.js b/test/api-acceptance/admin/members_spec.js
index <HASH>..<HASH> 100644
--- a/test/api-acceptance/admin/members_spec.js
+++ b/test/api-acceptance/admin/members_spec.js
@@ -261,49 +261,6 @@ describe('Members API', function () {
.expect(404);
});
- it('Can validate import data', async function () {
- const member = {
- name: 'test',
- email: 'memberTestAdd@test.com'
- };
-
- const res = await request
- .post(localUtils.API.getApiQuery(`members/upload/validate`))
- .send({members: [member]})
- .set('Origin', config.get('url'))
- .expect('Content-Type', /json/)
- .expect('Cache-Control', testUtils.cacheRules.private)
- .expect(200);
-
- should.not.exist(res.headers['x-cache-invalidate']);
- const jsonResponse = res.body;
- should.exist(jsonResponse);
- should.not.exist(jsonResponse.members);
- });
-
- it('Fails to validate import data when stripe_customer_id is present but Stripe is not connected', async function () {
- const member = {
- name: 'test',
- email: 'memberTestAdd@test.com',
- stripe_customer_id: 'cus_XXXXX'
- };
-
- const res = await request
- .post(localUtils.API.getApiQuery(`members/upload/validate`))
- .send({members: [member]})
- .set('Origin', config.get('url'))
- .expect('Content-Type', /json/)
- .expect('Cache-Control', testUtils.cacheRules.private)
- .expect(422);
-
- should.not.exist(res.headers['x-cache-invalidate']);
- const jsonResponse = res.body;
- should.exist(jsonResponse);
- should.exist(jsonResponse.errors);
- jsonResponse.errors[0].message.should.match(/Missing Stripe connection/i);
- jsonResponse.errors[0].context.should.match(/no Stripe account connected/i);
- });
-
it('Can export CSV', async function () {
const res = await request
.get(localUtils.API.getApiQuery(`members/upload/`))
|
Removed Members CSV import validation endpoint
no-issue
The new import flow does not use prevalidation of the CSV file, so we
have no use for this anymore.
|
TryGhost_Ghost
|
train
|
7f5bded0ac7ee25c269d0cddc2e0be00589dbd97
|
diff --git a/raiden/tests/utils/smoketest.py b/raiden/tests/utils/smoketest.py
index <HASH>..<HASH> 100644
--- a/raiden/tests/utils/smoketest.py
+++ b/raiden/tests/utils/smoketest.py
@@ -332,6 +332,7 @@ def start_ethereum(smoketest_genesis):
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
+ encoding='UTF-8',
)
ethereum_node.stdin.write(TEST_ACCOUNT_PASSWORD + os.linesep)
time.sleep(.1)
diff --git a/raiden/ui/cli.py b/raiden/ui/cli.py
index <HASH>..<HASH> 100644
--- a/raiden/ui/cli.py
+++ b/raiden/ui/cli.py
@@ -812,7 +812,7 @@ def smoketest(ctx, debug, **kwargs):
open(report_file, 'w+')
def append_report(subject, data):
- with open(report_file, 'a') as handler:
+ with open(report_file, 'a', encoding='UTF-8') as handler:
handler.write('{:=^80}'.format(' %s ' % subject.upper()) + os.linesep)
if data is not None:
if isinstance(data, bytes):
|
Set encoding in smoketest for macOS
macOS does not define `LANG` and `LC_*` etc. variables in the shell
by default. We must set the correct encoding for the Popen call.
|
raiden-network_raiden
|
train
|
37fffdb154996ef5757f23c999a1f327c10903ea
|
diff --git a/lib/middleware.js b/lib/middleware.js
index <HASH>..<HASH> 100644
--- a/lib/middleware.js
+++ b/lib/middleware.js
@@ -31,22 +31,24 @@ var databank = require('databank'),
// Note: req.user != req.remoteUser
var reqUser = function(req, res, next) {
+ var user;
Step(
function() {
User.get(req.params.nickname, this);
},
- function(err, user) {
+ function(err, results) {
if (err) throw err;
+ user = results;
user.sanitize();
req.user = user;
user.expand(this);
},
- function(err, user) {
+ function(err) {
if (err) {
next(err);
} else {
- req.person = user.person;
+ req.person = user.profile;
next();
}
}
|
User.expand() doesn't return anything
|
pump-io_pump.io
|
train
|
59e003628eb7dc9762117caf03c101384d80a037
|
diff --git a/lib/ydocx/document.rb b/lib/ydocx/document.rb
index <HASH>..<HASH> 100644
--- a/lib/ydocx/document.rb
+++ b/lib/ydocx/document.rb
@@ -2,7 +2,7 @@
# encoding: utf-8
require 'pathname'
-require 'zip/zip'
+require 'zip'
begin
require 'RMagick'
rescue LoadError
@@ -83,7 +83,7 @@ module YDocx
def create_files
files_dir = output_directory
mkdir Pathname.new(files_dir) unless files_dir.exist?
- @zip = Zip::ZipFile.open(@path.realpath)
+ @zip = Zip::File.open(@path.realpath)
@images.each do |image|
origin_path = Pathname.new image[:origin] # media/filename.ext
source_path = Pathname.new image[:source] # images/filename.ext
@@ -118,7 +118,7 @@ module YDocx
end
def read(file)
@path = Pathname.new file
- @zip = Zip::ZipFile.open(@path.realpath)
+ @zip = Zip::File.open(@path.realpath)
doc = @zip.find_entry('word/document.xml').get_input_stream
rel = @zip.find_entry('word/_rels/document.xml.rels').get_input_stream
@parser = Parser.new(doc, rel) do |parser|
|
Updated to rubyzip >= <I>
|
zdavatz_ydocx
|
train
|
285bcce3de90f2e5474978d0bbb5fa4485b957f3
|
diff --git a/mpd.py b/mpd.py
index <HASH>..<HASH> 100644
--- a/mpd.py
+++ b/mpd.py
@@ -275,6 +275,7 @@ class MPDClient(object):
line = self._rfile.readline()
if not line.endswith("\n"):
raise ConnectionError, "Connection lost while reading MPD hello"
+ line = line.rstrip("\n")
if not line.startswith(HELLO_PREFIX):
raise ProtocolError, "Got invalid MPD hello: '%s'" % line
self.mpd_version = line[len(HELLO_PREFIX):].strip()
|
mpd.py: strip trailing \n from MPD's hello line for a nicer error message
|
Mic92_python-mpd2
|
train
|
23ee306e7133cafe5cc1efcd6d9d9a7e3b7f4011
|
diff --git a/src/NSwag.Npm/bin/nswag.js b/src/NSwag.Npm/bin/nswag.js
index <HASH>..<HASH> 100644
--- a/src/NSwag.Npm/bin/nswag.js
+++ b/src/NSwag.Npm/bin/nswag.js
@@ -33,7 +33,7 @@ if (process.env["windir"]) {
}
var c = require('child_process');
-if (hasFullDotNet && args.toLowerCase().indexOf("/runtime:Win") != -1) {
+if (hasFullDotNet && args.toLowerCase().indexOf("/runtime:win") != -1) {
// Run full .NET version
if (args.toLowerCase().indexOf("/runtime:winx86") != -1) {
var cmd = '"' + __dirname + '/binaries/Win/nswag.x86.exe" ' + args;
|
Fix casing in npm, closes #<I>
|
RicoSuter_NSwag
|
train
|
cf8ca234253087ca2009e06e344742ab8f2a94e0
|
diff --git a/lib/redfish/definition.rb b/lib/redfish/definition.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish/definition.rb
+++ b/lib/redfish/definition.rb
@@ -78,6 +78,18 @@ module Redfish
attr_writer :echo
+ attr_writer :rake_integration
+
+ def enable_rake_integration?
+ @rake_integration.nil? ? true : @rake_integration
+ end
+
+ attr_writer :packaged
+
+ def packaged?
+ @packaged.nil? ? false : @packaged
+ end
+
def to_task_context(executor = Redfish::Executor.new)
Redfish::Context.new(executor,
self.glassfish_home,
diff --git a/test/test_definition.rb b/test/test_definition.rb
index <HASH>..<HASH> 100644
--- a/test/test_definition.rb
+++ b/test/test_definition.rb
@@ -34,6 +34,8 @@ class Redfish::TestDefinition < Redfish::TestCase
assert_equal definition.system_group, nil
assert_equal definition.terse?, false
assert_equal definition.echo?, false
+ assert_equal definition.enable_rake_integration?, true
+ assert_equal definition.packaged?, false
definition.secure = false
definition.admin_port = 8080
@@ -46,6 +48,8 @@ class Redfish::TestDefinition < Redfish::TestCase
definition.system_group = 'glassfish-group'
definition.terse = true
definition.echo = true
+ definition.rake_integration = false
+ definition.packaged = true
assert_equal definition.secure?, false
assert_equal definition.admin_port, 8080
@@ -58,6 +62,8 @@ class Redfish::TestDefinition < Redfish::TestCase
assert_equal definition.system_group, 'glassfish-group'
assert_equal definition.terse?, true
assert_equal definition.echo?, true
+ assert_equal definition.enable_rake_integration?, false
+ assert_equal definition.packaged?, true
context = definition.to_task_context
|
Support attributes for indicating whether definition is packaged and should be integrated with rake
|
realityforge_redfish
|
train
|
63c8f436e2e6350cd591dd3cd071b54c27a62f21
|
diff --git a/abydos/util/_data.py b/abydos/util/_data.py
index <HASH>..<HASH> 100644
--- a/abydos/util/_data.py
+++ b/abydos/util/_data.py
@@ -145,9 +145,10 @@ def list_available_packages(url=None):
if url is None:
url = INDEX_URL
- if url[:4] == 'http':
- with urllib.urlopen(url) as ix: # noqa: S310
- xml = ElementTree.fromstring(ix.read()) # noqa: S314
+ if url[:8] != 'https://':
+ raise ValueError('url should begin with "https://"')
+ with urllib.urlopen(url) as ix: # noqa: S310
+ xml = ElementTree.fromstring(ix.read()) # noqa: S314
packages = [
(
@@ -234,7 +235,7 @@ def download_package(
if not force:
for inst in installed: # pragma: no branch
if pack[0] == inst[0] and pack[2] <= inst[2]:
- if not silent: # pragma: no branch
+ if not silent:
print( # pragma: no cover # noqa: T001
'{} package already up-to-date'.format(
pack[1]
diff --git a/tests/util/test_data.py b/tests/util/test_data.py
index <HASH>..<HASH> 100644
--- a/tests/util/test_data.py
+++ b/tests/util/test_data.py
@@ -63,8 +63,11 @@ class DataTestCases(unittest.TestCase):
temppath = tempfile.mkdtemp()
download_package('wikitext_qgram', data_path=temppath, force=True)
+ download_package('wikitext_qgram', data_path=temppath)
shutil.rmtree(temppath)
+ with self.assertRaises(ValueError):
+ list_available_packages(url='file:///etc/passwd')
if __name__ == '__main__':
unittest.main()
|
tests to complete coverage; added exception for non-https URLs
|
chrislit_abydos
|
train
|
13ee901242c41e5e8194b9aac457cd0e1bfdb819
|
diff --git a/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingEvaluator.java b/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingEvaluator.java
index <HASH>..<HASH> 100644
--- a/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingEvaluator.java
+++ b/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingEvaluator.java
@@ -756,7 +756,7 @@ public class DefaultUrlMappingEvaluator implements UrlMappingEvaluator, ClassLoa
if (includes.contains(ACTION_EDIT)) {
// GET /$controller/edit -> action:'edit'
- UrlMapping editUrlMapping = createEditctionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, constraintArray);
+ UrlMapping editUrlMapping = createEditActionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, constraintArray);
configureUrlMapping(editUrlMapping);
}
@@ -777,26 +777,26 @@ public class DefaultUrlMappingEvaluator implements UrlMappingEvaluator, ClassLoa
UrlMappingData deleteUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> deleteUrlMappingConstraints = createFormatOnlyConstraints(constrainedPropertyList);
- return new RegexUrlMapping(deleteUrlMappingData,controllerName, ACTION_DELETE, null, pluginName, null, HttpMethod.DELETE.toString(), version, deleteUrlMappingConstraints.toArray(new ConstrainedProperty[deleteUrlMappingConstraints.size()]) , servletContext);
+ return new RegexUrlMapping(deleteUrlMappingData,controllerName, ACTION_DELETE, namespace, pluginName, null, HttpMethod.DELETE.toString(), version, deleteUrlMappingConstraints.toArray(new ConstrainedProperty[deleteUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createUpdateActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> constrainedPropertyList) {
UrlMappingData updateUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> updateUrlMappingConstraints = createFormatOnlyConstraints(constrainedPropertyList);
- return new RegexUrlMapping(updateUrlMappingData,controllerName, ACTION_UPDATE, null, pluginName, null, HttpMethod.PUT.toString(),version, updateUrlMappingConstraints.toArray(new ConstrainedProperty[updateUrlMappingConstraints.size()]) , servletContext);
+ return new RegexUrlMapping(updateUrlMappingData,controllerName, ACTION_UPDATE, namespace, pluginName, null, HttpMethod.PUT.toString(),version, updateUrlMappingConstraints.toArray(new ConstrainedProperty[updateUrlMappingConstraints.size()]) , servletContext);
}
- protected UrlMapping createEditctionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, ConstrainedProperty[] constraintArray) {
+ protected UrlMapping createEditActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, ConstrainedProperty[] constraintArray) {
UrlMappingData editMappingData = urlData.createRelative("/edit");
- return new RegexUrlMapping(editMappingData,controllerName,ACTION_EDIT, null, pluginName, null, HttpMethod.GET.toString(),version, constraintArray, servletContext);
+ return new RegexUrlMapping(editMappingData,controllerName,ACTION_EDIT, namespace, pluginName, null, HttpMethod.GET.toString(),version, constraintArray, servletContext);
}
protected UrlMapping createShowActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> constrainedPropertyList) {
UrlMappingData showUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> showUrlMappingConstraints = createFormatOnlyConstraints(constrainedPropertyList);
- return new RegexUrlMapping(showUrlMappingData,controllerName, ACTION_SHOW,null, pluginName, null, HttpMethod.GET.toString(), version, showUrlMappingConstraints.toArray(new ConstrainedProperty[showUrlMappingConstraints.size()]) , servletContext);
+ return new RegexUrlMapping(showUrlMappingData,controllerName, ACTION_SHOW, namespace, pluginName, null, HttpMethod.GET.toString(), version, showUrlMappingConstraints.toArray(new ConstrainedProperty[showUrlMappingConstraints.size()]) , servletContext);
}
@SuppressWarnings("unchecked")
|
GRAILS-<I> - missing namespaces in mappings for singular RESTful resource corrected, typo in method name corrected
|
grails_grails-core
|
train
|
05f313ca2ddad91f4f1e789ef36b3282e6725bc1
|
diff --git a/README.rst b/README.rst
index <HASH>..<HASH> 100644
--- a/README.rst
+++ b/README.rst
@@ -160,6 +160,12 @@ Note that the "smart" behavior takes place only when there is ambiguity, i.e.
if there exists a variable with the same name as a command: in all other
cases, everything works as usual.
+Regarding the ``list`` command itself, using ``list(…`` is a special case
+that gets handled as the Python builtin::
+
+ (Pdb++) list([1, 2])
+ [1, 2]
+
Additional functions in the ``pdb`` module
------------------------------------------
diff --git a/pdb.py b/pdb.py
index <HASH>..<HASH> 100644
--- a/pdb.py
+++ b/pdb.py
@@ -397,6 +397,10 @@ class Pdb(pdb.Pdb, ConfigurableClass):
arg.startswith('=')):
line = '!' + line
return pdb.Pdb.parseline(self, line)
+ if cmd == "list" and arg.startswith("("):
+ # heuristic: handle "list(..." as the builtin.
+ line = '!' + line
+ return pdb.Pdb.parseline(self, line)
return cmd, arg, newline
def do_inspect(self, arg):
diff --git a/testing/test_pdb.py b/testing/test_pdb.py
index <HASH>..<HASH> 100644
--- a/testing/test_pdb.py
+++ b/testing/test_pdb.py
@@ -556,6 +556,27 @@ NUM \t 5 frames hidden .*
""".format(line_num=fn.__code__.co_firstlineno))
+def test_shortlist_heuristic():
+ def fn():
+ a = 1
+ set_trace(Config=ConfigTest)
+ return a
+
+ check(fn, """
+[NUM] > .*fn()
+-> return a
+ 5 frames hidden .*
+# list {line_num}, 3
+NUM \t def fn():
+NUM \t a = 1
+NUM \t set_trace(Config=ConfigTest)
+NUM -> return a
+# list(range(4))
+[0, 1, 2, 3]
+# c
+""".format(line_num=fn.__code__.co_firstlineno))
+
+
def test_longlist():
def fn():
a = 1
|
Add heuristic for which 'list' is meant (#<I>)
`list(...` is the builtin, otherwise it's the pdb cmd.
|
antocuni_pdb
|
train
|
46abe8cbf23e0562e00415f0b327b3875dde50b0
|
diff --git a/storage/remote/client.go b/storage/remote/client.go
index <HASH>..<HASH> 100644
--- a/storage/remote/client.go
+++ b/storage/remote/client.go
@@ -14,6 +14,7 @@
package remote
import (
+ "bufio"
"bytes"
"fmt"
"io/ioutil"
@@ -117,7 +118,12 @@ func (c *Client) Store(samples model.Samples) error {
defer httpResp.Body.Close()
if httpResp.StatusCode/100 != 2 {
- err = fmt.Errorf("server returned HTTP status %s", httpResp.Status)
+ scanner := bufio.NewScanner(httpResp.Body)
+ line := ""
+ if scanner.Scan() {
+ line = scanner.Text()
+ }
+ err = fmt.Errorf("server returned HTTP status %s: %s", httpResp.Status, line)
}
if httpResp.StatusCode/100 == 5 {
return recoverableError{err}
diff --git a/storage/remote/client_test.go b/storage/remote/client_test.go
index <HASH>..<HASH> 100644
--- a/storage/remote/client_test.go
+++ b/storage/remote/client_test.go
@@ -37,15 +37,15 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
},
{
code: 300,
- err: fmt.Errorf("server returned HTTP status 300 Multiple Choices"),
+ err: fmt.Errorf("server returned HTTP status 300 Multiple Choices: test error"),
},
{
code: 404,
- err: fmt.Errorf("server returned HTTP status 404 Not Found"),
+ err: fmt.Errorf("server returned HTTP status 404 Not Found: test error"),
},
{
code: 500,
- err: recoverableError{fmt.Errorf("server returned HTTP status 500 Internal Server Error")},
+ err: recoverableError{fmt.Errorf("server returned HTTP status 500 Internal Server Error: test error")},
},
}
@@ -68,7 +68,7 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
err = c.Store(nil)
if !reflect.DeepEqual(err, test.err) {
- t.Fatalf("%d. Unexpected error; want %v, got %v", i, test.err, err)
+ t.Errorf("%d. Unexpected error; want %v, got %v", i, test.err, err)
}
server.Close()
|
Remote write: read first line of response and include it in the error.
|
prometheus_prometheus
|
train
|
11909b9519ba84cc726f02e92c9508af7a4c1ff6
|
diff --git a/h2o-extensions/xgboost/src/test/java/hex/tree/xgboost/XGBoostTest.java b/h2o-extensions/xgboost/src/test/java/hex/tree/xgboost/XGBoostTest.java
index <HASH>..<HASH> 100755
--- a/h2o-extensions/xgboost/src/test/java/hex/tree/xgboost/XGBoostTest.java
+++ b/h2o-extensions/xgboost/src/test/java/hex/tree/xgboost/XGBoostTest.java
@@ -56,7 +56,7 @@ public class XGBoostTest extends TestUtil {
@Before
public void setupMojoJavaScoring() {
System.setProperty("sys.ai.h2o.xgboost.scoring.java.enable", confMojoJavaScoring); // mojo scoring
- System.setProperty("sys.ai.h2o.xgboost.predict.java.enable", confMojoJavaScoring); // in-h2o predict
+ System.setProperty("sys.ai.h2o.xgboost.predict.java.enable", confJavaPredict); // in-h2o predict
}
public static final class FrameMetadata {
|
Fix typo - we were not testing all combinations of mojo & in-h2o predict
|
h2oai_h2o-3
|
train
|
8b5d3b1442ecca6b3525c836685c84257cc5d548
|
diff --git a/cdm/src/main/java/ucar/nc2/dt/radial/LevelII2Dataset.java b/cdm/src/main/java/ucar/nc2/dt/radial/LevelII2Dataset.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/dt/radial/LevelII2Dataset.java
+++ b/cdm/src/main/java/ucar/nc2/dt/radial/LevelII2Dataset.java
@@ -27,7 +27,7 @@ import ucar.nc2.units.DateUnit;
import ucar.nc2.units.SimpleUnit;
import ucar.nc2.units.DateFormatter;
import ucar.ma2.*;
-
+import ucar.nc2.Attribute;
import java.io.IOException;
import java.util.List;
import java.util.Date;
@@ -51,7 +51,7 @@ public class LevelII2Dataset extends RadialDatasetSweepAdapter implements TypedD
String convention = ds.findAttValueIgnoreCase(null, "Conventions", null);
if ((null != convention) && convention.equals(_Coordinate.Convention)) {
String format = ds.findAttValueIgnoreCase(null, "Format", null);
- if (format.equals("ARCHIVE2") || format.equals("AR2V0001"))
+ if (format.equals("ARCHIVE2") || format.equals("AR2V0001") || format.equals("CINRAD-SA"))
return true;
}
return false;
@@ -81,9 +81,23 @@ public class LevelII2Dataset extends RadialDatasetSweepAdapter implements TypedD
}
protected void setEarthLocation() {
- latv = ds.findGlobalAttribute("StationLatitude").getNumericValue().doubleValue();
- lonv = ds.findGlobalAttribute("StationLongitude").getNumericValue().doubleValue();
- elev = ds.findGlobalAttribute("StationElevationInMeters").getNumericValue().doubleValue();
+ Attribute ga = ds.findGlobalAttribute("StationLatitude");
+ if(ga != null )
+ latv = ga.getNumericValue().doubleValue();
+ else
+ latv = 0.0;
+
+ ga = ds.findGlobalAttribute("StationLongitude");
+ if(ga != null)
+ lonv = ga.getNumericValue().doubleValue();
+ else
+ lonv = 0.0;
+
+ ga = ds.findGlobalAttribute("StationElevationInMeters");
+ if(ga != null)
+ elev = ga.getNumericValue().doubleValue();
+ else
+ elev = 0.0;
origin = new EarthLocationImpl(latv, lonv, elev);
}
@@ -535,7 +549,7 @@ public class LevelII2Dataset extends RadialDatasetSweepAdapter implements TypedD
mele = sw.getMeanElevation();
//ucar.unidata.util.Trace.call2("LevelII2Dataset:testRadialVariable getSweep " + i);
float me = sw.getMeanElevation();
- //System.out.println("*** radar Sweep mean elevation of sweep " + i + " is: " + me);
+ System.out.println("*** radar Sweep mean elevation of sweep " + i + " is: " + me);
int nrays = sw.getRadialNumber();
float [] az = new float[nrays];
for (int j = 0; j < nrays; j++) {
@@ -574,7 +588,7 @@ public class LevelII2Dataset extends RadialDatasetSweepAdapter implements TypedD
public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException {
- String fileIn = "/home/yuanho/dorade/KATX_20040113_0107";
+ String fileIn = "/home/yuanho/dorade/CHGZ_2006071512.0300";
//RadialDatasetSweepFactory datasetFactory = new RadialDatasetSweepFactory();
//RadialDatasetSweep rds = datasetFactory.open(fileIn, null);
|
allow stationID to be null and station to be set at (0,0,0)
|
Unidata_thredds
|
train
|
14a792ed78b30026f8cc88d00382e859b20fb851
|
diff --git a/src/baguetteBox.js b/src/baguetteBox.js
index <HASH>..<HASH> 100644
--- a/src/baguetteBox.js
+++ b/src/baguetteBox.js
@@ -220,6 +220,7 @@ var baguetteBox = (function() {
for(var i = 0, fullImage; i < imagesMap[galleryIndex].length; i++) {
fullImage = create('div');
fullImage.className = 'full-image';
+ fullImage.id = 'baguette-img-' + i;
imagesElements.push(fullImage);
slider.appendChild(imagesElements[i]);
}
@@ -302,8 +303,8 @@ var baguetteBox = (function() {
// Set callback function when image loads
image.onload = function() {
// Remove loader element
- var spinner = this.parentNode.querySelector('.spinner');
- this.parentNode.removeChild(spinner);
+ var spinner = document.querySelector('#baguette-img-' + index + ' .spinner');
+ figure.removeChild(spinner);
if(!options.async && callback)
callback();
};
|
Fixed possible issue with loader not being removed in some cases in IE8
|
feimosi_baguetteBox.js
|
train
|
fbcadbb7b4b6a60ace7d9eab1a14ee5ad3294ea4
|
diff --git a/lxd/storage_volumes.go b/lxd/storage_volumes.go
index <HASH>..<HASH> 100644
--- a/lxd/storage_volumes.go
+++ b/lxd/storage_volumes.go
@@ -296,6 +296,11 @@ func storagePoolVolumesTypePost(d *Daemon, r *http.Request) response.Response {
return response.BadRequest(fmt.Errorf("Storage volume names may not contain slashes"))
}
+ // Backward compatibility.
+ if req.ContentType == "" {
+ req.ContentType = "filesystem"
+ }
+
_, err = storagePools.VolumeContentTypeNameToContentType(req.ContentType)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid content type %q", req.ContentType))
|
lxd/storage: Backward compatibility for content types
|
lxc_lxd
|
train
|
98e396101c7d256a6025828d285b7ce74feefa0e
|
diff --git a/src/main/shadow/boot/browser.js b/src/main/shadow/boot/browser.js
index <HASH>..<HASH> 100644
--- a/src/main/shadow/boot/browser.js
+++ b/src/main/shadow/boot/browser.js
@@ -113,7 +113,11 @@ var SHADOW_ENV = function() {
if (sourceMap) {
code += ("\n//# sourceMappingURL=" + path + ".map");
}
- goog.globalEval(code);
+ try {
+ goog.globalEval(code);
+ } catch (e) {
+ console.warn("failed to load", path, e);
+ }
}
return env;
diff --git a/src/main/shadow/boot/worker.js b/src/main/shadow/boot/worker.js
index <HASH>..<HASH> 100644
--- a/src/main/shadow/boot/worker.js
+++ b/src/main/shadow/boot/worker.js
@@ -27,7 +27,11 @@ var SHADOW_ENV = (function () {
if (sourceMap) {
code += ("\n//# sourceMappingURL=" + path + ".map");
}
- goog.globalEval(code);
+ try {
+ goog.globalEval(code);
+ } catch (e) {
+ console.warn("failed to load", path, e);
+ }
}
return env;
|
catch errors during evalLoad so it behaves like script tags
script tags continue loading the rest of the code even if one fails
|
thheller_shadow-cljs
|
train
|
6f1f0b9152cba865e8b419e7499bd043d3190d14
|
diff --git a/oleaster-runner/src/main/java/com/mscharhag/oleaster/runner/OleasterRunner.java b/oleaster-runner/src/main/java/com/mscharhag/oleaster/runner/OleasterRunner.java
index <HASH>..<HASH> 100644
--- a/oleaster-runner/src/main/java/com/mscharhag/oleaster/runner/OleasterRunner.java
+++ b/oleaster-runner/src/main/java/com/mscharhag/oleaster/runner/OleasterRunner.java
@@ -125,9 +125,7 @@ public class OleasterRunner extends ParentRunner<Spec> {
}
private void runAfterCallbacks(Spec spec) {
- List<Invokable> afterHandlers = this.collectInvokables(spec.getSuite(), Suite::getAfterHandlers);
- Collections.reverse(afterHandlers);
- this.runInvokables(afterHandlers);
+ this.runInvokables(this.collectInvokables(spec.getSuite(), Suite::getAfterHandlers));
}
|
Fixed order of after() callback executions (inner after() handlers are now executed before outer after() handlers)
|
mscharhag_oleaster
|
train
|
87a5fd79373c2be3238b8053a92a24e20a72a352
|
diff --git a/Twig/Extension.php b/Twig/Extension.php
index <HASH>..<HASH> 100644
--- a/Twig/Extension.php
+++ b/Twig/Extension.php
@@ -39,7 +39,7 @@ class Extension extends \Twig_Extension
}
public function timestampedController($controller, array $attributes=array(), array $query=array(), $updateTrackerName='global')
{
- $query['timestamp'] = $this->updateManager->getLastUpdate($updateTrackerName);
+ $query['timestamp'] = $this->updateManager->getLastUpdate($updateTrackerName)->format('U');
return new ControllerReference($controller, $attributes, $query);
}
}
|
Corrected bug in twig extension
|
antoineguigan_update-tracker-bundle
|
train
|
f53e2f9e65d29907603215fb1abb5ced31f2745d
|
diff --git a/lib/dicom.rb b/lib/dicom.rb
index <HASH>..<HASH> 100644
--- a/lib/dicom.rb
+++ b/lib/dicom.rb
@@ -2,46 +2,47 @@
#
# The following classes are meant to be used by users of Ruby DICOM:
# * DObject - for reading, manipulating and writing DICOM files.
-# * Element, Sequence, Item, Parent, Elemental - users who wish to interact with their DICOM objects will use these classes/modules.
+# * Element, Sequence, Item, Parent, Elemental - users who wish to interact with
+# their DICOM objects will use these classes/modules.
# * ImageItem - Image related methods are found in this class.
# * DClient - for client side network communication, like querying, moving & sending DICOM files.
# * DServer - for server side network communication: Setting up your own DICOM storage node (SCP).
# * Anonymizer - a convenience class for anonymizing your DICOM files.
#
-# The rest of the classes visible in the documentation generated by RDoc is in principle
-# 'private' classes, which are mainly of interest to developers.
+# The rest of the classes visible in the documentation generated by RDoc are
+# in principle 'private' classes, which are mainly of interest to developers.
# Logging:
-require 'dicom/logging'
+require_relative 'dicom/logging'
# Core library:
# Super classes/modules:
-require 'dicom/image_processor'
-require 'dicom/parent'
-require 'dicom/image_item'
-require 'dicom/elemental'
+require_relative 'dicom/image_processor'
+require_relative 'dicom/parent'
+require_relative 'dicom/image_item'
+require_relative 'dicom/elemental'
# Subclasses and independent classes:
-require 'dicom/d_client'
-require 'dicom/dictionary'
-require 'dicom/d_library'
-require 'dicom/d_object'
-require 'dicom/d_read'
-require 'dicom/d_server'
-require 'dicom/d_write'
-require 'dicom/element'
-require 'dicom/file_handler'
-require 'dicom/item'
-require 'dicom/link'
-require 'dicom/sequence'
-require 'dicom/stream'
+require_relative 'dicom/d_client'
+require_relative 'dicom/dictionary'
+require_relative 'dicom/d_library'
+require_relative 'dicom/d_object'
+require_relative 'dicom/d_read'
+require_relative 'dicom/d_server'
+require_relative 'dicom/d_write'
+require_relative 'dicom/element'
+require_relative 'dicom/file_handler'
+require_relative 'dicom/item'
+require_relative 'dicom/link'
+require_relative 'dicom/sequence'
+require_relative 'dicom/stream'
# Extensions to the Ruby library:
-require 'dicom/ruby_extensions'
+require_relative 'dicom/ruby_extensions'
# Module settings:
-require 'dicom/version'
-require 'dicom/constants'
-require 'dicom/variables'
+require_relative 'dicom/version'
+require_relative 'dicom/constants'
+require_relative 'dicom/variables'
# Image processors:
-require 'dicom/image_processor_mini_magick'
-require 'dicom/image_processor_r_magick'
+require_relative 'dicom/image_processor_mini_magick'
+require_relative 'dicom/image_processor_r_magick'
# Extensions (non-core functionality):
-require 'dicom/anonymizer'
+require_relative 'dicom/anonymizer'
|
Replace 'require' with 'require_relative'
As of Ruby <I>, require_relative is the preferred way of loading local
files.
|
dicom_ruby-dicom
|
train
|
6951db4a908e554c94c78ca91ffe8243237a274b
|
diff --git a/py3status/modules/xrandr.py b/py3status/modules/xrandr.py
index <HASH>..<HASH> 100644
--- a/py3status/modules/xrandr.py
+++ b/py3status/modules/xrandr.py
@@ -159,6 +159,7 @@ class Py3status:
self.active_layout = None
self.active_mode = 'extend'
self.displayed = None
+ self.initialized = False
self.max_width = 0
def _get_layout(self):
@@ -457,7 +458,7 @@ class Py3status:
response['color'] = self.py3.COLOR_BAD
# force default layout setup
- if self.force_on_start is not None:
+ if not self.initialized and self.force_on_start is not None:
sleep(1)
self._force_force_on_start()
@@ -467,6 +468,9 @@ class Py3status:
if self.fallback is True:
self._fallback_to_available_output()
+ # startup is done
+ self.initialized = True
+
return response
|
xrandr module: force_on_start is only meant for startup
|
ultrabug_py3status
|
train
|
cb79670d2ac5125fa3b6eb166e70b99f458afbc9
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -9,7 +9,8 @@ const fileUploadOptionsDefaults = {
safeFileNames: false,
preserveExtension: false,
abortOnLimit: false,
- createParentPath: false
+ createParentPath: false,
+ parseNested: false
};
/**
diff --git a/lib/processMultipart.js b/lib/processMultipart.js
index <HASH>..<HASH> 100644
--- a/lib/processMultipart.js
+++ b/lib/processMultipart.js
@@ -141,7 +141,10 @@ module.exports = function processMultipart(options, req, res, next) {
});
busboy.on('finish', () => {
- req.body = processNested(req.body);
+ if (options.parseNested) {
+ req.body = processNested(req.body);
+ req.files = processNested(req.files);
+ }
next();
});
|
Add parseNested option, disabled by default
|
richardgirges_express-fileupload
|
train
|
f841f3ab40d1d8245da793d60ab980cd9c9b3357
|
diff --git a/test/utils/tmpdir.go b/test/utils/tmpdir.go
index <HASH>..<HASH> 100644
--- a/test/utils/tmpdir.go
+++ b/test/utils/tmpdir.go
@@ -18,7 +18,6 @@ package utils
import (
"io/ioutil"
- "os"
"github.com/golang/glog"
)
@@ -31,8 +30,5 @@ func MakeTempDirOrDie(prefix string, baseDir string) string {
if err != nil {
glog.Fatalf("Can't make a temp rootdir: %v", err)
}
- if err = os.MkdirAll(tempDir, 0750); err != nil {
- glog.Fatalf("Can't mkdir(%q): %v", tempDir, err)
- }
return tempDir
}
|
Remove superfluous MkdirAll from MakeTempDirOrDie
After the call to ioutil.TempDir, the directory has already been
created, and MkdirAll therefore can't do anything. The mode argument
in particular is misleading.
|
kubernetes_kubernetes
|
train
|
00a1e7c89adadb4954a387037e56a59bb7c14b71
|
diff --git a/lib/common/common.go b/lib/common/common.go
index <HASH>..<HASH> 100644
--- a/lib/common/common.go
+++ b/lib/common/common.go
@@ -51,14 +51,14 @@ func ParseDockerURL(arg string) *types.ParsedDockerURL {
}
indexURL, imageName := SplitReposName(taglessRemote)
- if indexURL == "" && !strings.Contains(imageName, "/") {
+ // the Docker client considers images referenced only by a name (e.g.
+ // "busybox" or "ubuntu") as valid, and, in that case, it adds the
+ // "library/" prefix because that's how they're stored in the official
+ // registry
+ if indexURL == defaultIndexURL && !strings.Contains(imageName, "/") {
imageName = "library/" + imageName
}
- if indexURL == "" {
- indexURL = defaultIndexURL
- }
-
return &types.ParsedDockerURL{
IndexURL: indexURL,
ImageName: imageName,
diff --git a/lib/common/docker_functions.go b/lib/common/docker_functions.go
index <HASH>..<HASH> 100644
--- a/lib/common/docker_functions.go
+++ b/lib/common/docker_functions.go
@@ -38,9 +38,7 @@ func SplitReposName(reposName string) (string, string) {
if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
!strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
- // The URL for the index is different depending on the version of the
- // API used to fetch it, so it cannot be inferred here.
- indexName = ""
+ indexName = defaultIndexURL
remoteName = reposName
} else {
indexName = nameParts[0]
|
lib/common: infer default docker registry
If the Docker reference does not include any servers, we assume it's a
using the default Docker registry.
Since the Docker API v1 was deprecated in the default registry, we can
now infer the default docker registry name (registry-1.docker.io).
|
appc_docker2aci
|
train
|
fc11a70b5c9cfa90d74863405e1aec619399c032
|
diff --git a/imgaug/augmenters/meta.py b/imgaug/augmenters/meta.py
index <HASH>..<HASH> 100644
--- a/imgaug/augmenters/meta.py
+++ b/imgaug/augmenters/meta.py
@@ -1283,10 +1283,17 @@ class Augmenter(object): # pylint: disable=locally-disabled, unused-variable, l
This function is useful, when augmentations are run in the
background (i.e. on multiple cores).
It should be called before sending this Augmenter object to a
- background worker (i.e., if ``N`` workers are used, the function
- should be called ``N`` times). Otherwise, all background workers will
+ background worker or once within each worker with different seeds
+ (i.e., if ``N`` workers are used, the function should be called
+ ``N`` times). Otherwise, all background workers will
use the same seeds and therefore apply the same augmentations.
+ If this augmenter or any child augmenter had a random state that
+ pointed to the global random state, it will automatically be
+ replaced with a local random state. This is similar to what
+ :func:`imgaug.augmenters.meta.Augmenter.localize_random_state`
+ does.
+
Parameters
----------
random_state : None or int or numpy.random.RandomState, optional
|
Improve doc of reseed()
|
aleju_imgaug
|
train
|
ca93914177ca644ba868d911e29539d9978b6a73
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -346,7 +346,15 @@ MarkerLabel_.prototype.setContent = function () {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
} else {
- this.labelDiv_.innerHTML = ""; // Remove current content
+ // Remove current content
+ while (this.labelDiv_.lastChild) {
+ this.labelDiv_.removeChild(this.labelDiv_.lastChild);
+ }
+
+ while (this.eventDiv_.lastChild) {
+ this.eventDiv_.removeChild(this.eventDiv_.lastChild);
+ }
+
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.eventDiv_.appendChild(content);
|
Remove all child-nodes when re-rendering label
Fixes #2
|
jesstelford_node-MarkerWithLabel
|
train
|
e18d7d2fe8a26866d047efe73ad231481b7f8f63
|
diff --git a/lib/form/yui/dateselector/dateselector.js b/lib/form/yui/dateselector/dateselector.js
index <HASH>..<HASH> 100644
--- a/lib/form/yui/dateselector/dateselector.js
+++ b/lib/form/yui/dateselector/dateselector.js
@@ -44,36 +44,6 @@ YUI.add('moodle-form-dateselector', function(Y) {
});
/**
- * Override the default inDoc method as it is broken in IE
- *
- * YUI Bug: http://yuilibrary.com/projects/yui3/ticket/2529157
- * Example location: lib/yui/3.1.1/build/dom/dom-debug.js
- *
- * Moodle tracker issue to clean this up when required:
- * http://tracker.moodle.org/browse/MDL-23829
- */
- Y.DOM.inDoc = function(element, doc) {
- // there may be multiple elements with the same ID
- doc = doc || element['ownerDocument'];
- var nodes = [],
- ret = false,
- i,
- node;
-
- if (!element.getAttribute('id')) {
- element.setAttribute('id', Y.guid());
- }
- nodes = Y.DOM.allById(element.id, doc);
- for (i = 0; node = nodes[i++];) { // check for a match
- if (node === element) {
- ret = true;
- break;
- }
- }
- return ret;
- };
-
- /**
* Calendar class
*
* This is our main class
@@ -104,6 +74,7 @@ YUI.add('moodle-form-dateselector', function(Y) {
node.on('blur', this.blur_event, this);
return;
}
+ node.on('focus', this.focus_event, this);
node.on('click', this.focus_event, this);
node.after('change', this.set_date_from_selects, this);
}, this);
|
mform-dateselector MDL-<I> Removed patch to fix YUI issue that was fixed in <I>
|
moodle_moodle
|
train
|
33f90526bd383a4ffc98b0d2799bfefa1558caf7
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,7 +16,6 @@ setup(
test_suite='nose.collector',
tests_require=[
'aiohttp',
- 'grpcio',
'nose'
],
install_requires=[
|
Remove 'grpcio' requirement for tests
|
biosustain_venom
|
train
|
253534f5fcf2a2b89831b88d0f45bf00bd9fb97d
|
diff --git a/cirq-core/cirq/circuits/circuit.py b/cirq-core/cirq/circuits/circuit.py
index <HASH>..<HASH> 100644
--- a/cirq-core/cirq/circuits/circuit.py
+++ b/cirq-core/cirq/circuits/circuit.py
@@ -2083,7 +2083,7 @@ class Circuit(AbstractCircuit):
"""
# limit index to 0..len(self._moments), also deal with indices smaller 0
k = max(min(index if index >= 0 else len(self._moments) + index, len(self._moments)), 0)
- for moment_or_op in ops.flatten_to_ops_or_moments(moment_or_operation_tree):
+ for moment_or_op in list(ops.flatten_to_ops_or_moments(moment_or_operation_tree)):
if isinstance(moment_or_op, Moment):
self._moments.insert(k, moment_or_op)
k += 1
diff --git a/cirq-core/cirq/circuits/circuit_test.py b/cirq-core/cirq/circuits/circuit_test.py
index <HASH>..<HASH> 100644
--- a/cirq-core/cirq/circuits/circuit_test.py
+++ b/cirq-core/cirq/circuits/circuit_test.py
@@ -187,6 +187,12 @@ def test_append_single():
c.append([cirq.X(a)])
assert c == cirq.Circuit([cirq.Moment([cirq.X(a)])])
+ c = cirq.Circuit(cirq.H(a))
+ c.append(c)
+ assert c == cirq.Circuit(
+ [cirq.Moment(cirq.H(cirq.NamedQubit('a'))), cirq.Moment(cirq.H(cirq.NamedQubit('a')))]
+ )
+
def test_append_control_key():
q0, q1, q2 = cirq.LineQubit.range(3)
|
Convert iterator to list to list before looping through moments r ops in insert (#<I>)
|
quantumlib_Cirq
|
train
|
e9c5d4c2ba5dc4aff2a10878430f11664ed1f54d
|
diff --git a/suds/__init__.py b/suds/__init__.py
index <HASH>..<HASH> 100644
--- a/suds/__init__.py
+++ b/suds/__init__.py
@@ -29,7 +29,7 @@ import sys
#
__version__ = '0.3.8'
-__build__="(beta) R608-20091125"
+__build__="(beta) R610-20091201"
#
# Exceptions
diff --git a/suds/sax/attribute.py b/suds/sax/attribute.py
index <HASH>..<HASH> 100644
--- a/suds/sax/attribute.py
+++ b/suds/sax/attribute.py
@@ -80,16 +80,13 @@ class Attribute:
@return: self
@rtype: L{Attribute}
"""
- if value is None:
- self.value = None
- return self
if isinstance(value, Text):
- self.value = value.escape()
+ self.value = value
else:
- self.value = Text(value).escape()
+ self.value = Text(value)
return self
- def getValue(self, default=''):
+ def getValue(self, default=Text('')):
"""
Get the attributes value with optional default.
@param default: An optional value to be return when the
@@ -99,7 +96,7 @@ class Attribute:
@rtype: L{Text}
"""
if self.hasText():
- return self.value.unescape()
+ return self.value
else:
return default
@@ -176,7 +173,12 @@ class Attribute:
def __unicode__(self):
""" get an xml string representation """
- return u'%s="%s"' % (self.qname(), self.value)
+ n = self.qname()
+ if self.hasText():
+ v = self.value.escape()
+ else:
+ v = self.value
+ return u'%s="%s"' % (n, v)
def __getstate__(self):
state = self.__dict__.copy()
diff --git a/suds/sax/element.py b/suds/sax/element.py
index <HASH>..<HASH> 100644
--- a/suds/sax/element.py
+++ b/suds/sax/element.py
@@ -245,13 +245,10 @@ class Element:
@return: self
@rtype: I{Element}
"""
- if value is None:
- self.text = None
- return self
if isinstance(value, Text):
- self.text = value.escape()
+ self.text = value
else:
- self.text = Text(value).escape()
+ self.text = Text(value)
return self
def getText(self, default=None):
@@ -263,7 +260,7 @@ class Element:
@rtype: L{Text}
"""
if self.hasText():
- return self.text.unescape()
+ return self.text
else:
return default
@@ -760,8 +757,8 @@ class Element:
result.append('/>')
return ''.join(result)
result.append('>')
- if self.text is not None:
- result.append(self.text)
+ if self.hasText():
+ result.append(self.text.escape())
for c in self.children:
result.append('\n')
result.append(c.str(indent+1))
diff --git a/suds/sax/text.py b/suds/sax/text.py
index <HASH>..<HASH> 100644
--- a/suds/sax/text.py
+++ b/suds/sax/text.py
@@ -56,7 +56,7 @@ class Text(unicode):
if not self.escaped:
post = sax.encoder.encode(self)
escaped = ( post != self )
- return Text(post, escaped=escaped)
+ return Text(post, lang=self.lang, escaped=escaped)
return self
def unescape(self):
@@ -66,9 +66,14 @@ class Text(unicode):
@rtype: L{Text}
"""
if self.escaped:
- return sax.encoder.decode(self)
+ post = sax.encoder.decode(self)
+ return Text(post, lang=self.lang)
return self
+ def trim(self):
+ post = self.strip()
+ return Text(post, lang=self.lang, escaped=self.escaped)
+
def __add__(self, other):
joined = u''.join((self, other))
result = Text(joined, lang=self.lang, escaped=self.escaped)
@@ -84,9 +89,6 @@ class Text(unicode):
s.append(' <escaped>')
return ''.join(s)
- def trim(self):
- return Text(self.strip(), escaped=self.escaped)
-
class Raw(Text):
"""
diff --git a/tests/public.py b/tests/public.py
index <HASH>..<HASH> 100644
--- a/tests/public.py
+++ b/tests/public.py
@@ -67,6 +67,9 @@ try:
result = client.service.echoIntegerArray(input)
print 'echoIntegerArray() = %s' % result
assert result == input
+ result = client.service.echoIntegerArray(inputIntegerArray=input)
+ print 'echoIntegerArray() = %s' % result
+ assert result == input
except WebFault, f:
errors += 1
print f
|
Fix sax special character encoding (escaping). Needed to be simpler and got broken duing Text() object refactoring. Simpler approach to only escape special characters when rendering a text (string) representation of the DOM tree.
|
suds-community_suds
|
train
|
e381dba8f9018958b11722b7a3adef4b6153fdb4
|
diff --git a/src/Google/Service/YouTubeAnalytics.php b/src/Google/Service/YouTubeAnalytics.php
index <HASH>..<HASH> 100644
--- a/src/Google/Service/YouTubeAnalytics.php
+++ b/src/Google/Service/YouTubeAnalytics.php
@@ -262,6 +262,10 @@ class Google_Service_YouTubeAnalytics extends Google_Service
'location' => 'query',
'type' => 'integer',
),
+ 'currency' => array(
+ 'location' => 'query',
+ 'type' => 'string',
+ ),
'filters' => array(
'location' => 'query',
'type' => 'string',
@@ -598,6 +602,10 @@ class Google_Service_YouTubeAnalytics_Reports_Resource extends Google_Service_Re
* @opt_param int start-index An index of the first entity to retrieve. Use this
* parameter as a pagination mechanism along with the max-results parameter
* (one-based, inclusive).
+ * @opt_param string currency The currency to which financial metrics should be
+ * converted. The default is US Dollar (USD). If the result contains no
+ * financial metrics, this flag will be ignored. Responds with an error if the
+ * specified currency is not recognized.
* @opt_param string filters A list of filters that should be applied when
* retrieving YouTube Analytics data. The Available Reports document identifies
* the dimensions that can be used to filter each report, and the Dimensions
|
Updated YouTubeAnalytics.php
This change has been generated by a script that has detected changes in the
discovery doc of the API.
Check <URL>
|
googleapis_google-api-php-client
|
train
|
81d3bf060edfa3da7d52798fcb0d51bb4c83cb0d
|
diff --git a/tests/suites/unit/joomla/application/web/JApplicationWebClientTest.php b/tests/suites/unit/joomla/application/web/JApplicationWebClientTest.php
index <HASH>..<HASH> 100644
--- a/tests/suites/unit/joomla/application/web/JApplicationWebClientTest.php
+++ b/tests/suites/unit/joomla/application/web/JApplicationWebClientTest.php
@@ -54,6 +54,8 @@ class JApplicationWebClientTest extends PHPUnit_Framework_TestCase
array(JApplicationWebClient::ANDROID, true, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '4', 'Mozilla/5.0 (Linux; U; Android 2.2.1; en-ca; LG-P505R Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'),
array(JApplicationWebClient::IPAD, true, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '4.0.4', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10gin_lib.cc'),
array(JApplicationWebClient::IPHONE, true, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '4.0.5', 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7'),
+ array(JApplicationWebClient::IPAD, true, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '4.0.4', 'Mozilla/5.0(iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10gin_lib.cc'),
+ array(JApplicationWebClient::IPOD, true, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '4.0.4', 'Mozilla/5.0(iPod; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10gin_lib.cc'),
array(JApplicationWebClient::WINDOWS, false, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '5.0.4', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'),
array(JApplicationWebClient::MAC, false, JApplicationWebClient::WEBKIT, JApplicationWebClient::SAFARI, '5.0.3', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; ar) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4'),
array(JApplicationWebClient::WINDOWS, false, JApplicationWebClient::GECKO, JApplicationWebClient::FIREFOX, '3.6.9', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9 ( .NET CLR 3.5.30729; .NET CLR 4.0.20506)'),
|
Changed tests/suites/unit/joomla/application/web/JApplicationWebClientTest.php by adding iPod,iPad to array
|
joomla_joomla-framework
|
train
|
def4d62ddb05c0b7ae513a4d9d3a1051c0df0b6e
|
diff --git a/source/com/maxmind/geoip/LookupService.java b/source/com/maxmind/geoip/LookupService.java
index <HASH>..<HASH> 100644
--- a/source/com/maxmind/geoip/LookupService.java
+++ b/source/com/maxmind/geoip/LookupService.java
@@ -338,7 +338,7 @@ public class LookupService {
file.seek(file.getFilePointer() - 4);
}
}
- if ((databaseType == DatabaseInfo.COUNTRY_EDITION) |
+ if ((databaseType == DatabaseInfo.COUNTRY_EDITION) |
(databaseType == DatabaseInfo.PROXY_EDITION) |
(databaseType == DatabaseInfo.NETSPEED_EDITION)) {
databaseSegments = new int[1];
@@ -349,7 +349,9 @@ public class LookupService {
int l = (int) file.length();
dbbuffer = new byte[l];
file.seek(0);
- file.read(dbbuffer,0,l);
+ file.read(dbbuffer,0,l);
+ databaseInfo = this.getDatabaseInfo();
+ file.close();
}
}
@@ -358,7 +360,9 @@ public class LookupService {
*/
public void close() {
try {
- file.close();
+ if (file != null){
+ file.close();
+ }
file = null;
}
catch (Exception e) { }
|
close filehandle after data is read into memory for MemoryCache mode
|
maxmind_geoip-api-java
|
train
|
85bb5ebf7e1207a1bdcd01b0a41fd095f38e85d1
|
diff --git a/lib/puppet/network/http/handler.rb b/lib/puppet/network/http/handler.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/network/http/handler.rb
+++ b/lib/puppet/network/http/handler.rb
@@ -16,7 +16,7 @@ module Puppet::Network::HTTP::Handler
attr_reader :server, :handler
- YAML_DEPRECATION = "YAML in network requests is deprecated and will be removed in a future version"
+ YAML_DEPRECATION = "YAML in network requests is deprecated and will be removed in a future version. See http://links.puppetlabs.com/deprecate_yaml_on_network"
# Retrieve all headers from the http request, as a hash with the header names
# (lower-cased) as the keys
@@ -270,6 +270,7 @@ module Puppet::Network::HTTP::Handler
next result if param == :ip
value = CGI.unescape(value)
if value =~ /^---/
+ Puppet.debug("Found YAML while processing request parameter #{param} (value: <#{value}>)")
Puppet.deprecation_warning(YAML_DEPRECATION)
value = YAML.load(value, :safe => true, :deserialize_symbols => true)
else
|
(#<I>) Improve deprecation warning for yaml params
Previously we were not informed what parameter and value was being
transmitted as YAML, which made debugging and correcting the problem
nearly impossible. This outputs the offending request parameter and
value as a debug message to aid in fixing the issue.
|
puppetlabs_puppet
|
train
|
f46fac96870414ab415d0aad368da65f8566e977
|
diff --git a/spec/adhearsion/router/route_spec.rb b/spec/adhearsion/router/route_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/adhearsion/router/route_spec.rb
+++ b/spec/adhearsion/router/route_spec.rb
@@ -49,18 +49,27 @@ module Adhearsion
]
end
+ let :offer do
+ Punchblock::Event::Offer.new :to => to, :from => from
+ end
+
+ let(:call) { Adhearsion::Call.new offer }
+
context "with a call from fred to paul" do
- let(:call) { flexmock 'Adhearsion::Call', :from => 'fred', :to => 'paul' }
+ let(:from) { 'fred' }
+ let(:to) { 'paul' }
it { should_match_the_call }
end
context "with a call from fred to frank" do
- let(:call) { flexmock 'Adhearsion::Call', :from => 'fred', :to => 'frank' }
+ let(:from) { 'fred' }
+ let(:to) { 'frank' }
it { should_not_match_the_call }
end
context "with a call from frank to paul" do
- let(:call) { flexmock 'Adhearsion::Call', :from => 'frank', :to => 'paul' }
+ let(:from) { 'frank' }
+ let(:to) { 'paul' }
it { should_not_match_the_call }
end
end
|
[BUGFIX] Route specs should use a real call object rather than a mock for matching assertions
|
adhearsion_adhearsion
|
train
|
7bed1307e13b96b06ace3e70aae9b037e8595a7c
|
diff --git a/system/user.go b/system/user.go
index <HASH>..<HASH> 100644
--- a/system/user.go
+++ b/system/user.go
@@ -53,7 +53,7 @@ func CreateUser(u *User) error {
}
if u.PrimaryGroup != "" {
- args = append(args, "--primary-group", u.PrimaryGroup)
+ args = append(args, "--gid", u.PrimaryGroup)
}
if len(u.Groups) > 0 {
|
fix(user): user correct primary group flag for useradd
|
coreos_coreos-cloudinit
|
train
|
de1d4c83380ebcfec0be0943384867902498036d
|
diff --git a/termbox_inputfield.go b/termbox_inputfield.go
index <HASH>..<HASH> 100644
--- a/termbox_inputfield.go
+++ b/termbox_inputfield.go
@@ -141,7 +141,7 @@ func (i *InputField) HandleEvent(event termbox.Event) bool {
}
} else if event.Key == termbox.KeyCtrlU {
// Ctrl+U Clears the Input (before the cursor)
- i.value = i.value[i.cursor:]
+ i.value = i.value[i.cursor+len(i.value):]
} else {
// Get the rune to add to our value. Space and Tab are special cases where
// we can't use the event's rune directly
|
Fix Ctrl+U Behavior (Delete line before cursor)
|
br0xen_termbox-util
|
train
|
99b5fce0ec2f4c2ad08c152d233f8e28547a6bd2
|
diff --git a/binstar_client/commands/upload.py b/binstar_client/commands/upload.py
index <HASH>..<HASH> 100644
--- a/binstar_client/commands/upload.py
+++ b/binstar_client/commands/upload.py
@@ -199,7 +199,7 @@ def main(args):
args.description,
dependencies=file_attrs.get('dependencies'),
attrs=file_attrs['attrs'],
- channels=args.channels,
+ channels=args.labels,
callback=upload_print_callback(args))
except errors.Conflict:
full_name = '%s/%s/%s/%s' % (username, package_name, version, file_attrs['basename'])
@@ -237,8 +237,16 @@ def add_parser(subparsers):
parser.add_argument('files', nargs='+', help='Distributions to upload', default=[], type=windows_glob)
- parser.add_argument('-c', '--channel', action='append', default=[], dest='channels',
- help='Add this file to a specific channel. Warning: if the file Channels do not include "main", the file will not show up in your user channel')
+ label_help = (
+ '{deprecation}Add this file to a specific {label}. '
+ 'Warning: if the file {label}s do not include "main",'
+ 'the file will not show up in your user channel')
+
+ parser.add_argument('-c', '--channel', action='append', default=[], dest='labels',
+ help=label_help.format(deprecation='[DEPRECATED]\n', label='channel'),
+ metavar='CHANNELS')
+ parser.add_argument('-l', '--label', action='append', dest='labels',
+ help=label_help.format(deprecation='', label='label'))
parser.add_argument('--no-progress', help="Don't show upload progress", action='store_true')
parser.add_argument('-u', '--user', help='User account, defaults to the current user')
|
Add label alias to upload command
|
Anaconda-Platform_anaconda-client
|
train
|
4bd56c84a22a691317c8ebbf7805b721b814381f
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
@@ -65,6 +65,9 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra
public static final String METADATA_SCHEMA = "SCHEMA";
public static final String METADATA_INDEXMGR = "INDEXMANAGER";
+ public static final String DEFAULT_PARAM_USER = "$user";
+
+
protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
@@ -196,4 +199,12 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra
&& db.getUser().checkIfAllowed(ODatabaseSecurityResources.CLUSTER + "." + iClusterName, getSecurityOperationType()) != null;
}
+ protected void bindDefaultContextVariables(){
+ if(context != null) {
+ if(getDatabase() != null && getDatabase().getUser() != null) {
+ context.setVariable(DEFAULT_PARAM_USER, getDatabase().getUser().getDocument());
+ }
+ }
+ }
+
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
@@ -352,6 +352,8 @@ public class OCommandExecutorSQLSelect extends OCommandExecutorSQLResultsetAbstr
public Object execute(final Map<Object, Object> iArgs) {
try {
+ bindDefaultContextVariables();
+
if (iArgs != null)
// BIND ARGUMENTS INTO CONTEXT TO ACCESS FROM ANY POINT (EVEN FUNCTIONS)
{
|
added context variable in sql queries #<I>
|
orientechnologies_orientdb
|
train
|
e88c190cb77932cc65852e949839542ee49830c5
|
diff --git a/pyemma/_base/progress/reporter/__init__.py b/pyemma/_base/progress/reporter/__init__.py
index <HASH>..<HASH> 100644
--- a/pyemma/_base/progress/reporter/__init__.py
+++ b/pyemma/_base/progress/reporter/__init__.py
@@ -51,7 +51,6 @@ class ProgressReporterMixin(object):
def _prog_rep_progressbars(self):
# stores progressbar representation per stage
if not hasattr(self, '_ProgressReporterMixin__prog_rep_progressbars'):
- print("new dict")
self.__prog_rep_progressbars = {}
return self.__prog_rep_progressbars
@@ -69,16 +68,33 @@ class ProgressReporterMixin(object):
self.__prog_rep_callbacks = {}
return self.__prog_rep_callbacks
- def _progress_context(self):
+ def _progress_context(self, stage='all'):
+ """
+
+ Parameters
+ ----------
+ stage: str, iterable of keys, dict_key
+
+ Returns
+ -------
+ context manager
+ """
from contextlib import contextmanager
@contextmanager
def ctx():
try:
- yield self
+ yield
finally:
- for s in self._prog_rep_progressbars.keys():
- self._progress_force_finish(stage=s)
- return ctx
+ if stage == 'all':
+ keys = tuple(self._prog_rep_progressbars.keys())
+ for s in keys:
+ self._progress_force_finish(stage=s)
+ elif isinstance(stage, (tuple, list)):
+ for s in stage:
+ self._progress_force_finish(s)
+ else:
+ self._progress_force_finish(stage)
+ return ctx()
def __check_stage_registered(self, stage):
if stage not in self._prog_rep_progressbars:
@@ -112,8 +128,9 @@ class ProgressReporterMixin(object):
if amount_of_work <= ProgressReporterMixin._pg_threshold:
from unittest import mock
pg = mock.Mock()
+ pg.dummy = True
else:
- args = dict(total=amount_of_work, desc=description, leave=False, dynamic_ncols=True, **tqdm_args)
+ args = dict(total=amount_of_work, desc=description, leave=True, dynamic_ncols=True, **tqdm_args)
if _attached_to_ipy_notebook():
from .notebook import my_tqdm_notebook
pg = my_tqdm_notebook(**args)
@@ -147,7 +164,7 @@ class ProgressReporterMixin(object):
self.__check_stage_registered(stage)
- if hasattr(self._prog_rep_progressbars[stage], '_dummy'):
+ if hasattr(self._prog_rep_progressbars[stage], 'dummy'):
return
pg = self._prog_rep_progressbars[stage]
@@ -157,19 +174,31 @@ class ProgressReporterMixin(object):
""" forcefully finish the progress for given stage """
if not self.show_progress:
return
+
self.__check_stage_registered(stage)
pg = self._prog_rep_progressbars[stage]
pg.desc = description
- pg.update(pg.total)
+ #pg.update(pg.total - pg.n)
+ #pg.refresh(nolock=True)
pg.close()
- del self._prog_rep_progressbars[stage]
+ self._prog_rep_progressbars.pop(stage, None)
+ self._prog_rep_descriptions.pop(stage, None)
+ self._prog_rep_callbacks.pop(stage, None)
+
+ @property
+ def _progress_num_registered(self):
+ return len(self._prog_rep_progressbars)
+
+ @property
+ def _progress_registered_stages(self):
+ return tuple(self._prog_rep_progressbars.keys())
class ProgressReporter(ProgressReporterMixin):
- def context(self):
- return self._progress_context()
+ def context(self, stage='all'):
+ return self._progress_context(stage=stage)
def register(self, amount_of_work, description='', stage=0, tqdm_args=None):
self._progress_register(amount_of_work=amount_of_work, description=description, stage=stage, tqdm_args=tqdm_args)
@@ -182,3 +211,11 @@ class ProgressReporter(ProgressReporterMixin):
def finish(self, description=None, stage=0):
self._progress_force_finish(description=description, stage=stage)
+
+ @property
+ def num_registered(self):
+ return self._progress_num_registered
+
+ @property
+ def registered_stages(self):
+ return self._progress_registered_stages
|
stage can take str, iterable and key itself.
|
markovmodel_PyEMMA
|
train
|
cf39df822a59b578f21b9b865afb0926ddba992a
|
diff --git a/test/core/TestTsdbQuery.java b/test/core/TestTsdbQuery.java
index <HASH>..<HASH> 100644
--- a/test/core/TestTsdbQuery.java
+++ b/test/core/TestTsdbQuery.java
@@ -1341,9 +1341,9 @@ public final class TestTsdbQuery {
HashMap<String, String> tags = new HashMap<String, String>(1);
tags.put("host", "web01");
long timestamp = 1356998400;
- tsdb.addPoint("sys.cpu.user", timestamp += 30, (long)(Long.MAX_VALUE - 55), tags)
+ tsdb.addPoint("sys.cpu.user", timestamp += 30, Long.MAX_VALUE - 55, tags)
.joinUninterruptibly();
- tsdb.addPoint("sys.cpu.user", timestamp += 30, (long)(Long.MAX_VALUE - 25), tags)
+ tsdb.addPoint("sys.cpu.user", timestamp += 30, Long.MAX_VALUE - 25, tags)
.joinUninterruptibly();
tsdb.addPoint("sys.cpu.user", timestamp += 30, 5, tags).joinUninterruptibly();
|
Fix redundant cast in TestTsdbQuery
|
OpenTSDB_opentsdb
|
train
|
f7f50b3fe88d75f793ad68fc751222b4d32059cc
|
diff --git a/goaci.go b/goaci.go
index <HASH>..<HASH> 100644
--- a/goaci.go
+++ b/goaci.go
@@ -353,6 +353,9 @@ func writeACI(pathsNames *pathsAndNames, manifest *schema.ImageManifest) error {
tr := tar.NewWriter(gw)
defer tr.Close()
+ // FIXME: the files in the tar archive are added with the
+ // wrong uid/gid. The uid/gid of the aci builder leaks in the
+ // tar archive. See: #16
iw := aci.NewImageWriter(*manifest, tr)
if err := filepath.Walk(pathsNames.aciDirPath, aci.BuildWalker(pathsNames.aciDirPath, iw)); err != nil {
return err
|
Add a FIXME for an uig/gid leaking issue
|
appc_goaci
|
train
|
fb9b48304abb1a6fea683d15b4e2b54575370f52
|
diff --git a/src/WindowBase.js b/src/WindowBase.js
index <HASH>..<HASH> 100644
--- a/src/WindowBase.js
+++ b/src/WindowBase.js
@@ -4,6 +4,7 @@ const fs = require('fs');
const vm = require('vm');
const util = require('util');
const {Worker, workerData, parentPort} = require('worker_threads');
+const {MessageEvent} = require('./Event');
const {process} = global;
// global initialization
@@ -138,7 +139,10 @@ parentPort.on('message', m => {
}
case 'postMessage': {
try {
- global.emit('message', m.message);
+ const e = new MessageEvent('messge', {
+ data: m.message,
+ });
+ global.emit('message', e);
} catch(err) {
console.warn(err.stack);
}
|
Emit real worker messages in WindowBase.js
|
exokitxr_exokit
|
train
|
800f4c79d2ef5dd2a93c3b84eabfc34bb0ec5271
|
diff --git a/src/ReflectionEngine.php b/src/ReflectionEngine.php
index <HASH>..<HASH> 100644
--- a/src/ReflectionEngine.php
+++ b/src/ReflectionEngine.php
@@ -141,18 +141,49 @@ class ReflectionEngine
$namespace = self::parseFileNamespace($classFileName, $namespaceName);
$namespaceNodes = $namespace->stmts;
- foreach ($namespaceNodes as $namespaceLevelNode) {
- if ($namespaceLevelNode instanceof ClassLike && $namespaceLevelNode->name == $className) {
- $namespaceLevelNode->setAttribute('fileName', $classFileName);
+ $node = self::findClassLikeNodeByClassName($namespaceNodes, $className);
- return $namespaceLevelNode;
- }
+ if ($node instanceof ClassLike) {
+ $node->setAttribute('fileName', $classFileName);
+
+ return $node;
}
throw new \InvalidArgumentException("Class $fullClassName was not found in the $classFileName");
}
/**
+ * Loop through an array and find a ClassLike statement by the given class name.
+ *
+ * If an if statement like `if (false) {` is found, the class will also be search inside that if statement.
+ * This relies on the guide of greg0ire on how to deprecate a type.
+ *
+ * @see https://dev.to/greg0ire/how-to-deprecate-a-type-in-php-48cf
+ * @param array $nodes
+ * @param string $className
+ *
+ * @return null|ClassLike
+ */
+ protected static function findClassLikeNodeByClassName($nodes, $className) {
+ foreach ($nodes as $node) {
+ if ($node instanceof ClassLike && $node->name == $className) {
+ return $node;
+ } elseif (
+ $node instanceof Node\Stmt\If_
+ && $node->cond instanceof Node\Expr\ConstFetch
+ && isset($node->cond->name->parts[0])
+ && $node->cond->name->parts[0] === 'false'
+ ) {
+ $result = self::findClassLikeNodeByClassName($node->stmts, $className);
+
+ if ($result instanceof ClassLike) {
+ return $result;
+ }
+ }
+ }
+ }
+
+ /**
* Parses class method
*
* @param string $fullClassName Name of the class
|
[fix_php_type_migration] Make it possible to scan for deprecated types.
According to <URL>
|
goaop_parser-reflection
|
train
|
fd9fc5d0a3ec9051cfe511f1a154241c2b1aab59
|
diff --git a/tests/inc/DataTestCase.php b/tests/inc/DataTestCase.php
index <HASH>..<HASH> 100644
--- a/tests/inc/DataTestCase.php
+++ b/tests/inc/DataTestCase.php
@@ -41,10 +41,12 @@ class DataTestCase extends TestCase
$queries = [];
$conn->onQuery[__CLASS__] = function ($conn, $sql) use (& $queries) {
- if (strpos($sql, 'pg_catalog') === false && strpos($sql, 'information_schema') === false && strpos($sql, 'SHOW FULL') === false) {
- $queries[] = $sql;
- echo $sql, "\n";
+ if (preg_match('#(pg_catalog|information_schema|SHOW\s+FULL|SELECT\s+CURRVAL)#i', $sql) === 1) {
+ return;
}
+
+ $queries[] = $sql;
+ echo $sql, "\n";
};
try {
|
tests: better ignore for logged queries
|
nextras_orm
|
train
|
42c6e7faf0a8c902303f9a9813ed2fa35f1c89be
|
diff --git a/test/serialization_format_change_test.rb b/test/serialization_format_change_test.rb
index <HASH>..<HASH> 100644
--- a/test/serialization_format_change_test.rb
+++ b/test/serialization_format_change_test.rb
@@ -7,8 +7,8 @@ class SerializationFormatChangeTest < IdentityCache::TestCase
MESSAGE = "serialization format changed => increment IdentityCache.CACHE_VERSION and run rake update_serialization_format"
def test_serialization_format_has_not_changed
- serialization = serialize(serialized_record)
- preserialization = File.binread(serialized_record_file)
+ serialization = Marshal.load(serialize(serialized_record))
+ preserialization = Marshal.load(File.binread(serialized_record_file))
assert_equal(preserialization, serialization, MESSAGE)
rescue SystemCallError
assert(false, MESSAGE)
|
Compare unmarshalled hashes instead of marshalled data
Marshal.dump output has subtly changed in Ruby <I>, but the marshal
version hasn't changed. This change compares hashes loaded by
Marshal.load, which tolerates the change in serialization format,
rather than the raw serialized bytes.
|
Shopify_identity_cache
|
train
|
79206b2f55f933d6345dfdd9a5a876f784b409cc
|
diff --git a/src/Tao/Controller/Controller.php b/src/Tao/Controller/Controller.php
index <HASH>..<HASH> 100644
--- a/src/Tao/Controller/Controller.php
+++ b/src/Tao/Controller/Controller.php
@@ -34,9 +34,9 @@ class Controller
*
* @see UrlGeneratorInterface
*/
- public function generateUrl($route, $parameters = [], $language = null, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
+ public function generateUrl($route, $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
- return $this->app['router']->generate($route, $parameters, $language, $referenceType);
+ return $this->app['router']->generate($route, $parameters, $referenceType);
}
/**
@@ -61,9 +61,9 @@ class Controller
*
* @return RedirectResponse
*/
- protected function redirectToRoute($route, array $parameters = array(), $status = 302)
+ protected function redirectToRoute($route, array $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH, $status = 302)
{
- return $this->redirect($this->generateUrl($route, $parameters), $status);
+ return $this->redirect($this->generateUrl($route, $parameters, $referenceType), $status);
}
public function jsonResponse($data = null, $status = 200, array $headers = [])
|
pass reference type argument to redirectToRoute method
|
forxer_tao
|
train
|
a2d17bfec64e96789271c54ea5665524fb7e66bb
|
diff --git a/dedupe/core.py b/dedupe/core.py
index <HASH>..<HASH> 100644
--- a/dedupe/core.py
+++ b/dedupe/core.py
@@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
from builtins import range, next, zip, map
from future.utils import viewvalues
-import sys
+import sys
import itertools
import time
import tempfile
@@ -351,6 +351,9 @@ def scoreGazette(records, data_model, classifier, num_cores=1, threshold=0):
score_records = ScoreGazette(data_model, classifier, threshold)
+ if sys.version < '3':
+ records = (list(y) for y in records)
+
for scored_pairs in imap(score_records, records):
yield scored_pairs
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -26,7 +26,7 @@ install_requires = ['fastcluster',
setup(
name='dedupe',
url='https://github.com/dedupeio/dedupe',
- version='1.9.1',
+ version='1.9.2',
author='Forest Gregg',
author_email='fgregg@datamade.us',
description='A python library for accurate and scaleable data deduplication and entity-resolution',
|
python 2 imap_unordered can't handle a generator of generators
|
dedupeio_dedupe
|
train
|
5b034f00ecea097f850f900a5b0165616cfe9fa1
|
diff --git a/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/AlignmentFileReader.java b/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/AlignmentFileReader.java
index <HASH>..<HASH> 100644
--- a/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/AlignmentFileReader.java
+++ b/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/AlignmentFileReader.java
@@ -17,10 +17,10 @@
package org.opencb.biodata.formats.alignment;
import htsjdk.samtools.*;
-import org.opencb.biodata.formats.alignment.AlignmentConverter;
+import org.opencb.biodata.formats.alignment.io.AlignmentDataReader;
import org.opencb.biodata.models.alignment.Alignment;
+import org.opencb.biodata.models.alignment.AlignmentHeader;
import org.opencb.biodata.models.core.Region;
-import org.opencb.commons.io.DataReader;
import org.opencb.commons.utils.FileUtils;
import java.io.IOException;
@@ -33,11 +33,12 @@ import java.util.function.Consumer;
/**
* Created by imedina on 18/10/15.
*/
-public class AlignmentFileReader implements DataReader<Alignment>, Iterable<Alignment> {
+public class AlignmentFileReader implements AlignmentDataReader, Iterable<Alignment> {
private Path input;
private SamReader samReader;
+ private SAMFileHeader samFileHeader;
private SAMRecordIterator samRecordIterator;
public AlignmentFileReader(Path input) throws IOException {
@@ -62,11 +63,17 @@ public class AlignmentFileReader implements DataReader<Alignment>, Iterable<Alig
SamReaderFactory srf = SamReaderFactory.make();
srf.validationStringency(ValidationStringency.LENIENT);
samReader = srf.open(SamInputResource.of(input.toFile()));
+ samFileHeader = samReader.getFileHeader();
samRecordIterator = samReader.iterator();
return samReader != null;
}
+ @Override
+ public AlignmentHeader getHeader() {
+ return AlignmentConverter.buildAlignmentHeader(samFileHeader, "");
+ }
+
public AlignmentFileReaderIterator query(String chromosome, int start, int end, boolean contained) {
SAMRecordIterator queryIterator = samReader.query(chromosome, start, end, contained);
return new AlignmentFileReaderIterator(queryIterator);
@@ -109,7 +116,6 @@ public class AlignmentFileReader implements DataReader<Alignment>, Iterable<Alig
return alignmentFileReaderIterator;
}
-
@Override
public boolean close() {
if (samRecordIterator != null) {
diff --git a/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/io/AlignmentDataReader.java b/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/io/AlignmentDataReader.java
index <HASH>..<HASH> 100644
--- a/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/io/AlignmentDataReader.java
+++ b/biodata-formats/src/main/java/org/opencb/biodata/formats/alignment/io/AlignmentDataReader.java
@@ -30,5 +30,5 @@ import org.opencb.commons.io.DataReader;
*/
public interface AlignmentDataReader extends DataReader<Alignment> {
- public AlignmentHeader getHeader();
+ AlignmentHeader getHeader();
}
|
formats: small improvements in AlignmentFileReader, now it implements AlignmentDataReader interface
|
opencb_biodata
|
train
|
df2b18fdd18b2497a32c0b2a370451144818a857
|
diff --git a/translator/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGenerator.java b/translator/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGenerator.java
index <HASH>..<HASH> 100644
--- a/translator/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGenerator.java
+++ b/translator/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGenerator.java
@@ -97,10 +97,17 @@ public class ObjectiveCSegmentedHeaderGenerator extends ObjectiveCHeaderGenerato
newline();
printForwardDeclarations(collector.getForwardDeclarations());
+ outer:
for (Import imp : collector.getSuperTypes()) {
if (mainTypeName.equals(imp.getMainTypeName())) {
continue;
}
+ // Verify this import isn't declared in this source file.
+ for (AbstractTypeDeclaration type : importCollectors.keySet()) {
+ if (imp.getType().equals(type.getTypeBinding())) {
+ continue outer;
+ }
+ }
printf("#define %s_RESTRICT 1\n", imp.getMainTypeName());
printf("#define %s_INCLUDE 1\n", imp.getTypeName());
printf("#include \"%s.h\"\n", imp.getImportFileName());
diff --git a/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCHeaderGeneratorTest.java b/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCHeaderGeneratorTest.java
index <HASH>..<HASH> 100644
--- a/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCHeaderGeneratorTest.java
+++ b/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCHeaderGeneratorTest.java
@@ -731,4 +731,13 @@ public class ObjectiveCHeaderGeneratorTest extends GenerationTest {
"- (void)yak;");
assertNotInTranslation(translation, "zebra"); // No zebra() since it's private.
}
+
+ // Verify that when a class is referenced in the same source file, a header
+ // isn't included for it.
+ public void testPackagePrivateBaseClass() throws IOException {
+ String translation = translateSourceFile(
+ "package bar; public class Test extends Foo {} " +
+ "abstract class Foo {}", "Test", "bar/Test.h");
+ assertNotInTranslation(translation, "#include \"Foo.h\"");
+ }
}
diff --git a/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGeneratorTest.java b/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGeneratorTest.java
index <HASH>..<HASH> 100644
--- a/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGeneratorTest.java
+++ b/translator/src/test/java/com/google/devtools/j2objc/gen/ObjectiveCSegmentedHeaderGeneratorTest.java
@@ -71,4 +71,13 @@ public class ObjectiveCSegmentedHeaderGeneratorTest extends GenerationTest {
"#define Test_INCLUDE 1",
"#endif");
}
+
+ // Verify that when a class is referenced in the same source file, a header
+ // isn't included for it.
+ public void testPackagePrivateBaseClass() throws IOException {
+ String translation = translateSourceFile(
+ "package bar; public class Test extends Foo {} " +
+ "abstract class Foo {}", "Test", "bar/Test.h");
+ assertNotInTranslation(translation, "#include \"Foo.h\"");
+ }
}
|
Fixed segmented header generation when referenced type is in same source file.
|
google_j2objc
|
train
|
ae66ab45d7d72ffc81548f194b2df5695ae96b98
|
diff --git a/lib/fog/openstack.rb b/lib/fog/openstack.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/openstack.rb
+++ b/lib/fog/openstack.rb
@@ -74,18 +74,29 @@ module Fog
@openstack_api_key = options[:openstack_api_key]
@openstack_username = options[:openstack_username]
@openstack_tenant = options[:openstack_tenant]
- @service_name = options[:openstack_service_name]
+ @openstack_auth_token = options[:openstack_auth_token]
+ @service_name = options[:openstack_service_name]
@identity_service_name = options[:openstack_identity_service_name]
- @endpoint_type = options[:openstack_endpoint_type] || 'publicURL'
-
- req_body= {
- 'auth' => {
- 'passwordCredentials' => {
- 'username' => @openstack_username,
- 'password' => @openstack_api_key
+ @endpoint_type = options[:openstack_endpoint_type] || 'publicURL'
+
+ if @openstack_auth_token
+ req_body = {
+ 'auth' => {
+ 'token' => {
+ 'id' => @openstack_auth_token
+ }
}
}
- }
+ else
+ req_body = {
+ 'auth' => {
+ 'passwordCredentials' => {
+ 'username' => @openstack_username,
+ 'password' => @openstack_api_key
+ }
+ }
+ }
+ end
req_body['auth']['tenantName'] = @openstack_tenant if @openstack_tenant
body = retrieve_tokens_v2(connection, req_body, uri)
diff --git a/lib/fog/openstack/compute.rb b/lib/fog/openstack/compute.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/openstack/compute.rb
+++ b/lib/fog/openstack/compute.rb
@@ -273,6 +273,7 @@ module Fog
options = {
:openstack_api_key => @openstack_api_key,
:openstack_username => @openstack_username,
+ :openstack_auth_token => @openstack_auth_token,
:openstack_auth_uri => @openstack_auth_uri,
:openstack_tenant => @openstack_tenant,
:openstack_service_name => @openstack_service_name,
diff --git a/lib/fog/openstack/identity.rb b/lib/fog/openstack/identity.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/openstack/identity.rb
+++ b/lib/fog/openstack/identity.rb
@@ -166,6 +166,7 @@ module Fog
options = {
:openstack_api_key => @openstack_api_key,
:openstack_username => @openstack_username,
+ :openstack_auth_token => @openstack_auth_token,
:openstack_auth_uri => @openstack_auth_uri,
:openstack_tenant => @openstack_tenant,
:openstack_service_name => @openstack_service_name,
diff --git a/lib/fog/openstack/image.rb b/lib/fog/openstack/image.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/openstack/image.rb
+++ b/lib/fog/openstack/image.rb
@@ -141,6 +141,7 @@ module Fog
:openstack_api_key => @openstack_api_key,
:openstack_username => @openstack_username,
:openstack_auth_uri => @openstack_auth_uri,
+ :openstack_auth_token => @openstack_auth_token,
:openstack_service_name => @openstack_service_name,
:openstack_endpoint_type => 'adminURL'
}
|
[openstack] Update Authentication through X-Auth-Token
|
fog_fog
|
train
|
c12132187e2c802ddc9158a66bcd7ee416410c5a
|
diff --git a/src/exceptions/stacktrace.js b/src/exceptions/stacktrace.js
index <HASH>..<HASH> 100644
--- a/src/exceptions/stacktrace.js
+++ b/src/exceptions/stacktrace.js
@@ -44,11 +44,13 @@ module.exports = {
opts = utils.mergeObject(defaultOptions, opts)
return new Promise(function (resolve) {
- var stackframes = ErrorStackParser.parse(error)
+ var stackFrames = ErrorStackParser.parse(error)
if (typeof opts.filter === 'function') {
- stackframes = stackframes.filter(opts.filter)
+ stackFrames = stackFrames.filter(opts.filter)
}
- resolve(Promise.all(stackframes.map(function (sf) {
+
+
+ resolve(Promise.all(stackFrames.map(function (sf) {
return new Promise(function (resolve) {
resolve(sf)
})
|
Consistent casing of variable name
|
opbeat_opbeat-js-core
|
train
|
25423987186813e0be14184dc2469ccce3640d9c
|
diff --git a/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/CharacterSelector.java b/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/CharacterSelector.java
index <HASH>..<HASH> 100644
--- a/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/CharacterSelector.java
+++ b/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/CharacterSelector.java
@@ -9,15 +9,15 @@ public interface CharacterSelector {
* Selects one of the given characters to login.
* <p>
* This method may be called during the authentication if no character is
- * selected. An {@link AuthenticationException} will be thrown if the method
- * returns {@code null}.
+ * selected.
* <p>
- * 假如在登录期间发现还没有选择一个角色,就会调用这个方法来选择角色。假如这个方法返回 {@code null} ,则会抛出一个
- * {@link AuthenticationException} 。(注:一个Yggdrasil账号可以拥有多个游戏角色)
+ * 假如在登录期间发现还没有选择一个角色,就会调用这个方法来选择角色。假如这个方法返回 {@code null}
+ * 。(注:一个Yggdrasil账号可以拥有多个游戏角色)
*
* @param availableProfiles the available characters
* @return the character to login
+ * @throws AuthenticationException if an authentication error occurs
*/
- GameProfile select(GameProfile[] availableProfiles);
+ GameProfile select(GameProfile[] availableProfiles) throws AuthenticationException;
}
diff --git a/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java b/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java
index <HASH>..<HASH> 100644
--- a/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java
+++ b/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java
@@ -380,11 +380,9 @@ public class YggdrasilAuthenticator implements Authenticator, SessionCredential,
}
GameProfile selectedProfile = selector.select(profiles);
- if (selectedProfile == null) {
- throw new AuthenticationException("No profile is selected");
+ if (selectedProfile != null) {
+ authResult = authenticationService.selectProfile(authResult.getClientToken(), authResult.getAccessToken(), selectedProfile.getUUID());
}
-
- authResult = authenticationService.selectProfile(authResult.getClientToken(), authResult.getAccessToken(), selectedProfile.getUUID());
}
}
diff --git a/jmccc-yggdrasil-authenticator/src/test/java/org/to2mbn/jmccc/auth/yggdrasil/test/YggdrasilAuthenticatorTest.java b/jmccc-yggdrasil-authenticator/src/test/java/org/to2mbn/jmccc/auth/yggdrasil/test/YggdrasilAuthenticatorTest.java
index <HASH>..<HASH> 100644
--- a/jmccc-yggdrasil-authenticator/src/test/java/org/to2mbn/jmccc/auth/yggdrasil/test/YggdrasilAuthenticatorTest.java
+++ b/jmccc-yggdrasil-authenticator/src/test/java/org/to2mbn/jmccc/auth/yggdrasil/test/YggdrasilAuthenticatorTest.java
@@ -27,14 +27,12 @@ public class YggdrasilAuthenticatorTest {
assertEquals(service.e_profiles[1], authenticator.getCurrentSession().getSelectedProfile());
}
- @Test(expected = AuthenticationException.class)
public void testRefreshWithPasswordNullProfile() throws AuthenticationException {
MockAuthenticationService service = new MockAuthenticationService();
YggdrasilAuthenticator authenticator = new YggdrasilAuthenticator(service);
authenticator.refreshWithPassword("user", "password", new MockCharacterSelector(null));
}
- @Test(expected = AuthenticationException.class)
public void testRefreshWithPasswordNoProfile() throws AuthenticationException {
MockAuthenticationService service = new MockAuthenticationService();
service.e_profiles = new GameProfile[0];
|
Don't throw AuthenticationException if no profile is selected when refreshing
|
to2mbn_JMCCC
|
train
|
cb3f25593b1137e344086364d4b1a52c08e8eb3b
|
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -643,13 +643,7 @@ module ActionController
end
def array_of_permitted_scalars?(value)
- if value.is_a?(Array)
- value.all? {|element| permitted_scalar?(element)}
- end
- end
-
- def array_of_permitted_scalars_filter(value)
- if array_of_permitted_scalars?(value)
+ if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)}
yield value
end
end
@@ -665,7 +659,7 @@ module ActionController
if filter[key] == EMPTY_ARRAY
# Declaration { comment_ids: [] }.
- array_of_permitted_scalars_filter(self[key]) do |val|
+ array_of_permitted_scalars?(self[key]) do |val|
params[key] = val
end
else
|
remove useless function
Now that the value is cached on the stack,
`array_of_permitted_scalars_filter` is exactly the same as
`array_of_permitted_scalars?`, so lets just have one
|
rails_rails
|
train
|
84b9d5a661595a90604cf7cfb9e82c120d666f1b
|
diff --git a/cloudinary-core/src/main/java/com/cloudinary/transformation/BaseExpression.java b/cloudinary-core/src/main/java/com/cloudinary/transformation/BaseExpression.java
index <HASH>..<HASH> 100644
--- a/cloudinary-core/src/main/java/com/cloudinary/transformation/BaseExpression.java
+++ b/cloudinary-core/src/main/java/com/cloudinary/transformation/BaseExpression.java
@@ -26,7 +26,8 @@ public abstract class BaseExpression<T extends BaseExpression> {
"*", "mul",
"/", "div",
"+", "add",
- "-", "sub"
+ "-", "sub",
+ "^", "pow"
);
public static final Map<String, String> PREDEFINED_VARS = ObjectUtils.asMap(
"width", "w",
@@ -245,6 +246,29 @@ public abstract class BaseExpression<T extends BaseExpression> {
return (T) this;
}
+ /**
+ * Utility shortcut method which invokes on this Expression instance {@link #pow()} method, takes its result and
+ * invokes {@link #value(Object)} method on it. Effectively, invocation of this shortcut results in
+ * "to the power of value" sub-expression added to the end of current expression instance.
+ *
+ * @param value argument for {@link #value(Object)} call
+ * @return result of {@link #value(Object)} call
+ */
+ public T pow(Object value) {
+ return (T) pow().value(value);
+ }
+
+ /**
+ * Adds "to the power of" sub-expression to the end of the list of already present sub-expressions in this
+ * expression instance.
+ *
+ * @return this expression instance
+ */
+ public T pow() {
+ expressions.add("pow");
+ return (T) this;
+ }
+
public T value(Object value) {
expressions.add(String.valueOf(value));
return (T) this;
diff --git a/cloudinary-core/src/test/java/com/cloudinary/TransformationTest.java b/cloudinary-core/src/test/java/com/cloudinary/TransformationTest.java
index <HASH>..<HASH> 100644
--- a/cloudinary-core/src/test/java/com/cloudinary/TransformationTest.java
+++ b/cloudinary-core/src/test/java/com/cloudinary/TransformationTest.java
@@ -210,4 +210,12 @@ public class TransformationTest {
).fontFamily("Arial").fontSize(18));
assertEquals("c_scale,l_text:Arial_18:$(start)Hello%20$(name)$(ext)%252C%20%24%28no%20%29%20%24%28%20no%29$(end)", t.generate());
}
+
+ @Test
+ public void testShouldSupportPowOperator() {
+ Transformation t = new Transformation()
+ .variables(variable("$small", 150), variable("$big", "$small ^ 1.5"));
+
+ assertEquals("$small_150,$big_$small_pow_1.5", t.generate());
+ }
}
\ No newline at end of file
|
Add support for pow operator in expressions (#<I>)
|
cloudinary_cloudinary_java
|
train
|
55414e0f919e6196b02739c0685346b06c66516a
|
diff --git a/app/controllers/concerns/genkan/authenticatable.rb b/app/controllers/concerns/genkan/authenticatable.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/concerns/genkan/authenticatable.rb
+++ b/app/controllers/concerns/genkan/authenticatable.rb
@@ -12,7 +12,7 @@ module Genkan
def authenticate
unless logged_in?
- session[:referer] = request.fullpath
+ store_location
redirect_to genkan.login_path, notice: t('genkan.sessions.required')
end
end
@@ -25,5 +25,9 @@ module Genkan
def logged_in?
send(current_user_method_name).present?
end
+
+ def store_location
+ session[:referer] = request.fullpath
+ end
end
end
|
Refactor Genkan::Authenticatable
|
yhirano55_genkan
|
train
|
de284c2253d9b2ee515f30cde20aa72bc4dcc72a
|
diff --git a/lib/services.js b/lib/services.js
index <HASH>..<HASH> 100644
--- a/lib/services.js
+++ b/lib/services.js
@@ -33,7 +33,7 @@ module.exports = function(dolphin){
* Removes a service.
*/
services.remove = function (serviceId) {
- return dolphin._delete('service/' + serviceId, opts);
+ return dolphin._delete('services/' + serviceId, opts);
}
return services;
|
Update services.js
fix services.remove url
|
OptimalBits_dolphin
|
train
|
8578f72762ae08740b6258d12658b6e432e26d48
|
diff --git a/lib/multi.js b/lib/multi.js
index <HASH>..<HASH> 100644
--- a/lib/multi.js
+++ b/lib/multi.js
@@ -2,21 +2,31 @@
var Multi = function (repackersMap) {
this.repackersMap = repackersMap;
- this.collectingFunc = null;
+ this.collectFunc = null;
};
Multi.prototype.srcKeyPrefixSeparator = '__';
Multi.prototype.dstKeyPrefixSeparator = '.';
Multi.prototype.anyKeyPrefix = '*';
-Multi.prototype.getCollectingFunc = function () {
- if (this.collectingFunc == null) {
- this.collectingFunc = function (row, data) {
- // TODO handle exceptions
- data.push(this.repack(row));
+Multi.prototype.getCollectFunc = function () {
+ if (this.collectFunc == null) {
+ var self = this;
+ this.collectFunc = function (row, data) {
+ data.push(self.repack(row));
};
}
- return this.collectingFunc;
+ return this.collectFunc;
+};
+
+Multi.prototype.getTransformFunc = function () {
+ if (this.transformFunc == null) {
+ var self = this;
+ this.transformFunc = function (row) {
+ return self.repack(row);
+ };
+ }
+ return this.transformFunc;
};
Multi.prototype.extractSrcKeyPrefix = function (srcKey) {
@@ -29,9 +39,9 @@ Multi.prototype.extractDstKeyPrefix = function (dstKey) {
Multi.prototype.getKeyPrefix = function (key, sep) {
var result;
- var sepPos = srcKey.indexOf(sep);
+ var sepPos = key.indexOf(sep);
if (sepPos > 0) {
- result = srcKey.substr(sepPos + sep.length);
+ result = key.substr(sepPos + sep.length);
}
return result;
};
@@ -42,7 +52,7 @@ Multi.prototype.getRepacker = function (prefix) {
result = this.repackersMap[prefix];
}
if (result == null) {
- result = this.repackersMap[thia.anyKeyPrefix];
+ result = this.repackersMap[this.anyKeyPrefix];
if (result == null) {
if (prefix == null) {
throw new Error('No default repacker defined');
@@ -57,7 +67,7 @@ Multi.prototype.getRepacker = function (prefix) {
Multi.prototype.createDstKeyGroups = function (dstKeys) {
var groups = {};
- for (i = 0; i < dstKeys.length; i++) {
+ for (var i = 0; i < dstKeys.length; i++) {
var dstKey = dstKeys[i];
var prefix = this.extractDstKeyPrefix(dstKey) || this.anyKeyPrefix;
var group = groups[prefix];
@@ -71,7 +81,7 @@ Multi.prototype.createDstKeyGroups = function (dstKeys) {
Multi.prototype.createSrcGroups = function (src, opt_prefixesToUse) {
var groups = {};
- for (srcKey in src) {
+ for (var srcKey in src) {
var prefix = this.extractSrcKeyPrefix(srcKey) || this.anyKeyPrefix;
if (opt_prefixesToUse != null && !(prefix in opt_prefixesToUse)) {
continue;
@@ -87,7 +97,7 @@ Multi.prototype.createSrcGroups = function (src, opt_prefixesToUse) {
Multi.prototype.addSrcKeysPrefix = function (srcKeys, prefix) {
var result = [];
- for (i = 0; i < srcKeys.length; i++) {
+ for (var i = 0; i < srcKeys.length; i++) {
result.push([prefix, srcKeys[i]].join(this.srcKeyPrefixSeparator));
}
return result;
diff --git a/lib/repacker.js b/lib/repacker.js
index <HASH>..<HASH> 100644
--- a/lib/repacker.js
+++ b/lib/repacker.js
@@ -10,7 +10,7 @@ var Repacker = function (opt_rules, opt_othersRule) {
this.dstKeyRuleMap = null;
this.ruleCoveredSrcKeys = null;
- this.collectingFunc = null;
+ this.collectFunc = null;
this.transformFunc = null;
this.keyExprMap = null;
@@ -52,14 +52,14 @@ Repacker.prototype.getFields = function (dstKeys, prefix, outPrefix) {
return this.srcKeysToFields(this.getSrcKeys(dstKeys), prefix, outPrefix);
};
-Repacker.prototype.getCollectingFunc = function () {
- if (this.collectingFunc == null) {
+Repacker.prototype.getCollectFunc = function () {
+ if (this.collectFunc == null) {
var self = this;
- this.collectingFunc = function (row, data) {
+ this.collectFunc = function (row, data) {
data.push(self.repack(row));
};
}
- return this.collectingFunc;
+ return this.collectFunc;
};
Repacker.prototype.getTransformFunc = function () {
|
collectingFunc renamed to collectFunc, number of fixes in multi
|
dimsmol_repack
|
train
|
8df85d9db7e7e27fff58944ec89a85566d598b3d
|
diff --git a/src/com/aoindustries/util/persistent/DynamicPersistentBlockBuffer.java b/src/com/aoindustries/util/persistent/DynamicPersistentBlockBuffer.java
index <HASH>..<HASH> 100644
--- a/src/com/aoindustries/util/persistent/DynamicPersistentBlockBuffer.java
+++ b/src/com/aoindustries/util/persistent/DynamicPersistentBlockBuffer.java
@@ -332,7 +332,7 @@ public class DynamicPersistentBlockBuffer extends AbstractPersistentBlockBuffer
pbuffer.put(nextId, (byte)blockSizeBits);
if(fsm==null) freeSpaceMaps.set(blockSizeBits, fsm = new TreeSet<Long>());
fsm.add(nextId);
- barrier(false); // When splitting, the right side must have appropriate size header before left side is updated
+ barrier(false); // Required? When splitting, the right side must have appropriate size header before left side is updated
pbuffer.put(biggerAvailableId, (byte)blockSizeBits);
return biggerAvailableId;
}
diff --git a/test/com/aoindustries/util/persistent/BlockBufferSingleBitmapFixedTest.java b/test/com/aoindustries/util/persistent/BlockBufferSingleBitmapFixedTest.java
index <HASH>..<HASH> 100644
--- a/test/com/aoindustries/util/persistent/BlockBufferSingleBitmapFixedTest.java
+++ b/test/com/aoindustries/util/persistent/BlockBufferSingleBitmapFixedTest.java
@@ -62,4 +62,12 @@ public class BlockBufferSingleBitmapFixedTest extends BlockBufferTestParent {
public void testFailureRecoveryBarrier() {
// Skip test
}
+
+ /**
+ * This test is not compatible with non-persistent {@link SparseBuffer}
+ */
+ @Override
+ public void testFailureRecoveryForce() {
+ // Skip test
+ }
}
diff --git a/test/com/aoindustries/util/persistent/BlockBufferTestParent.java b/test/com/aoindustries/util/persistent/BlockBufferTestParent.java
index <HASH>..<HASH> 100644
--- a/test/com/aoindustries/util/persistent/BlockBufferTestParent.java
+++ b/test/com/aoindustries/util/persistent/BlockBufferTestParent.java
@@ -53,7 +53,7 @@ abstract public class BlockBufferTestParent extends TestCase {
abstract public PersistentBlockBuffer getBlockBuffer(PersistentBuffer pbuffer) throws IOException;
abstract public long getAllocationSize(Random random) throws IOException;
- public void teTODOstAllocateDeallocate() throws Exception {
+ public void testAllocateDeallocate() throws Exception {
File tempFile = File.createTempFile("BlockBufferTestParent", null);
tempFile.deleteOnExit();
PersistentBlockBuffer blockBuffer = getBlockBuffer(getBuffer(tempFile, ProtectionLevel.NONE));
|
Dynamic block buffer is slow but all tests passed.
|
aoindustries_aocode-public
|
train
|
d8ed247c7f11b1ca4756134e145d2ec3bfeb8eaf
|
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -1,24 +1,9 @@
require 'bigdecimal'
-require 'psych'
require 'yaml'
class BigDecimal
- YAML_TAG = 'tag:yaml.org,2002:float'
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
- # This emits the number without any scientific notation.
- # This is better than self.to_f.to_s since it doesn't lose precision.
- #
- # Note that reconstituting YAML floats to native floats may lose precision.
- def to_yaml(opts = {})
- return super if !YAML::ENGINE.syck?
-
- YAML.quick_emit(nil, opts) do |out|
- string = to_s
- out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain)
- end
- end
-
def encode_with(coder)
string = to_s
coder.represent_scalar(nil, YAML_MAPPING[string] || string)
|
No need to override the to_yaml method in BigDecimal
|
rails_rails
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.