hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
76d18d147d71a79427edb93a9e011f4bf7f6d31a | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -24,6 +24,7 @@ setup(name='docrep',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
],
keywords='docstrings docs docstring napoleon numpy reStructured text', | Add Python <I> as Programming Language [skip ci] | Chilipp_docrep | train |
d3d4e3cdead72f523787d8fb6fe9265b74c7d5d4 | diff --git a/aws/data_source_aws_security_group.go b/aws/data_source_aws_security_group.go
index <HASH>..<HASH> 100644
--- a/aws/data_source_aws_security_group.go
+++ b/aws/data_source_aws_security_group.go
@@ -5,6 +5,7 @@ import (
"log"
"github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/schema"
)
@@ -91,8 +92,14 @@ func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) er
d.Set("description", sg.Description)
d.Set("vpc_id", sg.VpcId)
d.Set("tags", tagsToMap(sg.Tags))
- d.Set("arn", fmt.Sprintf("arn:%s:ec2:%s:%s:security-group/%s",
- meta.(*AWSClient).partition, meta.(*AWSClient).region, *sg.OwnerId, *sg.GroupId))
+ arn := arn.ARN{
+ Partition: meta.(*AWSClient).partition,
+ Service: "ec2",
+ Region: meta.(*AWSClient).region,
+ AccountID: *sg.OwnerId,
+ Resource: fmt.Sprintf("security-group/%s", *sg.GroupId),
+ }
+ d.Set("arn", arn.String())
return nil
} | Use AWS ARN structure - aws_security_group resource. | terraform-providers_terraform-provider-aws | train |
d28ac387036df3868322dd8e3f564a7209686d51 | diff --git a/EOAuth2Service.php b/EOAuth2Service.php
index <HASH>..<HASH> 100644
--- a/EOAuth2Service.php
+++ b/EOAuth2Service.php
@@ -44,16 +44,42 @@ abstract class EOAuth2Service extends EAuthServiceBase implements IAuthService {
*/
protected $access_token = '';
+ /**
+ * @var string Error key name in _GET options.
+ */
+ protected $errorParam = 'error';
+
+ /**
+ * @var string Error description key name in _GET options.
+ */
+ protected $errorDescriptionParam = 'error_description';
+
+ /**
+ * @var string Error code for access_denied response.
+ */
+ protected $errorAccessDeniedCode = 'access_denied';
+
/**
* Authenticate the user.
*
* @return boolean whether user was successfuly authenticated.
+ * @throws EAuthException
*/
public function authenticate() {
- // user denied error
- if (isset($_GET['error']) && $_GET['error'] == 'access_denied') {
- $this->cancel();
+ if (isset($_GET[$this->errorParam])) {
+ $error_code = $_GET[$this->errorParam];
+ if ($error_code === $this->errorAccessDeniedCode) {
+ // access_denied error (user canceled)
+ $this->cancel();
+ }
+ else {
+ $error = $error_code;
+ if (isset($_GET[$this->errorDescriptionParam])) {
+ $error = $_GET[$this->errorDescriptionParam].' ('.$error.')';
+ }
+ throw new EAuthException($error);
+ }
return false;
}
@@ -100,6 +126,7 @@ abstract class EOAuth2Service extends EAuthServiceBase implements IAuthService {
/**
* Returns the url to request to get OAuth2 access token.
*
+ * @param string $code
* @return string url to request.
*/
protected function getTokenUrl($code) {
diff --git a/EOAuthService.php b/EOAuthService.php
index <HASH>..<HASH> 100644
--- a/EOAuthService.php
+++ b/EOAuthService.php
@@ -68,9 +68,14 @@ abstract class EOAuthService extends EAuthServiceBase implements IAuthService {
* Authenticate the user.
*
* @return boolean whether user was successfuly authenticated.
+ * @throws EAuthException
*/
public function authenticate() {
$this->authenticated = $this->auth->authenticate();
+ $error = $this->auth->getError();
+ if (isset($error)) {
+ throw new EAuthException($error);
+ }
return $this->getIsAuthenticated();
}
diff --git a/EOpenIDService.php b/EOpenIDService.php
index <HASH>..<HASH> 100644
--- a/EOpenIDService.php
+++ b/EOpenIDService.php
@@ -60,6 +60,8 @@ abstract class EOpenIDService extends EAuthServiceBase implements IAuthService {
* Authenticate the user.
*
* @return boolean whether user was successfuly authenticated.
+ * @throws EAuthException
+ * @throws CHttpException
*/
public function authenticate() {
if (!empty($_REQUEST['openid_mode'])) {
diff --git a/services/FacebookOAuthService.php b/services/FacebookOAuthService.php
index <HASH>..<HASH> 100644
--- a/services/FacebookOAuthService.php
+++ b/services/FacebookOAuthService.php
@@ -31,6 +31,9 @@ class FacebookOAuthService extends EOAuth2Service {
'access_token' => 'https://graph.facebook.com/oauth/access_token',
);
+ protected $errorParam = 'error_code';
+ protected $errorDescriptionParam = 'error_message';
+
protected function fetchAttributes() {
$info = (object)$this->makeSignedRequest('https://graph.facebook.com/me');
diff --git a/services/GitHubOAuthService.php b/services/GitHubOAuthService.php
index <HASH>..<HASH> 100644
--- a/services/GitHubOAuthService.php
+++ b/services/GitHubOAuthService.php
@@ -31,6 +31,8 @@ class GitHubOAuthService extends EOAuth2Service {
'access_token' => 'https://github.com/login/oauth/access_token',
);
+ protected $errorAccessDeniedCode = 'user_denied';
+
protected function fetchAttributes() {
$info = (object)$this->makeSignedRequest('https://api.github.com/user');
@@ -56,19 +58,6 @@ class GitHubOAuthService extends EOAuth2Service {
}
/**
- * Authenticate the user.
- *
- * @return boolean whether user was successfuly authenticated.
- */
- public function authenticate() {
- if (isset($_GET['error']) && $_GET['error'] == 'user_denied') {
- $this->cancel();
- }
-
- return parent::authenticate();
- }
-
- /**
* Returns the error info from json.
*
* @param stdClass $json the json response. | Added proper error handling (Fixed #<I>) | Nodge_yii-eauth | train |
ee93134da350c285bb3266eb1f23ad201623eeb5 | diff --git a/PySimpleGUI.py b/PySimpleGUI.py
index <HASH>..<HASH> 100644
--- a/PySimpleGUI.py
+++ b/PySimpleGUI.py
@@ -1,5 +1,5 @@
#!/usr/bin/python3
-version = __version__ = "4.39.1.4 Unreleased\nfix for TCL error when scrolling col element (Jason99020 scores again!), Button error popups with trace when bad images found, addition of size parameter to TabGroup, changed where key gets set for buttons - was causing problems with buttons that set a key explicitly"
+version = __version__ = "4.39.1.5 Unreleased\nfix for TCL error when scrolling col element (Jason99020 scores again!), Button error popups with trace when bad images found, addition of size parameter to TabGroup, changed where key gets set for buttons - was causing problems with buttons that set a key explicitly, fix for grraph drag events that was caused by the realtime button fix"
__version__ = version.split()[0] # For PEP 396 and PEP 345
@@ -23,32 +23,32 @@ port = 'PySimpleGUI'
"""
Copyright 2018, 2019, 2020, 2021 PySimpleGUI
-
+
Before getting into the details, let's talk about the high level goals of the PySimpleGUI project.
-
+
From the inception these have been the project principals upon which it is all built
1. Fun - it's a serious goal of the project. If we're not having FUN while making stuff, then something's not right
2. Successful - you need to be successful or it's all for naught
3. You are the important party - It's your success that determines the success of PySimpleGUI
-
+
If these 3 things are kept at the forefront, then the rest tends to fall into place.
-
+
PySimpleGUI is a "system", not just a program. There are 4 components of the "PySimpleGUI system"
1. This software - PySimpleGUI.com
2. The documentation - PySimpleGUI.org
3. Demo Programs - Demos.PySimpleGUI.org
4. Support - Issues.PySimpleGUI.org
-
-
+
+
This software is available for your use under a LGPL3+ license
-
+
This notice, these first 150 lines of code shall remain unchanged
888 .d8888b. 8888888b. 888 .d8888b.
888 d88P Y88b 888 Y88b 888 d88P Y88b
- 888 888 888 888 888 888 .d88P
+ 888 888 888 888 888 888 .d88P
888 888 888 d88P 888 8888" 888
888 888 88888 8888888P" 888 "Y8b. 8888888
888 888 888 888 888 888 888 888
@@ -2457,7 +2457,7 @@ class Spin(Element):
key = key if key is not None else k
sz = size if size != (None, None) else s
- super().__init__(ELEM_TYPE_INPUT_SPIN, size, auto_size_text, font=font, background_color=bg, text_color=fg,
+ super().__init__(ELEM_TYPE_INPUT_SPIN, size=sz, auto_size_text=auto_size_text, font=font, background_color=bg, text_color=fg,
key=key, pad=pad, tooltip=tooltip, visible=visible, metadata=metadata)
return
@@ -5031,7 +5031,7 @@ class Graph(Element):
Draw some text on your graph. This is how you label graph number lines for example
:param text: text to display
- :type text: (str)
+ :type text: (Any)
:param location: location to place first letter
:type location: Tuple[int, int] | Tuple[float, float]
:param color: text color
@@ -8436,7 +8436,10 @@ Normally a tuple, but can be a simplified-dual-color-string "foreground on backg
# if the last button clicked was realtime, emulate a read non-blocking
# the idea is to quickly return realtime buttons without any blocks until released
if self.LastButtonClickedWasRealtime:
- # self.LastButtonClickedWasRealtime = False # stops from generating events until something changes
+ # clear the realtime flag if the element is not a button element (for example a graph element that is dragging)
+ if self.AllKeysDict and self.AllKeysDict.get(self.LastButtonClicked, None):
+ if self.AllKeysDict.get(self.LastButtonClicked).Type != ELEM_TYPE_BUTTON:
+ self.LastButtonClickedWasRealtime = False # stops from generating events until something changes
try:
rc = self.TKroot.update()
@@ -9764,7 +9767,7 @@ def read_all_windows(timeout=None, timeout_key=TIMEOUT_KEY):
:param timeout: Time in milliseconds to delay before a returning a timeout event
:type timeout: (int)
- :param ti```meout_key: Key to return when a timeout happens. Defaults to the standard TIMEOUT_KEY
+ :param timeout_key: Key to return when a timeout happens. Defaults to the standard TIMEOUT_KEY
:type timeout_key: (Any)
:return: A tuple with the (Window, event, values dictionary/list)
:rtype: Tuple[Window, Any, (Dict or List)]
@@ -17291,6 +17294,7 @@ def popup_menu(window, element, menu_def, title=None, location=(None, None)):
:param location: The location on the screen to place the window
:type location: (int, int) | (None, None)
"""
+
element._popup_menu_location = location
top_menu = tk.Menu(window.TKroot, tearoff=True, tearoffcommand=element._tearoff_menu_callback)
if window.right_click_menu_background_color not in (COLOR_SYSTEM_DEFAULT, None):
@@ -17305,7 +17309,7 @@ def popup_menu(window, element, menu_def, title=None, location=(None, None)):
top_menu.config(activeforeground=window.right_click_menu_selected_colors[0])
if window.right_click_menu_selected_colors[1] != COLOR_SYSTEM_DEFAULT:
top_menu.config(activebackground=window.right_click_menu_selected_colors[1])
- top_menu.config(title=window.Title)
+ top_menu.config(title=window.Title if title is None else title)
AddMenuItem(top_menu, menu_def[1], element, right_click_menu=True)
# element.Widget.bind('<Button-3>', element._RightClickMenuCallback)
top_menu.invoke(0) | Fix for Graph Element dragging complete that was caused when the RealtimeButton problem was fixed. Title parameter for popup_menu now correctly used | PySimpleGUI_PySimpleGUI | train |
611415c2b93ba2bdac7e426da403016ffc02e759 | diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -28,7 +28,8 @@ MOCK_MODULES = [
"gi.repository", "dbus.mainloop.glib", "dbus",
"pywapi", "basiciw",
"i3pystatus.pulseaudio.pulse",
- "notmuch"
+ "notmuch",
+ "requests",
]
for mod_name in MOCK_MODULES: | docs/conf.py | enkore_i3pystatus | train |
ad4a27ad2b27d05708217e5b34f4daddedf4fa7f | diff --git a/HARK/ConsumptionSaving/ConsLaborModel.py b/HARK/ConsumptionSaving/ConsLaborModel.py
index <HASH>..<HASH> 100644
--- a/HARK/ConsumptionSaving/ConsLaborModel.py
+++ b/HARK/ConsumptionSaving/ConsLaborModel.py
@@ -545,6 +545,8 @@ if __name__ == '__main__':
LifecycleExample.track_vars = ['mNrmNow','cNrmNow','pLvlNow','t_age']
LifecycleExample.initializeSim()
LifecycleExample.simulate()
+# plt.plot(np.linspace(0, 5, 10000), LifecycleExample.cNrmNow_hist[30])
+# plt.show()
###############################################################################
@@ -616,4 +618,6 @@ if __name__ == '__main__':
LaborIntMargExample.track_vars = ['bNrmNow', 'cNrmNow']
LaborIntMargExample.initializeSim()
LaborIntMargExample.simulate()
+# plt.plot(np.linspace(0,100,10000), LaborIntMargExample.cNrmNow_hist[30])
+# plt.show()
\ No newline at end of file | Spend some time on the simulation again but still not able to fully understand the getControls() method and the consumption function in the Labor model, but the plot seems to make sense, please review on this.
I am pretty certain that the ConsumerParameters.py file is fine. | econ-ark_HARK | train |
6d1d494c33960fa9ca7156007ee970198bcdd0bc | diff --git a/src/main/java/com/wrapper/spotify/objects/ReleaseDatePrecision.java b/src/main/java/com/wrapper/spotify/objects/ReleaseDatePrecision.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/wrapper/spotify/objects/ReleaseDatePrecision.java
+++ b/src/main/java/com/wrapper/spotify/objects/ReleaseDatePrecision.java
@@ -2,9 +2,9 @@ package com.wrapper.spotify.objects;
public enum ReleaseDatePrecision {
- year("year"),
- month("month"),
- day("day");
+ YEAR("year"),
+ MONTH("month"),
+ DAY("day");
public final String precision; | Capitalization
+ Capitalized enum names | thelinmichael_spotify-web-api-java | train |
67de0af60485b4da45d015e9a1dfad5439d5fca2 | diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -32,12 +32,12 @@ module ActionView
# form_tag('/upload', :multipart => true)
# # => <form action="/upload" method="post" enctype="multipart/form-data">
#
- # <% form_tag('/posts')do -%>
+ # <%= form_tag('/posts')do -%>
# <div><%= submit_tag 'Save' %></div>
# <% end -%>
# # => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
#
- # <% form_tag('/posts', :remote => true) %>
+ # <%= form_tag('/posts', :remote => true) %>
# # => <form action="/posts" method="post" data-remote="true">
#
def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)
@@ -425,17 +425,17 @@ module ActionView
# <tt>options</tt> accept the same values as tag.
#
# ==== Examples
- # <% field_set_tag do %>
+ # <%= field_set_tag do %>
# <p><%= text_field_tag 'name' %></p>
# <% end %>
# # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
#
- # <% field_set_tag 'Your details' do %>
+ # <%= field_set_tag 'Your details' do %>
# <p><%= text_field_tag 'name' %></p>
# <% end %>
# # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
#
- # <% field_set_tag nil, :class => 'format' do %>
+ # <%= field_set_tag nil, :class => 'format' do %>
# <p><%= text_field_tag 'name' %></p>
# <% end %>
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset> | Updated documentation for block helpers in form_tag_helper.rb | rails_rails | train |
9e316fd4710efb8205c4fdda750e5bc85e897722 | diff --git a/custodian/qchem/jobs.py b/custodian/qchem/jobs.py
index <HASH>..<HASH> 100644
--- a/custodian/qchem/jobs.py
+++ b/custodian/qchem/jobs.py
@@ -277,7 +277,7 @@ class QchemJob(Job):
sub_out = sub_out_file_object.readlines()
out_file_object.writelines(header_lines)
out_file_object.writelines(sub_out)
- if rc < 0:
+ if rc < 0 and rc != -99999:
out_file_object.writelines(["Application {} exit codes: {}\n".format(qc_jobid, rc)])
if log_file_object:
with open(sub_log_filename) as sub_log_file_object: | return code -<I> is just an indication I didn't find the exit code and shouldn't be appended to the output file | materialsproject_custodian | train |
66f8997671c41278a4045ca6c3e3a19c8175a7ed | diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -380,6 +380,10 @@ module ActionDispatch # :nodoc:
def to_path
@response.stream.to_path
end
+
+ def to_ary
+ nil
+ end
end
def rack_response(status, header)
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -1,4 +1,6 @@
require 'abstract_unit'
+require 'timeout'
+require 'rack/content_length'
class ResponseTest < ActiveSupport::TestCase
def setup
@@ -238,6 +240,18 @@ class ResponseTest < ActiveSupport::TestCase
end
end
+ test "compatibility with Rack::ContentLength" do
+ @response.body = 'Hello'
+ app = lambda { |env| @response.to_a }
+ env = Rack::MockRequest.env_for("/")
+
+ status, headers, body = app.call(env)
+ assert_nil headers['Content-Length']
+
+ status, headers, body = Rack::ContentLength.new(app).call(env)
+ assert_equal '5', headers['Content-Length']
+ end
+
test "implicit destructuring and Array conversion is deprecated" do
response = ActionDispatch::Response.new(404, { 'Content-Type' => 'text/plain' }, ['Not Found']) | Add support for Rack::ContentLength middelware | rails_rails | train |
734368d7e510e96a4edca28f3025270c3a7996cf | diff --git a/src/spec/shared/support/api_helpers.rb b/src/spec/shared/support/api_helpers.rb
index <HASH>..<HASH> 100644
--- a/src/spec/shared/support/api_helpers.rb
+++ b/src/spec/shared/support/api_helpers.rb
@@ -40,8 +40,8 @@ module Support
def build_director_api_url(url_path, query)
director_url = URI(current_sandbox.director_url)
- director_url.path = URI.encode_www_form_component(url_path)
- director_url.query = URI.encode_www_form_component(query)
+ director_url.path = url_path
+ director_url.query = query
return director_url
end
end | Don't encode query and path in api helper
There is no need to escape input since this code is
only used in our own integration tests so the source can be trusted.
Alternativly we could in the future change query to be a hash and
escape using URI.encode_www_form, but this would mean we have to find
all callers of this method.
[#<I>] | cloudfoundry_bosh | train |
a6bc78e607b889eaa643520409bc6df0e61d5691 | diff --git a/packages/@vue/cli-service/lib/commands/serve.js b/packages/@vue/cli-service/lib/commands/serve.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-service/lib/commands/serve.js
+++ b/packages/@vue/cli-service/lib/commands/serve.js
@@ -2,8 +2,7 @@ const {
info,
error,
hasYarn,
- openBrowser,
- clearConsole
+ openBrowser
} = require('@vue/cli-shared-utils')
const defaults = {
@@ -25,7 +24,6 @@ module.exports = (api, options) => {
'--https': `use https (default: ${defaults.https})`
}
}, args => {
- clearConsole()
info('Starting development server...')
api.setMode(args.mode || defaults.mode) | chore: do not clear screen when serving so that warnings can be seen | vuejs_vue-cli | train |
b15cd069a83443be3154b719d0cc9fe8117f09fb | diff --git a/bcache/get.go b/bcache/get.go
index <HASH>..<HASH> 100644
--- a/bcache/get.go
+++ b/bcache/get.go
@@ -61,7 +61,7 @@ func dehumanize(hbytes []byte) (uint64, error) {
mul := float64(1)
var (
mant float64
- err error
+ err error
)
// If lastByte is beyond the range of ASCII digits, it must be a
// multiplier.
@@ -93,7 +93,7 @@ func dehumanize(hbytes []byte) (uint64, error) {
'Z': ZiB,
'Y': YiB,
}
- mul = float64(multipliers[rune(lastByte)])
+ mul = multipliers[rune(lastByte)]
mant, err = parsePseudoFloat(string(hbytes))
if err != nil {
return 0, err
@@ -139,10 +139,10 @@ func (p *parser) readValue(fileName string) uint64 {
}
// ParsePriorityStats parses lines from the priority_stats file.
-func parsePriorityStats(line string, ps *PriorityStats) (error) {
+func parsePriorityStats(line string, ps *PriorityStats) error {
var (
value uint64
- err error
+ err error
)
switch {
case strings.HasPrefix(line, "Unused:"):
diff --git a/bcache/get_test.go b/bcache/get_test.go
index <HASH>..<HASH> 100644
--- a/bcache/get_test.go
+++ b/bcache/get_test.go
@@ -14,8 +14,8 @@
package bcache
import (
- "testing"
"math"
+ "testing"
)
func TestDehumanizeTests(t *testing.T) {
@@ -45,8 +45,8 @@ func TestDehumanizeTests(t *testing.T) {
out: 2024,
},
{
- in: []byte(""),
- out: 0,
+ in: []byte(""),
+ out: 0,
invalid: true,
},
}
@@ -59,7 +59,7 @@ func TestDehumanizeTests(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
if got != tst.out {
- t.Errorf("dehumanize: '%s', want %f, got %f", tst.in, tst.out, got)
+ t.Errorf("dehumanize: '%s', want %d, got %d", tst.in, tst.out, got)
}
}
}
@@ -84,7 +84,7 @@ func TestParsePseudoFloatTests(t *testing.T) {
}
for _, tst := range parsePseudoFloatTests {
got, err := parsePseudoFloat(tst.in)
- if err != nil || math.Abs(got - tst.out) > 0.0001 {
+ if err != nil || math.Abs(got-tst.out) > 0.0001 {
t.Errorf("parsePseudoFloat: %s, want %f, got %f", tst.in, tst.out, got)
}
}
@@ -92,23 +92,23 @@ func TestParsePseudoFloatTests(t *testing.T) {
func TestPriorityStats(t *testing.T) {
var want = PriorityStats{
- UnusedPercent: 99,
+ UnusedPercent: 99,
MetadataPercent: 5,
}
var (
- in string
+ in string
gotErr error
- got PriorityStats
+ got PriorityStats
)
in = "Metadata: 5%"
gotErr = parsePriorityStats(in, &got)
if gotErr != nil || got.MetadataPercent != want.MetadataPercent {
- t.Errorf("parsePriorityStats: '%s', want %f, got %f", in, want.MetadataPercent, got.MetadataPercent)
+ t.Errorf("parsePriorityStats: '%s', want %d, got %d", in, want.MetadataPercent, got.MetadataPercent)
}
in = "Unused: 99%"
gotErr = parsePriorityStats(in, &got)
if gotErr != nil || got.UnusedPercent != want.UnusedPercent {
- t.Errorf("parsePriorityStats: '%s', want %f, got %f", in, want.UnusedPercent, got.UnusedPercent)
+ t.Errorf("parsePriorityStats: '%s', want %d, got %d", in, want.UnusedPercent, got.UnusedPercent)
}
} | bcache: fix vet and unconvert issues. (#<I>) | prometheus_procfs | train |
434579c78edadc0ca918c24589c01c3ec62903b4 | diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/security/GroupRoleCheckTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/security/GroupRoleCheckTests.java
index <HASH>..<HASH> 100644
--- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/security/GroupRoleCheckTests.java
+++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/security/GroupRoleCheckTests.java
@@ -1,11 +1,10 @@
package org.cloudfoundry.identity.uaa.scim.security;
-import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication;
import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal;
import org.cloudfoundry.identity.uaa.constants.OriginKeys;
import org.cloudfoundry.identity.uaa.scim.ScimGroupMember;
import org.cloudfoundry.identity.uaa.scim.ScimGroupMembershipManager;
-import org.junit.Before;
+import org.junit.After;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.Authentication;
@@ -26,9 +25,9 @@ import static org.mockito.Mockito.when;
*/
public class GroupRoleCheckTests {
- @Before
- public void SetUp() {
-
+ @After
+ public void cleanUp() {
+ SecurityContextHolder.clearContext();
}
@Test | Clear security context after a test that mocks it | cloudfoundry_uaa | train |
6a401805b3ffcf9ee3be2cdd3c1e870a70b8b7b4 | diff --git a/modules/images.js b/modules/images.js
index <HASH>..<HASH> 100644
--- a/modules/images.js
+++ b/modules/images.js
@@ -10,7 +10,6 @@ module.exports = function(grunt, util, config) {
var glob = require('glob');
var _ = require('lodash');
- var pngquant = util.npmRequire('imagemin-pngquant');
var dirs = util.setupDirs({
srcParam: 'imagesSrc',
@@ -28,6 +27,8 @@ module.exports = function(grunt, util, config) {
return config;
}
+ var pngquant = util.npmRequire('imagemin-pngquant');
+
var localConfig = {
imagemin: {
options: { | Do not require pngquant if there are no images. | tamiadev_tamia-grunt | train |
bc75eb10bc286213797698bf86b46aac9524c6d3 | diff --git a/management_api.go b/management_api.go
index <HASH>..<HASH> 100644
--- a/management_api.go
+++ b/management_api.go
@@ -73,40 +73,44 @@ func (e *Enforcer) HasPolicy(params ...interface{}) bool {
}
// AddPolicy adds an authorization rule to the current policy.
-// If you try to add an existing policy, the call fails and returns false.
+// If the rule already exists, the call fails and returns false, otherwise returns true.
func (e *Enforcer) AddPolicy(params ...interface{}) bool {
- res := false
+ alreadyExisted := false
if len(params) == 1 && reflect.TypeOf(params[0]).Kind() == reflect.Slice {
- res = e.addPolicy("p", "p", params[0].([]string))
+ alreadyExisted = e.addPolicy("p", "p", params[0].([]string))
} else {
policy := make([]string, 0)
for _, param := range params {
policy = append(policy, param.(string))
}
- res = e.addPolicy("p", "p", policy)
+ alreadyExisted = e.addPolicy("p", "p", policy)
}
- return res
+ return alreadyExisted
}
// RemovePolicy removes an authorization rule from the current policy.
-func (e *Enforcer) RemovePolicy(params ...interface{}) {
+func (e *Enforcer) RemovePolicy(params ...interface{}) bool {
+ ruleRemoved := false
if len(params) == 1 && reflect.TypeOf(params[0]).Kind() == reflect.Slice {
- e.removePolicy("p", "p", params[0].([]string))
+ ruleRemoved = e.removePolicy("p", "p", params[0].([]string))
} else {
policy := make([]string, 0)
for _, param := range params {
policy = append(policy, param.(string))
}
- e.removePolicy("p", "p", policy)
+ ruleRemoved = e.removePolicy("p", "p", policy)
}
+
+ return ruleRemoved
}
// RemoveFilteredPolicy removes an authorization rule from the current policy, field filters can be specified.
-func (e *Enforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) {
- e.removeFilteredPolicy("p", "p", fieldIndex, fieldValues...)
+func (e *Enforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) bool {
+ ruleRemoved := e.removeFilteredPolicy("p", "p", fieldIndex, fieldValues...)
+ return ruleRemoved
}
// HasGroupingPolicy determines whether a role inheritance rule exists.
@@ -124,44 +128,47 @@ func (e *Enforcer) HasGroupingPolicy(params ...interface{}) bool {
}
// AddGroupingPolicy adds a role inheritance rule to the current policy.
-// If you try to add an existing policy, the call fails and returns false.
+// If the rule already exists, the call fails and returns false, otherwise returns true.
func (e *Enforcer) AddGroupingPolicy(params ...interface{}) bool {
- res := false
+ alreadyExisted := false
if len(params) == 1 && reflect.TypeOf(params[0]).Kind() == reflect.Slice {
- res = e.addPolicy("g", "g", params[0].([]string))
+ alreadyExisted = e.addPolicy("g", "g", params[0].([]string))
} else {
policy := make([]string, 0)
for _, param := range params {
policy = append(policy, param.(string))
}
- res = e.addPolicy("g", "g", policy)
+ alreadyExisted = e.addPolicy("g", "g", policy)
}
e.model.BuildRoleLinks()
- return res
+ return alreadyExisted
}
// RemoveGroupingPolicy removes a role inheritance rule from the current policy.
-func (e *Enforcer) RemoveGroupingPolicy(params ...interface{}) {
+func (e *Enforcer) RemoveGroupingPolicy(params ...interface{}) bool {
+ ruleRemoved := false
if len(params) == 1 && reflect.TypeOf(params[0]).Kind() == reflect.Slice {
- e.removePolicy("g", "g", params[0].([]string))
+ ruleRemoved = e.removePolicy("g", "g", params[0].([]string))
} else {
policy := make([]string, 0)
for _, param := range params {
policy = append(policy, param.(string))
}
- e.removePolicy("g", "g", policy)
+ ruleRemoved = e.removePolicy("g", "g", policy)
}
e.model.BuildRoleLinks()
+ return ruleRemoved
}
// RemoveFilteredGroupingPolicy removes a role inheritance rule from the current policy, field filters can be specified.
-func (e *Enforcer) RemoveFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) {
- e.removeFilteredPolicy("g", "g", fieldIndex, fieldValues...)
+func (e *Enforcer) RemoveFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) bool {
+ ruleRemoved := e.removeFilteredPolicy("g", "g", fieldIndex, fieldValues...)
e.model.BuildRoleLinks()
+ return ruleRemoved
}
// AddFunction adds a customized function. | Return whether any rule is deleted for the series of RemovePolicy() functions in Management API. | casbin_casbin | train |
ceac98fc96c3ee34baf6e4973576e4bcf072a437 | diff --git a/src/main/java/org/jboss/virtual/spi/zip/jzipfile/JZipFileZipEntry.java b/src/main/java/org/jboss/virtual/spi/zip/jzipfile/JZipFileZipEntry.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/virtual/spi/zip/jzipfile/JZipFileZipEntry.java
+++ b/src/main/java/org/jboss/virtual/spi/zip/jzipfile/JZipFileZipEntry.java
@@ -77,7 +77,7 @@ public class JZipFileZipEntry implements ZipEntry
public long getCrc()
{
- return entry.getCrc32();
+ return entry.getCrc32() & 0xffffffffL;
}
public void setCrc(long crc) | Fix directory detection, CRC calc (resolves some tests) | jbossas_jboss-vfs | train |
6420a5605b963a7b9533cfe435db102c46f45bfb | diff --git a/src/Psalm/Internal/Analyzer/TypeAnalyzer.php b/src/Psalm/Internal/Analyzer/TypeAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Internal/Analyzer/TypeAnalyzer.php
+++ b/src/Psalm/Internal/Analyzer/TypeAnalyzer.php
@@ -1225,7 +1225,8 @@ class TypeAnalyzer
return null;
}
- private static function getCallableMethodIdFromObjectLike(ObjectLike $input_type_part) : ?string
+ /** @return ?string */
+ private static function getCallableMethodIdFromObjectLike(ObjectLike $input_type_part)
{
if (!isset($input_type_part->properties[0])
|| !isset($input_type_part->properties[1]) | Put nullable in docblock for PHP <I> | vimeo_psalm | train |
f2702bd2c9f2cfcbf6a210598a6fe537550cac26 | diff --git a/src/animation.js b/src/animation.js
index <HASH>..<HASH> 100644
--- a/src/animation.js
+++ b/src/animation.js
@@ -305,7 +305,7 @@ export class Animation {
if (!isNaN(firstValue)) {
// simple number
- this.value = easingFunction(progress, from, to, 1)
+ this.value = easingFunction(progress, from, to, 1, this.getPointDuration() * this.duration)
} else if (typeof firstValue === 'string') {
this.value = from
} else {
@@ -313,7 +313,7 @@ export class Animation {
this.value = {}
for (let prop in firstValue) {
if (isNaN(firstValue[prop])) continue
- this.value[prop] = easingFunction(progress, from[prop], to[prop], 1)
+ this.value[prop] = easingFunction(progress, from[prop], to[prop], 1, this.getPointDuration() * this.duration)
}
}
} | pass duration to easing function for animation | madjam002_specular | train |
0ba889a3917a7a15e10fb941cd49b6c72292519f | diff --git a/pyjade/runtime.py b/pyjade/runtime.py
index <HASH>..<HASH> 100644
--- a/pyjade/runtime.py
+++ b/pyjade/runtime.py
@@ -49,17 +49,17 @@ def escape(s):
def attrs (attrs=[],terse=False, undefined=None):
buf = []
if bool(attrs):
- buf.append('')
+ buf.append(u'')
for k,v in attrs:
if undefined is not None and isinstance(v, undefined):
continue
if v!=None and (v!=False or type(v)!=bool):
if k=='class' and isinstance(v, (list, tuple)):
- v = ' '.join(map(str,flatten(v)))
+ v = u' '.join(map(str,flatten(v)))
t = v==True and type(v)==bool
if t and not terse: v=k
- buf.append('%s'%k if terse and t else '%s="%s"'%(k,v))
- return ' '.join(buf)
+ buf.append(u'%s'%k if terse and t else u'%s="%s"'%(k,v))
+ return u' '.join(buf)
def is_mapping(value):
return isinstance(value, MappingType) | Use unicode literals in runtime function attrs().
This resolves issue #<I>. | syrusakbary_pyjade | train |
9e1a5413d2b7c28955a2f89978d50201c8fc17b5 | diff --git a/concrete/config/concrete.php b/concrete/config/concrete.php
index <HASH>..<HASH> 100644
--- a/concrete/config/concrete.php
+++ b/concrete/config/concrete.php
@@ -6,8 +6,8 @@ return [
*
* @var string
*/
- 'version' => '8.5.1',
- 'version_installed' => '8.5.1',
+ 'version' => '8.5.2a1',
+ 'version_installed' => '8.5.2a1',
'version_db' => '20190301133300', // the key of the latest database migration
/* | Updating version number to <I>a1 | concrete5_concrete5 | train |
ac7ea89371827c7bcc96cd0e5fc8ab495c22fdb0 | diff --git a/bosh_cli/lib/cli/runner.rb b/bosh_cli/lib/cli/runner.rb
index <HASH>..<HASH> 100644
--- a/bosh_cli/lib/cli/runner.rb
+++ b/bosh_cli/lib/cli/runner.rb
@@ -25,6 +25,9 @@ module Bosh::Cli
@option_parser = OptionParser.new(banner)
Config.colorize = nil
+ if ENV.has_key? "BOSH_COLOR"
+ Config.colorize = ENV["BOSH_COLOR"] == "false"
+ end
Config.output ||= STDOUT
parse_global_options | Support BOSH_COLOR env var for implicit --no-color
If BOSH_COLOR is set to the string "false", then the `bosh' utility will
behave as if the `--no-color` option has been set. This behavior can be
overridden by also passing `--color` (which takes precedence)
If BOSH_COLOR is not set, or has any other value, the previous default
behavior holds (only do color if we are hooked up to a terminal) | cloudfoundry_bosh | train |
9f951cec7b6b9af327530c6e1f0453801e5d4666 | diff --git a/ratelimitbackend/backends.py b/ratelimitbackend/backends.py
index <HASH>..<HASH> 100644
--- a/ratelimitbackend/backends.py
+++ b/ratelimitbackend/backends.py
@@ -22,7 +22,7 @@ class RateLimitMixin(object):
def authenticate(self, **kwargs):
request = kwargs.pop('request', None)
- username = kwargs.get(self.username_key)
+ username = kwargs[self.username_key]
if request is not None:
counts = self.get_counters(request)
if sum(counts.values()) >= self.requests: | Require correct username_key for custom backend | brutasse_django-ratelimit-backend | train |
b2db02ca4a0f0c74a47752ba75dba28c37a97579 | diff --git a/examples/issue-managed-tokens/issue-managed-tokens.js b/examples/issue-managed-tokens/issue-managed-tokens.js
index <HASH>..<HASH> 100644
--- a/examples/issue-managed-tokens/issue-managed-tokens.js
+++ b/examples/issue-managed-tokens/issue-managed-tokens.js
@@ -11,10 +11,10 @@ const NETWORK = `testnet`
// This is the WH propertyId of the token that this program will be creating
// new tokens for.
-const PROPERTY_ID = 460
+const PROPERTY_ID = 196
// The quantity of new tokens to issue.
-const TOKEN_QTY = 2345
+const TOKEN_QTY = 1000000
// Instantiate Wormhole based on the network.
let Wormhole
diff --git a/examples/send-tokens/send-tokens.js b/examples/send-tokens/send-tokens.js
index <HASH>..<HASH> 100644
--- a/examples/send-tokens/send-tokens.js
+++ b/examples/send-tokens/send-tokens.js
@@ -3,12 +3,12 @@
*/
// Set NETWORK to either testnet or mainnet
-const NETWORK = `mainnet`
+const NETWORK = `testnet`
// Change these values to match your token.
-const RECV_ADDR = "qz6svmakwcvh0c8smqp2jmu73cq88latyvnevx6ctp"
-const propertyId = 200 // WH ID identifying the token. 1 === WHC.
-const TOKEN_QTY = 1 // Number of tokens to send.
+const RECV_ADDR = "bchtest:qz9tlxnmmwprc9ursnuah86n9esl77dez5ewtf8ewy"
+const propertyId = 196 // WH ID identifying the token. 1 === WHC.
+const TOKEN_QTY = 500000 // Number of tokens to send.
const WH = require("../../lib/Wormhole").default | Switched managed token scripts to testnet | Bitcoin-com_wormhole-sdk | train |
93c95473722a70ead2e98a1848853b7c03cefa8c | diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100755
--- a/manifest.php
+++ b/manifest.php
@@ -53,7 +53,7 @@ return [
'taoQtiItem' => '>=20.0.2',
'taoTests' => '>=13.2.0',
'tao' => '>=41.1.0',
- 'generis' => '>=12.5.0',
+ 'generis' => '>=12.15.0',
'taoDelivery' => '>=13.3.0',
'taoItems' => '>=6.0.0',
], | dependency generis <I>. Removed some assertTrue from risky tests. | oat-sa_extension-tao-testqti | train |
a24be376219761995b41a1b5d92276548f7889c8 | diff --git a/app/controllers/api/v1/conversations_controller.rb b/app/controllers/api/v1/conversations_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/api/v1/conversations_controller.rb
+++ b/app/controllers/api/v1/conversations_controller.rb
@@ -15,10 +15,20 @@ class Api::V1::ConversationsController < ApplicationController
def create
@app = App.find_by(key: params[:app_id])
- @conversation = @app.start_conversation({
- message: params[:message],
- from: find_user(params[:email])
- })
+ user = find_user(params[:email])
+ if params[:message].present?
+ @conversation = @app.start_conversation({
+ message: params[:message],
+ from: user
+ })
+ else
+ # return a conversation with empty messages , if any or create new one
+ # this is to avoid multiple empty convos
+ @conversation = user.conversations
+ .left_joins(:messages)
+ .where(conversation_parts: {id: nil}).first ||
+ @app.conversations.create(main_participant: user)
+ end
render :show
end
diff --git a/app/javascript/components2/messenger.js b/app/javascript/components2/messenger.js
index <HASH>..<HASH> 100644
--- a/app/javascript/components2/messenger.js
+++ b/app/javascript/components2/messenger.js
@@ -318,7 +318,7 @@ class Messenger extends Component {
constructor(props){
super(props)
this.state = {
- conversation: null,
+ conversation: {},
conversation_messages: [],
conversations: [],
display_mode: "conversations",
@@ -342,8 +342,11 @@ class Messenger extends Component {
}
componentDidUpdate(prevProps, prevState){
- if(prevState.display_mode !== this.state.display_mode)
+ if(prevState.display_mode !== this.state.display_mode && this.display_mode === "conversations")
this.getConversations()
+
+ if(this.state.conversation.id !== prevState.conversation.id)
+ this.conversationSubscriber()
}
eventsSubscriber(){
@@ -397,7 +400,6 @@ class Messenger extends Component {
console.log("connected to conversations")
},
disconnected: ()=> {
- alert("disconnected")
console.log("disconnected from conversations")
},
received: (data)=> {
@@ -441,7 +443,7 @@ class Messenger extends Component {
// for now let's save in html
const html_comment = convertToHTML( comment );
- if(this.state.conversation){
+ if(this.state.conversation.id){
this.createComment(html_comment, cb)
}else{
this.createCommentOnNewConversation(html_comment, cb)
@@ -513,10 +515,11 @@ class Messenger extends Component {
displayNewConversation(e){
e.preventDefault()
- this.setState({
- conversation: null,
- conversation_messages: [],
- display_mode: "conversation"
+ this.createCommentOnNewConversation(null, ()=>{
+ this.setState({
+ conversation_messages: [],
+ display_mode: "conversation"
+ })
})
}
@@ -535,8 +538,8 @@ class Messenger extends Component {
this.setState({
display_mode: "conversation"
}, ()=> {
- this.conversationSubscriber() ;
- this.getConversations() ;
+ //this.conversationSubscriber() ;
+ //this.getConversations() ;
this.scrollToLastItem()
})
})
@@ -612,11 +615,10 @@ class Messenger extends Component {
<CommentsWrapper>
{
this.state.conversations.map((o,i)=>{
- console.log("this", this)
- const t = this
+
const message = o.last_message
return <CommentsItem key={o.id}
- onClick={(e)=>{t.displayConversation(e, o)}}>
+ onClick={(e)=>{this.displayConversation(e, o)}}>
{
message ?
diff --git a/app/models/app.rb b/app/models/app.rb
index <HASH>..<HASH> 100644
--- a/app/models/app.rb
+++ b/app/models/app.rb
@@ -36,7 +36,7 @@ class App < ApplicationRecord
end
def add_visit(opts={})
- ap_user = add_user(opts)
+ add_user(opts)
end
def start_conversation(options)
diff --git a/app/models/app_user.rb b/app/models/app_user.rb
index <HASH>..<HASH> 100644
--- a/app/models/app_user.rb
+++ b/app/models/app_user.rb
@@ -6,6 +6,7 @@ class AppUser < ApplicationRecord
belongs_to :user
belongs_to :app
+ has_many :conversations, foreign_key: :main_participant_id
has_many :metrics , as: :trackable
store_accessor :properties, [ :name, :first_name, :last_name, :country ]
scope :availables, ->{
@@ -13,6 +14,7 @@ class AppUser < ApplicationRecord
"passive", "subscribed"])
}
+
delegate :email, to: :user
def as_json(options = nil)
diff --git a/app/models/user.rb b/app/models/user.rb
index <HASH>..<HASH> 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -4,7 +4,7 @@ class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
- has_many :app_user
+ has_many :app_users
has_many :roles
has_many :apps, through: :roles, source: :app | handle new conversation, view / channel / controller | michelson_chaskiq | train |
89336c298c1cef2919dd438a03d7952a20688167 | diff --git a/photon/datastores_test.go b/photon/datastores_test.go
index <HASH>..<HASH> 100644
--- a/photon/datastores_test.go
+++ b/photon/datastores_test.go
@@ -10,72 +10,66 @@
package photon
import (
- "github.com/onsi/ginkgo"
- "github.com/onsi/gomega"
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
"github.com/vmware/photon-controller-go-sdk/photon/internal/mocks"
)
-var _ = ginkgo.Describe("Datastores", func() {
+var _ = Describe("Datastores", func() {
var (
- server *mocks.Server
- client *Client
+ server *mocks.Server
+ client *Client
+ datastoreSpec *Datastore
)
- ginkgo.BeforeEach(func() {
+ BeforeEach(func() {
server, client = testSetup()
+
+ datastoreId := "1234"
+ datastoreSpec = &Datastore{
+ Kind: "datastore",
+ Type: "LOCAL_VMFS",
+ ID: datastoreId,
+ SelfLink: "https://192.0.0.2" + rootUrl + "/infrastructure/datastores/" + datastoreId,
+ }
})
- ginkgo.AfterEach(func() {
+ AfterEach(func() {
server.Close()
})
- ginkgo.Describe("Get", func() {
- ginkgo.It("Get a single datastore successfully", func() {
- kind := "datastore"
- datastoreType := "LOCAL_VMFS"
- datastoreID := "1234"
- server.SetResponseJson(200,
- Datastore{
- Kind: kind,
- Type: datastoreType,
- ID: datastoreID,
- SelfLink: "https://192.0.0.2/infrastructure/datastores/1234",
- })
+ Describe("Get", func() {
+ It("Get a single datastore successfully", func() {
+
+ server.SetResponseJson(200, datastoreSpec)
+
+ datastore, err := client.Datastores.Get(datastoreSpec.ID)
+ GinkgoT().Log(err)
- datastore, err := client.Datastores.Get("1234")
- ginkgo.GinkgoT().Log(err)
+ Expect(err).Should(BeNil())
+ Expect(datastore).ShouldNot(BeNil())
+ Expect(datastore.Kind).Should(Equal(datastoreSpec.Kind))
+ Expect(datastore.Type).Should(Equal(datastoreSpec.Type))
+ Expect(datastore.ID).Should(Equal(datastoreSpec.ID))
- gomega.Expect(err).Should(gomega.BeNil())
- gomega.Expect(datastore).ShouldNot(gomega.BeNil())
- gomega.Expect(datastore.Kind).Should(gomega.Equal(kind))
- gomega.Expect(datastore.Type).Should(gomega.Equal(datastoreType))
- gomega.Expect(datastore.ID).Should(gomega.Equal(datastoreID))
})
})
- ginkgo.Describe("GetAll", func() {
- ginkgo.It("Get all datastores successfully", func() {
- kind := "datastore"
- datastoreType := "LOCAL_VMFS"
- datastoreID := "1234"
- datastore := Datastore{
- Kind: kind,
- Type: datastoreType,
- ID: datastoreID,
- SelfLink: "https://192.0.0.2/infrastructure/datastores/1234",
- }
+ Describe("GetAll", func() {
+ It("Get all datastores successfully", func() {
datastoresExpected := Datastores{
- Items: []Datastore{datastore},
+ Items: []Datastore{*datastoreSpec},
}
+
server.SetResponseJson(200, datastoresExpected)
datastores, err := client.Datastores.GetAll()
- ginkgo.GinkgoT().Log(err)
+ GinkgoT().Log(err)
- gomega.Expect(err).Should(gomega.BeNil())
- gomega.Expect(datastores).ShouldNot(gomega.BeNil())
- gomega.Expect(datastores.Items[0].Kind).Should(gomega.Equal(kind))
- gomega.Expect(datastores.Items[0].Type).Should(gomega.Equal(datastoreType))
- gomega.Expect(datastores.Items[0].ID).Should(gomega.Equal(datastoreID))
+ Expect(err).Should(BeNil())
+ Expect(datastores).ShouldNot(BeNil())
+ Expect(datastores.Items[0].Kind).Should(Equal(datastoreSpec.Kind))
+ Expect(datastores.Items[0].Type).Should(Equal(datastoreSpec.Type))
+ Expect(datastores.Items[0].ID).Should(Equal(datastoreSpec.ID))
})
})
}) | Clean up datastore API test in Go-SDK
===
Changes:
- simplify the test code.
- correct the URI of SelfLink
===
Change-Id: I0bf0dee<I>bcd<I>f2b<I>a<I>adf<I> | vmware_photon-controller-go-sdk | train |
94dfcec0bef54b3d98006aaa4fa70bace0ed67d8 | diff --git a/code/VersionedFileExtension.php b/code/VersionedFileExtension.php
index <HASH>..<HASH> 100755
--- a/code/VersionedFileExtension.php
+++ b/code/VersionedFileExtension.php
@@ -56,9 +56,14 @@ class VersionedFileExtension extends DataObjectDecorator {
$uploadMsg = _t('VersionedFiles.UPLOADNEWFILE', 'Upload a New File');
$rollbackMsg = _t('VersionedFiles.ROLLBACKPREVVERSION', 'Rollback to a Previous Version');
- $replacementOptions = array (
- "upload//$uploadMsg" => new FileField('ReplacementFile', '')
- );
+ $sameTypeMessage = sprintf(_t (
+ 'VersionedFiles.SAMETYPEMESSAGE', 'You may only replace this file with another of the same type: .%s'
+ ), $this->owner->getExtension());
+
+ $replacementOptions = array("upload//$uploadMsg" => new FieldGroup (
+ new LiteralField('SameTypeMessage', '<p>' . $sameTypeMessage . '</p>'),
+ new FileField('ReplacementFile', '')
+ ));
$versions = $this->owner->Versions (
sprintf('"VersionNumber" <> %d', $this->getVersionNumber())
diff --git a/lang/en_US.php b/lang/en_US.php
index <HASH>..<HASH> 100755
--- a/lang/en_US.php
+++ b/lang/en_US.php
@@ -21,6 +21,7 @@ $lang['en_US']['VersionedFiles']['ISCURRENT'] = 'Is Current';
$lang['en_US']['VersionedFiles']['LINK'] = 'Link';
$lang['en_US']['VersionedFiles']['REPLACE'] = 'Replace';
$lang['en_US']['VersionedFiles']['ROLLBACKPREVVERSION'] = 'Rollback to a Previous Version';
+$lang['en_US']['VersionedFiles']['SAMETYPEMESSAGE'] = 'You may only replace this file with another of the same type: .%s';
$lang['en_US']['VersionedFiles']['SELECTAVERSION'] = '(Select a Version)';
$lang['en_US']['VersionedFiles']['UPLOADNEWFILE'] = 'Upload a New File';
$lang['en_US']['VersionedFiles']['VERSIONNUMBER'] = 'Version Number'; | MINOR: Added a message to tell the user they can only upload files of the same type to replace a file. | symbiote_silverstripe-versionedfiles | train |
9d242ee73e37390782b679792ff4d5520b2fe1c3 | diff --git a/src/Base/PhantomasCaller.php b/src/Base/PhantomasCaller.php
index <HASH>..<HASH> 100644
--- a/src/Base/PhantomasCaller.php
+++ b/src/Base/PhantomasCaller.php
@@ -44,6 +44,9 @@ class PhantomasCaller {
$command[] = '--reporter=json';
$command[] = '--timeout=30';
+ // Remove a lot of output that we don't need at the moment.
+ $command[] = '--skip-modules=domMutations,domQueries,domHiddenContent,domComplexity,jQuery';
+
// Check for the presence of shield as this will potentially block
// phantomas.
if ($this->drush->isShieldEnabled()) {
diff --git a/src/Check/Phantomas/InPage404s.php b/src/Check/Phantomas/InPage404s.php
index <HASH>..<HASH> 100644
--- a/src/Check/Phantomas/InPage404s.php
+++ b/src/Check/Phantomas/InPage404s.php
@@ -13,7 +13,7 @@ use SiteAudit\Annotation\CheckInfo;
* description = "You should not have any broken assets on your page.",
* remediation = "Fix the 404s.",
* success = "No broken assets on the page (out of <code>:total</code> total requests).",
- * failure = "Broken assets on the page (<code>:not_found</code> out of <code>:total</code> requests).",
+ * failure = "Broken assets on the page (<code>:not_found</code> out of <code>:total</code> requests). :not_found_assets.",
* exception = "Could not determine if there are any in page 404s.",
* )
*/
@@ -28,6 +28,9 @@ class InPage404s extends Check {
$this->setToken('not_found', $not_found);
if ($not_found > 0) {
+ // Find the broken assets.
+ $notFound = $this->context->phantomas->getOffender('notFound');
+ $this->setToken('not_found_assets', 'The broken assets are <code>' . implode('</code>, <code>', $notFound) . '</code>');
return AuditResponse::AUDIT_FAILURE;
} | List broken assets on page, and also exclude the jQuery DOM checks as we dont use them, and they take up a lot of JSON. | drutiny_drutiny | train |
0975c706c503d403810ddeba24ea14b5c9bdd133 | diff --git a/d1_client_cli/src/setup.py b/d1_client_cli/src/setup.py
index <HASH>..<HASH> 100755
--- a/d1_client_cli/src/setup.py
+++ b/d1_client_cli/src/setup.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+
"""
:mod:`setup`
====================
@@ -19,14 +20,21 @@ setup(
url='http://dataone.org',
license='Apache License, Version 2.0',
description='A DataONE Command-line interface',
- packages=find_packages(),
-
+ packages = find_packages(),
+
# Dependencies that are available through PYPI / easy_install.
- install_requires=[
+ install_requires = [
'pyxb >= 1.1.3',
],
- package_data={
+
+ dependency_links = [
+ 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Common-1.0.0c4-py2.6.egg',
+ 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Client_Library-1.0.0c4-py2.6.egg',
+ ]
+
+ package_data = {
# If any package contains *.txt or *.rst files, include them:
'': ['*.txt', '*.rst'],
}
)
+ | Add references to common and libclient, which will not be deployed to PyPi. | DataONEorg_d1_python | train |
7985d76a079d5613f05ddb77cb749ae90dd2cbe2 | diff --git a/core/src/main/java/com/capitalone/dashboard/config/MongoConfig.java b/core/src/main/java/com/capitalone/dashboard/config/MongoConfig.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/capitalone/dashboard/config/MongoConfig.java
+++ b/core/src/main/java/com/capitalone/dashboard/config/MongoConfig.java
@@ -15,24 +15,25 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.List;
@Component
@EnableMongoRepositories(basePackageClasses = RepositoryPackage.class)
public class MongoConfig extends AbstractMongoConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoConfig.class);
- @Value("${dbname:dashboard}")
+ @Value("${dbname:dashboarddb}")
private String databaseName;
- @Value("${dbhost:localhost}")
- private String host;
- @Value("${dbport:27017}")
- private int port;
+ @Value("#{'${dbhostport}'.split(',')}")
+ private List<String> hostport;
@Value("${dbusername:}")
private String userName;
@Value("${dbpassword:}")
private String password;
+
@Override
protected String getDatabaseName() {
return databaseName;
@@ -41,16 +42,26 @@ public class MongoConfig extends AbstractMongoConfiguration {
@Override
@Bean
public MongoClient mongo() throws Exception {
- ServerAddress serverAddr = new ServerAddress(host, port);
- LOGGER.info("Initializing Mongo Client server at: {}", serverAddr);
+ List<ServerAddress> serverAddressList = new ArrayList<>();
+ for (String h : hostport) {
+ String myHost = h.substring(0, h.indexOf(":"));
+ int myPort = Integer.parseInt(h.substring(h.indexOf(":") + 1, h.length()));
+ ServerAddress serverAddress = new ServerAddress(myHost, myPort);
+ serverAddressList.add(serverAddress);
+
+ }
+ LOGGER.info("Initializing Mongo Client server at: {}", serverAddressList.toArray().toString());
MongoClient client;
+
+
if (StringUtils.isEmpty(userName)) {
- client = new MongoClient(serverAddr);
+ client = new MongoClient(serverAddressList);
} else {
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
userName, databaseName, password.toCharArray());
- client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential));
+ client = new MongoClient(serverAddressList, Collections.singletonList(mongoCredential));
}
+
LOGGER.info("Connecting to Mongo: {}", client);
return client;
} | Modified MongoConfig in order to support MongoDb replica set | Hygieia_Hygieia | train |
3c51c4c64aa1383cb1882896ebd81c1c9868dfde | diff --git a/aiortc/rtcsctptransport.py b/aiortc/rtcsctptransport.py
index <HASH>..<HASH> 100644
--- a/aiortc/rtcsctptransport.py
+++ b/aiortc/rtcsctptransport.py
@@ -1527,9 +1527,12 @@ class RTCSctpTransport(EventEmitter):
channel._setId(stream_id)
# send data
- await self._send(stream_id, protocol, user_data,
- max_retransmits=channel.maxRetransmits, ordered=channel.ordered)
- if protocol in [WEBRTC_STRING_EMPTY, WEBRTC_STRING, WEBRTC_BINARY_EMPTY, WEBRTC_BINARY]:
+ if protocol == WEBRTC_DCEP:
+ await self._send(stream_id, protocol, user_data)
+ else:
+ await self._send(stream_id, protocol, user_data,
+ max_retransmits=channel.maxRetransmits,
+ ordered=channel.ordered)
channel._addBufferedAmount(-len(user_data))
def _data_channel_open(self, channel): | [data channels] always transmit DCEP messages reliably | aiortc_aiortc | train |
e61d0160efcbdd084fd162ee6cd99ac62e1ca813 | diff --git a/uni_form/templatetags/uni_form_tags.py b/uni_form/templatetags/uni_form_tags.py
index <HASH>..<HASH> 100644
--- a/uni_form/templatetags/uni_form_tags.py
+++ b/uni_form/templatetags/uni_form_tags.py
@@ -139,14 +139,23 @@ class BasicNode(template.Node):
return response_dict
+whole_uni_formset_template = get_template('uni_form/whole_uni_formset.html')
+whole_uni_form_template = get_template('uni_form/whole_uni_form.html')
+
class UniFormNode(BasicNode):
def render(self, context):
c = self.get_render(context)
if c['is_formset']:
- template = get_template('uni_form/whole_uni_formset.html')
+ if settings.DEBUG:
+ template = get_template('uni_form/whole_uni_formset.html')
+ else:
+ template = whole_uni_formset_template
else:
- template = get_template('uni_form/whole_uni_form.html')
+ if settings.DEBUG:
+ template = get_template('uni_form/whole_uni_form.html')
+ else:
+ template = whole_uni_form_template
return template.render(c) | Avoiding reloading templates every time `{% uni_form %}` tag is used, improving performance. See #GH-<I> | pydanny-archive_django-uni-form | train |
59a5565babe855d5dc41f0cc83bf7bfdd49ee86b | diff --git a/Entity/BreadcrumbsItem.php b/Entity/BreadcrumbsItem.php
index <HASH>..<HASH> 100755
--- a/Entity/BreadcrumbsItem.php
+++ b/Entity/BreadcrumbsItem.php
@@ -28,6 +28,9 @@ class BreadcrumbsItem
return $this->id;
}
+ /**
+ * @param integer $id
+ */
public function setId($id)
{
$this->id = $id;
@@ -53,21 +56,33 @@ class BreadcrumbsItem
return $this->path;
}
+ /**
+ * @param string $moduleName
+ */
public function setModuleName($moduleName)
{
$this->moduleName = $moduleName;
}
+ /**
+ * @param string $presenter
+ */
public function setPresenter($presenter)
{
$this->presenter = $presenter;
}
+ /**
+ * @param string $title
+ */
public function setTitle($title)
{
$this->title = $title;
}
+ /**
+ * @param string $path
+ */
public function setPath($path)
{
$this->path = $path;
diff --git a/Entity/Page.php b/Entity/Page.php
index <HASH>..<HASH> 100755
--- a/Entity/Page.php
+++ b/Entity/Page.php
@@ -306,6 +306,9 @@ class Page extends Seo
return NULL;
}
+ /**
+ * @param string $slug
+ */
public function setSlug($slug)
{
$this->slug = $slug;
diff --git a/Entity/User.php b/Entity/User.php
index <HASH>..<HASH> 100755
--- a/Entity/User.php
+++ b/Entity/User.php
@@ -93,7 +93,7 @@ class User extends Entity
}
/**
- * @return string
+ * @return Role
*/
public function getRole()
{
diff --git a/tests/EntityTest.php b/tests/EntityTest.php
index <HASH>..<HASH> 100755
--- a/tests/EntityTest.php
+++ b/tests/EntityTest.php
@@ -34,6 +34,10 @@ abstract class EntityTestCase extends BasicTestCase
$tool->dropDatabase();
}
+ /**
+ * @param string $path
+ * @param string $namespace
+ */
protected function getClassesMetadata($path, $namespace)
{
$metadata = array();
@@ -50,6 +54,9 @@ abstract class EntityTestCase extends BasicTestCase
return $metadata;
}
+ /**
+ * @param string $path
+ */
private function isEntity($path)
{
foreach ($this->exceptions as $exception) { | Scrutinizer Auto-Fixes
This patch was automatically generated as part of the following inspection:
<URL> | voslartomas_WebCMS2 | train |
d9a161522f191a7f1955d2e96d2ec402fead3a9d | diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -12,7 +12,7 @@ module.exports = function (grunt) {
nggettext_compile: {
all: {
options: {
- module: 'backwho',
+ module: 'monad',
format: 'json'
},
files: [
@@ -26,7 +26,12 @@ module.exports = function (grunt) {
}
]
}
+ },
+ watch: {
+ files: ['<%= nggettext_extract.pot.files["po/template.pot"] %>', '<%= nggettext_compile.all.files[0].src %>']
}
});
+ grunt.loadNpmTasks('grunt-contrib-watch');
+ grunt.registerTask('default', ['nggettext_extract', 'nggettext_compile']);
}; | fixup gruntfile (todo: replace gulp by grunt completely?) | monomelodies_monad | train |
c698b932362a6e7f4b05c4370edf489f38ac9d7c | diff --git a/logging/logging.go b/logging/logging.go
index <HASH>..<HASH> 100644
--- a/logging/logging.go
+++ b/logging/logging.go
@@ -31,13 +31,17 @@ const (
// the logging struct
type Logger struct {
+ // Be careful of the alignment issue of the variable seqid because it
+ // uses the sync/atomic.AddUint64() operation. If the alignment is
+ // wrong, it will cause a panic. To solve the alignment issue in an
+ // easy way, we put seqid to the beginning of the structure.
+ seqid uint64
name string
level Level
format string
out io.Writer
lock sync.Mutex
startTime time.Time
- seqid uint64
sync bool
} | fix the <I>bit alignment issue | ccding_go-logging | train |
2e1ff06c27e1408512b9175241b0899ebd8a823c | diff --git a/openquake/calculators/classical.py b/openquake/calculators/classical.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/classical.py
+++ b/openquake/calculators/classical.py
@@ -283,9 +283,7 @@ class PSHACalculator(base.HazardCalculator):
truncation_level=oq.truncation_level,
imtls=oq.imtls,
maximum_distance=oq.maximum_distance,
- disagg=oq.poes_disagg or oq.iml_disagg,
- ses_per_logic_tree_path=oq.ses_per_logic_tree_path,
- seed=oq.ses_seed)
+ disagg=oq.poes_disagg or oq.iml_disagg)
with self.monitor('managing sources', autoflush=True):
allargs = self.gen_args(self.csm, monitor)
iterargs = saving_sources_by_task(allargs, self.datastore)
@@ -324,7 +322,9 @@ class PSHACalculator(base.HazardCalculator):
gsims = self.rlzs_assoc.gsims_by_grp_id[sg.id]
if oq.poes_disagg or oq.iml_disagg: # only for disaggregation
monitor.sm_id = self.rlzs_assoc.sm_ids[sg.id]
- param = dict(samples=sm.samples)
+ param = dict(
+ samples=sm.samples, seed=oq.ses_seed,
+ ses_per_logic_tree_path=oq.ses_per_logic_tree_path)
for block in self.csm.split_sources(
sg.sources, self.src_filter, maxweight):
yield block, self.src_filter, gsims, param, monitor
diff --git a/openquake/calculators/event_based.py b/openquake/calculators/event_based.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/event_based.py
+++ b/openquake/calculators/event_based.py
@@ -110,14 +110,14 @@ def compute_ruptures(sources, src_filter, gsims, param, monitor):
if s_sites is None:
continue
num_occ_by_rup = sample_ruptures(
- src, monitor.ses_per_logic_tree_path, param['samples'],
- monitor.seed)
+ src, param['ses_per_logic_tree_path'], param['samples'],
+ param['seed'])
# NB: the number of occurrences is very low, << 1, so it is
# more efficient to filter only the ruptures that occur, i.e.
# to call sample_ruptures *before* the filtering
for ebr in _build_eb_ruptures(
src, num_occ_by_rup, src_filter.integration_distance,
- s_sites, monitor.seed, rup_mon):
+ s_sites, param['seed'], rup_mon):
eb_ruptures.append(ebr)
dt = time.time() - t0
calc_times.append((src.id, dt)) | Moved some attributes from the monitor to the param dictionary
Former-commit-id: ff<I>b<I>e0e4a8fa<I>bd7aea<I>dc4cb | gem_oq-engine | train |
c67e017a67121399526ab59013ab27504d72a21c | diff --git a/Model/ResourceModel/NodeType/Product.php b/Model/ResourceModel/NodeType/Product.php
index <HASH>..<HASH> 100644
--- a/Model/ResourceModel/NodeType/Product.php
+++ b/Model/ResourceModel/NodeType/Product.php
@@ -99,15 +99,18 @@ class Product extends AbstractNode
*/
public function fetchImageData($productIds = [])
{
+ $metadata = $this->metadataPool->getMetadata(ProductInterface::class);
+ $linkField = $metadata->getLinkField();
+
$connection = $this->getConnection('read');
$nameAttributeId = $this->getAttributeIdByCode($connection, 'image');
$table = $this->getTable('catalog_product_entity_varchar');
$select = $connection->select()
- ->from($table, ['entity_id', 'value'])
+ ->from($table, [$linkField, 'value'])
->where('attribute_id = ?', $nameAttributeId)
->where('store_id = ?', 0)
- ->where('entity_id IN (' . implode(',', $productIds) . ')');
+ ->where($linkField .' IN (' . implode(',', $productIds) . ')');
return $connection->fetchPairs($select);
} | #<I> Add compatibility with magneto EE | SnowdogApps_magento2-menu | train |
837075a378625153883728a2fbffb75b788ada1b | diff --git a/src/Psalm/Internal/Analyzer/ProjectAnalyzer.php b/src/Psalm/Internal/Analyzer/ProjectAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Internal/Analyzer/ProjectAnalyzer.php
+++ b/src/Psalm/Internal/Analyzer/ProjectAnalyzer.php
@@ -610,11 +610,7 @@ class ProjectAnalyzer
&& $this->project_cache_provider->canDiffFiles()
) {
$deleted_files = $this->file_reference_provider->getDeletedReferencedFiles();
- $diff_files = $deleted_files;
-
- foreach ($this->config->getProjectDirectories() as $dir_name) {
- $diff_files = array_merge($diff_files, $this->getDiffFilesInDir($dir_name, $this->config));
- }
+ $diff_files = array_merge($deleted_files, $this->getDiffFiles());
}
$this->progress->write($this->generatePHPVersionMessage());
@@ -1079,10 +1075,8 @@ class ProjectAnalyzer
/**
* @return list<string>
*/
- protected function getDiffFilesInDir(string $dir_name, Config $config): array
+ protected function getDiffFiles(): array
{
- $file_extensions = $config->getFileExtensions();
-
if (!$this->parser_cache_provider || !$this->project_cache_provider) {
throw new UnexpectedValueException('Parser cache provider cannot be null here');
}
@@ -1091,16 +1085,12 @@ class ProjectAnalyzer
$last_run = $this->project_cache_provider->getLastRun(PSALM_VERSION);
- $file_paths = $this->file_provider->getFilesInDir($dir_name, $file_extensions);
-
- foreach ($file_paths as $file_path) {
- if ($config->isInProjectDirs($file_path)) {
- if ($this->file_provider->getModifiedTime($file_path) >= $last_run
- && $this->parser_cache_provider->loadExistingFileContentsFromCache($file_path)
- !== $this->file_provider->getContents($file_path)
- ) {
- $diff_files[] = $file_path;
- }
+ foreach ($this->project_files as $file_path) {
+ if ($this->file_provider->getModifiedTime($file_path) >= $last_run
+ && $this->parser_cache_provider->loadExistingFileContentsFromCache($file_path)
+ !== $this->file_provider->getContents($file_path)
+ ) {
+ $diff_files[] = $file_path;
}
} | Use cached `ProjectAnalyzer::$project_files` to build list of changed files | vimeo_psalm | train |
c1559ce4ebaf3cd660ea3f6172ce47fc602750bc | diff --git a/src/components/User.php b/src/components/User.php
index <HASH>..<HASH> 100644
--- a/src/components/User.php
+++ b/src/components/User.php
@@ -11,11 +11,14 @@
namespace hipanel\components;
+use Yii;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
class User extends \yii\web\User
{
+ public $isGuestAllowed = false;
+
/**
* @var string the seller login
*/
@@ -57,4 +60,33 @@ class User extends \yii\web\User
{
return empty($this->getIdentity()->id);
}
+
+ /**
+ * Prepares authorization data.
+ * Redirects to authorization if necessary.
+ * @return array
+ */
+ public function getAuthData()
+ {
+ if ($this->isGuest) {
+ if ($this->isGuestAllowed) {
+ return [];
+ } else {
+ Yii::$app->response->redirect('/site/login');
+ Yii::$app->end();
+ }
+ }
+
+ $token = $this->identity->getAccessToken();
+ if (empty($token)) {
+ /// this is very important line
+ /// without this line - redirect loop
+ $this->logout();
+
+ Yii::$app->response->redirect('/site/login');
+ Yii::$app->end();
+ }
+
+ return ['access_token' => $token];
+ }
} | + `User::getAuthData` | hiqdev_hipanel-core | train |
ec798f5c6f561bbb5e6ed4e3df8fce1b0909094e | diff --git a/generators/scheduler/templates/bin/scheduler_daemon.rb b/generators/scheduler/templates/bin/scheduler_daemon.rb
index <HASH>..<HASH> 100644
--- a/generators/scheduler/templates/bin/scheduler_daemon.rb
+++ b/generators/scheduler/templates/bin/scheduler_daemon.rb
@@ -9,7 +9,7 @@
require 'rubygems'
require 'daemons'
-scheduler = File.join(File.dirname(__FILE__), %w(.. lib scheduler.rb))
+scheduler_path = File.join(File.dirname(__FILE__), %w(.. lib scheduler.rb))
pid_dir = File.expand_path(File.join(File.dirname(__FILE__), %w(.. log)))
@@ -23,4 +23,4 @@ app_options = {
:log_output => true
}
-Daemons.run(scheduler, app_options)
\ No newline at end of file
+Daemons.run(scheduler_path, app_options)
\ No newline at end of file
diff --git a/generators/scheduler/templates/lib/scheduled_tasks/session_cleaner_task.rb b/generators/scheduler/templates/lib/scheduled_tasks/session_cleaner_task.rb
index <HASH>..<HASH> 100644
--- a/generators/scheduler/templates/lib/scheduled_tasks/session_cleaner_task.rb
+++ b/generators/scheduler/templates/lib/scheduled_tasks/session_cleaner_task.rb
@@ -1,4 +1,4 @@
-class RemoveOldSessionsTask < SchedulerTask
+class SessionCleanerTask < SchedulerTask
every '1d', :first_at => Chronic.parse('2 am')
def run
diff --git a/generators/scheduler/templates/lib/scheduler.rb b/generators/scheduler/templates/lib/scheduler.rb
index <HASH>..<HASH> 100644
--- a/generators/scheduler/templates/lib/scheduler.rb
+++ b/generators/scheduler/templates/lib/scheduler.rb
@@ -42,14 +42,16 @@ end
task_files.each{|f|
begin
unless load_only.any? && load_only.all?{|m| f !~ Regexp.new(Regexp.escape(m)) }
+ file_name_without_suffix = f.split('/').last.split('.').first
require f
- filename = f.split('/').last.split('.').first
- puts "Loading task #{filename}..."
- tasks << filename.camelcase.constantize # path/newsfeed_task.rb => NewsfeedTask
+ task_class = file_name_without_suffix.camelize.constantize
+ puts "Loading task #{task_class}..."
+ tasks << task_class # path/newsfeed_task.rb => NewsfeedTask
end
rescue Exception => e
- msg = "Error loading task #{filename}: #{e.class.name}: #{e.message}"
+ msg = "Error loading task #{file_name_without_suffix}: #{e.class.name}: #{e.message}"
puts msg
+ # Might want to make this only in "verbose mode" - hard to see message above
puts e.backtrace.join("\n")
# Might want to create a class to talk to your team and do something like..
# Campfire.say "#{msg}, see log for backtrace" if Rails.env.production? || Rails.env.staging? | Minor cleanup: renamed RemoveOldSessionsTask to SessionCleanerTask to match filename. Cleaned up task class loading for better error reporting | ssoroka_scheduler_daemon | train |
d26c524f230dae3cf3148caff34a4126bc1b77ae | diff --git a/spyderplugins/p_breakpoints.py b/spyderplugins/p_breakpoints.py
index <HASH>..<HASH> 100644
--- a/spyderplugins/p_breakpoints.py
+++ b/spyderplugins/p_breakpoints.py
@@ -78,8 +78,6 @@ class Breakpoints(BreakpointWidget, SpyderPluginMixin):
list_action = create_action(self, _("List breakpoints"),
triggered=self.show)
list_action.setEnabled(True)
- self.register_shortcut(list_action, context="_",
- name="Switch to Breakpoints")
# A fancy way to insert the action into the Breakpoints menu under
# the assumption that Breakpoints is the first QMenu in the list. | Breakpoints: Its shortcut was registered twice, which was making it impossible to use it | spyder-ide_spyder | train |
48b844fa7abf29428dabc494971309c08d11380d | diff --git a/core/engine.go b/core/engine.go
index <HASH>..<HASH> 100644
--- a/core/engine.go
+++ b/core/engine.go
@@ -278,7 +278,7 @@ func (e *Engine) processThresholds(abort func()) {
defer e.MetricsLock.Unlock()
t := e.Executor.GetTime()
- abortOnTaint := false
+ abortOnFail := false
e.thresholdsTainted = false
for _, m := range e.Metrics {
@@ -297,13 +297,13 @@ func (e *Engine) processThresholds(abort func()) {
e.logger.WithField("m", m.Name).Debug("Thresholds failed")
m.Tainted = null.BoolFrom(true)
e.thresholdsTainted = true
- if !abortOnTaint && m.Thresholds.Abort {
- abortOnTaint = true
+ if !abortOnFail && m.Thresholds.Abort {
+ abortOnFail = true
}
}
}
- if abortOnTaint && abort != nil {
+ if abortOnFail && abort != nil {
abort()
}
}
diff --git a/stats/thresholds.go b/stats/thresholds.go
index <HASH>..<HASH> 100644
--- a/stats/thresholds.go
+++ b/stats/thresholds.go
@@ -84,8 +84,8 @@ func (t *Threshold) Run() (bool, error) {
}
type ThresholdConfig struct {
- Threshold string `json:"threshold"`
- AbortOnTaint bool `json:"abortOnTaint"`
+ Threshold string `json:"threshold"`
+ AbortOnFail bool `json:"abortOnFail"`
}
//used internally for JSON marshalling
@@ -102,7 +102,7 @@ func (tc *ThresholdConfig) UnmarshalJSON(data []byte) error {
}
func (tc ThresholdConfig) MarshalJSON() ([]byte, error) {
- if tc.AbortOnTaint {
+ if tc.AbortOnFail {
return json.Marshal(rawThresholdConfig(tc))
}
return json.Marshal(tc.Threshold)
@@ -131,7 +131,7 @@ func NewThresholdsWithConfig(configs []ThresholdConfig) (Thresholds, error) {
ts := make([]*Threshold, len(configs))
for i, config := range configs {
- t, err := NewThreshold(config.Threshold, rt, config.AbortOnTaint)
+ t, err := NewThreshold(config.Threshold, rt, config.AbortOnFail)
if err != nil {
return Thresholds{}, errors.Wrapf(err, "%d", i)
}
@@ -191,7 +191,7 @@ func (ts Thresholds) MarshalJSON() ([]byte, error) {
configs := make([]ThresholdConfig, len(ts.Thresholds))
for i, t := range ts.Thresholds {
configs[i].Threshold = t.Source
- configs[i].AbortOnTaint = t.AbortOnFail
+ configs[i].AbortOnFail = t.AbortOnFail
}
return json.Marshal(configs)
}
diff --git a/stats/thresholds_test.go b/stats/thresholds_test.go
index <HASH>..<HASH> 100644
--- a/stats/thresholds_test.go
+++ b/stats/thresholds_test.go
@@ -120,7 +120,7 @@ func TestNewThresholdsWithConfig(t *testing.T) {
for i, th := range ts.Thresholds {
assert.Equal(t, configs[i].Threshold, th.Source)
assert.False(t, th.Failed)
- assert.Equal(t, configs[i].AbortOnTaint, th.AbortOnFail)
+ assert.Equal(t, configs[i].AbortOnFail, th.AbortOnFail)
assert.NotNil(t, th.pgm)
assert.Equal(t, ts.Runtime, th.rt)
}
@@ -217,8 +217,8 @@ func TestThresholdsJSON(t *testing.T) {
{`["1+1==2","1+1==3"]`, []string{"1+1==2", "1+1==3"}, false, ""},
{`[{"threshold":"1+1==2"}]`, []string{"1+1==2"}, false, `["1+1==2"]`},
- {`[{"threshold":"1+1==2","abortOnTaint":true}]`, []string{"1+1==2"}, true, ""},
- {`[{"threshold":"1+1==2","abortOnTaint":false}]`, []string{"1+1==2"}, false, `["1+1==2"]`},
+ {`[{"threshold":"1+1==2","abortOnFail":true}]`, []string{"1+1==2"}, true, ""},
+ {`[{"threshold":"1+1==2","abortOnFail":false}]`, []string{"1+1==2"}, false, `["1+1==2"]`},
{`[{"threshold":"1+1==2"}, "1+1==3"]`, []string{"1+1==2", "1+1==3"}, false, `["1+1==2","1+1==3"]`},
} | Changing var names for improved consistency and clarity | loadimpact_k6 | train |
8f10d8783a9f96775c5f11a2388ef2ef87a0d856 | diff --git a/controllers/api.go b/controllers/api.go
index <HASH>..<HASH> 100644
--- a/controllers/api.go
+++ b/controllers/api.go
@@ -416,17 +416,17 @@ func (c *ApiController) TriggerGithubPushHook() {
hook := githubutil.GithubPushHook{}
- var result string
-
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &hook); err != nil {
c.Ctx.Output.SetStatus(400)
c.Ctx.Output.Body([]byte("empty title"))
fmt.Println(err)
- result = "{success: false}"
}
- result = "{success: true}"
- c.Ctx.WriteString(result)
+ projectId, _ := models.ReadOrCreateProject(hook.Repository.Owner.Login, hook.Repository.Name, hook.Repository.URL)
+
+ models.AddGithubBuild(projectId, hook)
+
+ return
}
diff --git a/models/models.go b/models/models.go
index <HASH>..<HASH> 100644
--- a/models/models.go
+++ b/models/models.go
@@ -7,6 +7,7 @@ import (
"fmt"
+ "github.com/ArchCI/archci/githubutil"
"github.com/ArchCI/archci/gitlabutil"
)
@@ -100,6 +101,29 @@ func AddBuildWithProject(project Project) error {
return err
}
+func AddGithubBuild(projectId int64, data githubutil.GithubPushHook) error {
+ o := orm.NewOrm()
+
+ // TODO(tobe): could not get commit id, commit time and committer
+
+ build := Build{
+ UserName: data.Repository.Owner.Login,
+ ProjectId: projectId,
+ ProjectName: data.Repository.Name,
+ RepoUrl: data.Repository.URL,
+ Branch: data.Repository.DefaultBranch,
+ Commit: "ffffffffff",
+ CommitTime: time.Now(),
+ Committer: "unknown",
+ BuildTime: time.Now(),
+ FinishTime: time.Now(),
+ Status: BUILD_STATUS_NOT_START}
+
+ _, err := o.Insert(&build)
+ fmt.Println("ERR: %v\n", err)
+ return err
+}
+
func AddGitlabBuild(projectId int64, data gitlabutil.GitlabPushHook) error {
o := orm.NewOrm()
@@ -126,12 +150,6 @@ func AddGitlabBuild(projectId int64, data gitlabutil.GitlabPushHook) error {
return err
}
-/*
-func AddGithubBuild() error {
-
-}
-*/
-
// For advanced usage in http://beego.me/docs/mvc/model/query.md#all
func GetAllProjects() []*Project {
o := orm.NewOrm()
@@ -173,7 +191,6 @@ func ReadOrCreateProject(userName string, projectName string, repoUrl string) (i
} else {
return 0, err
}
-
}
func GetAllWorkers() []*Worker { | Implement github continues integration with webhook | ArchCI_archci | train |
5c925ab245ea0aff080c4d821ede2bb99a73b16e | diff --git a/src/Plugin/search_api/datasource/StrawberryfieldFlavorDatasource.php b/src/Plugin/search_api/datasource/StrawberryfieldFlavorDatasource.php
index <HASH>..<HASH> 100644
--- a/src/Plugin/search_api/datasource/StrawberryfieldFlavorDatasource.php
+++ b/src/Plugin/search_api/datasource/StrawberryfieldFlavorDatasource.php
@@ -94,18 +94,29 @@ class StrawberryfieldFlavorDatasource extends DatasourcePluginBase {
return "node";
}
+ /**
+ * Determines whether the entity type supports bundles.
+ *
+ * @return bool
+ * TRUE if the entity type supports bundles, FALSE otherwise.
+ */
+ protected function hasBundles() {
+ return $this->getEntityType()->hasKey('bundle');
+ }
+
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
$default_configuration = [];
-//§/ if ($this->hasBundles()) {
-//§/ $default_configuration['bundles'] = [
-//§/ 'default' => TRUE,
-//§/ 'selected' => [],
-//§/ ];
-//§/ }
+ if ($this->hasBundles()) {
+ $default_configuration['bundles'] = [
+ 'default' => TRUE,
+ 'selected' => [],
+ ];
+ }
+
if ($this->isTranslatable()) {
$default_configuration['languages'] = [
@@ -244,11 +255,7 @@ class StrawberryfieldFlavorDatasource extends DatasourcePluginBase {
// might want to include and later sort out those for which we want only the
// translations in $languages and those (matching $bundles) where we want
// all (enabled) translations.
- //§/
- //§/ ToDO manage bundles
- //§/ at the moment bybass
- //§/ if ($this->hasBundles()) {
- if ( 1 == 0) {
+ if ($this->hasBundles()) {
$bundle_property = $this->getEntityType()->getKey('bundle');
if ($bundles && !$languages) {
$select->condition($bundle_property, $bundles, 'IN');
@@ -277,8 +284,8 @@ class StrawberryfieldFlavorDatasource extends DatasourcePluginBase {
$entity_ids = $select->execute();
- dpm("In getPartialItemIds");
- dpm($entity_ids);
+//§/ dpm("In getPartialItemIds");
+//§/ dpm($entity_ids);
if (!$entity_ids) {
return NULL;
@@ -329,8 +336,8 @@ class StrawberryfieldFlavorDatasource extends DatasourcePluginBase {
$this->getEntityStorage()->resetCache($entity_ids);
}
-dpm("In getPartialItemIds");
-dpm($item_ids);
+//§/dpm("In getPartialItemIds");
+//§/dpm($item_ids);
return $item_ids;
}
@@ -344,7 +351,7 @@ dpm($item_ids);
$documents = [];
$sbfflavordata_definition = StrawberryfieldFlavorDataDefinition::create('strawberryfield_flavor_data');
-dpm("In loadmultiple 2");
+dpm("In loadmultiple");
dpm($ids);
foreach($ids as $id){ | Added default configuration bundles (no bundle at the moment) | esmero_strawberryfield | train |
efc32dd3d3dacd16eabfdbfb8f6f4fe1a75e6920 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,5 @@
# [develop](https://github.com/adhearsion/punchblock)
+ * Feature: Output component now exposes #recording and #recording_uri for easy access to record results.
* Feature: Early media support for Asterisk, using Progress to start an early media session
* BREAKING: Asterisk translator now does NOT answer the call automatically when Output, Input or Record are used.
* Feature: Output component on Asterisk now supports early media. If the line is not answered, it runs Progress followed by Playback with noanswer.
diff --git a/lib/punchblock/component/record.rb b/lib/punchblock/component/record.rb
index <HASH>..<HASH> 100644
--- a/lib/punchblock/component/record.rb
+++ b/lib/punchblock/component/record.rb
@@ -188,6 +188,22 @@ module Punchblock
end
end
+ ##
+ # Directly returns the recording for the component
+ # @return [Punchblock::Component::Record::Recording] The recording object
+ #
+ def recording
+ complete_event.recording
+ end
+
+ ##
+ # Directly returns the recording URI for the component
+ # @return [String] The recording URI
+ #
+ def recording_uri
+ recording.uri
+ end
+
class Pause < CommandNode # :nodoc:
register :pause, :record
end
diff --git a/spec/punchblock/component/record_spec.rb b/spec/punchblock/component/record_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/punchblock/component/record_spec.rb
+++ b/spec/punchblock/component/record_spec.rb
@@ -154,6 +154,36 @@ module Punchblock
end
end
+ context "direct recording accessors" do
+ let :stanza do
+ <<-MESSAGE
+<complete xmlns='urn:xmpp:rayo:ext:1'>
+<success xmlns='urn:xmpp:rayo:record:complete:1'/>
+<recording xmlns='urn:xmpp:rayo:record:complete:1' uri="file:/tmp/rayo7451601434771683422.mp3" duration="34000" size="23450"/>
+</complete>
+ MESSAGE
+ end
+ let(:event) { RayoNode.import(parse_stanza(stanza).root) }
+
+ before do
+ subject.request!
+ subject.execute!
+ subject.add_event event
+ end
+
+ describe "#recording" do
+ it "should be a Punchblock::Component::Record::Recording" do
+ subject.recording.should be_a Punchblock::Component::Record::Recording
+ end
+ end
+
+ describe "#recording_uri" do
+ it "should be the recording URI set earlier" do
+ subject.recording_uri.should be == "file:/tmp/rayo7451601434771683422.mp3"
+ end
+ end
+ end
+
describe '#stop_action' do
subject { command.stop_action } | [FEATURE] Feature: Output component now exposes #recording and #recording_uri for easy access to record results. | adhearsion_punchblock | train |
20c816a7b6e7eee3685b57bbc3022e3b03fed243 | diff --git a/anonymoususage/anonymoususage.py b/anonymoususage/anonymoususage.py
index <HASH>..<HASH> 100644
--- a/anonymoususage/anonymoususage.py
+++ b/anonymoususage/anonymoususage.py
@@ -292,6 +292,31 @@ class AnonymousUsageTracker(object):
self.stop_watcher()
return False
+ def database_to_csv(self, path, orderby='type'):
+ """
+ Create a CSV file for the latest usage stats.
+ :param path: path to output CSV file
+ :param dbconn_master: master database connection
+ :param dbconn_part: partial database connection
+ :param tableinfo: table header information
+ """
+ tableinfo = self.get_table_info()
+ stats_master = database_to_json(self.dbcon_master, tableinfo)
+ stats_partial = database_to_json(self.dbcon_part, tableinfo)
+ with open(path, 'w') as f:
+ csvfile = csv.writer(f)
+ csvfile.writerow(['Name', 'Type', 'Value', 'Description'])
+ rows = []
+ for key in set(stats_master.iterkeys()).union(stats_partial.iterkeys()):
+ # Attempt to get the latest stat (from partial), if it doesn't exist get it from master
+ stat = stats_partial.get(key, stats_master[key])
+ rows.append([key, stat['type'], stat['data'], stat['description']])
+ if orderby == 'type':
+ rows.sort(key=lambda x: x[1]) # Sort by type
+ elif orderby == 'name':
+ rows.sort(key=lambda x: x[0]) # Sort by type
+ csvfile.writerows(rows)
+
def to_file(self, path, precision='%.2g'):
"""
Create a CSV report of the trackables | added database_to_csv() method to AnonymousUsageTracker that dumps the latest stats to a csv file. | lobocv_anonymoususage | train |
02c0e434085ff91e841649fa6ecb03f6ef7cbc78 | diff --git a/src/discover.js b/src/discover.js
index <HASH>..<HASH> 100644
--- a/src/discover.js
+++ b/src/discover.js
@@ -17,9 +17,6 @@ var cachedInfo = {};
* This function deals with the Webfinger lookup, discovering a connecting
* user's storage details.
*
- * The discovery timeout can be configured via
- * `config.discoveryTimeout` (in ms).
- *
* @param {string} userAddress - user@host
*
* @returns {Promise} A promise for an object with the following properties. | Remove old comment about changing a private property | remotestorage_remotestorage.js | train |
382b76b1cb2da58ac66540f18544151019dce734 | diff --git a/salt/modules/match.py b/salt/modules/match.py
index <HASH>..<HASH> 100644
--- a/salt/modules/match.py
+++ b/salt/modules/match.py
@@ -4,7 +4,9 @@ The match module allows for match routines to be run and determine target specs
'''
# Import python libs
+import inspect
import logging
+import sys
# Import salt libs
import salt.minion
@@ -234,3 +236,36 @@ def glob(tgt, minion_id=None):
except Exception as exc:
log.exception(exc)
return False
+
+
+def filter_by(lookup, expr_form='compound', minion_id=None):
+ '''
+ Return the first match in a dictionary of target patterns
+
+ .. versionadded:: Helium
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' match.filter_by '{foo*: Foo!, bar*: Bar!}' minion_id=bar03
+
+ Pillar Example:
+
+ .. code-block:: yaml
+
+ {% set roles = salt['match.filter_by']({
+ 'web*': ['app', 'caching'],
+ 'db*': ['db'],
+ }) %}
+ '''
+ expr_funcs = dict(inspect.getmembers(sys.modules[__name__],
+ predicate=inspect.isfunction))
+
+ for key in lookup.keys():
+ if minion_id and expr_funcs[expr_form](key, minion_id):
+ return lookup[key]
+ elif expr_funcs[expr_form](key, minion_id):
+ return lookup[key]
+
+ return None | Added a filter_by function to the match module | saltstack_salt | train |
e79cc4fc9f657566cfb826af849c313135f5b69e | diff --git a/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java b/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java
index <HASH>..<HASH> 100644
--- a/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java
+++ b/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java
@@ -362,23 +362,15 @@ public class AtomPlacer {
nextAtom.setFlag(CDKConstants.ISPLACED, true);
boolean trans = false;
- // quick fix to handle geometry of cumulated, CC=C=CC, ideally it
- // would be useful to know the geometries
- if (prevBond != null && IBond.Order.DOUBLE.equals(prevBond.getOrder())
- && IBond.Order.DOUBLE.equals(currBond.getOrder())) {
+ if (prevBond != null && isColinear(atom, molecule.getConnectedBondsList(atom))) {
int atomicNumber = atom.getAtomicNumber();
int charge = atom.getFormalCharge();
- if (charge == 0
- && (Elements.Carbon.number() == atomicNumber || Elements.Germanium.number() == atomicNumber || Elements.Silicon
- .number() == atomicNumber)) {
-
- // double length of the last bond to determing next placement
- Point2d p = new Point2d(prevBond.getConnectedAtom(atom).getPoint2d());
- p.interpolate(atom.getPoint2d(), 2);
- nextAtom.setPoint2d(p);
- }
+ // double length of the last bond to determing next placement
+ Point2d p = new Point2d(prevBond.getConnectedAtom(atom).getPoint2d());
+ p.interpolate(atom.getPoint2d(), 2);
+ nextAtom.setPoint2d(p);
}
if (GeometryUtil.has2DCoordinates(atomContainer)) {
@@ -431,7 +423,7 @@ public class AtomPlacer {
previousAtom.getPoint2d().y - atom.getPoint2d().y);
double addAngle = Math.toRadians(120);
if (!trans) addAngle = Math.toRadians(60);
- if (shouldBeLinear(atom, molecule)) addAngle = Math.toRadians(180);
+ if (isColinear(atom, molecule.getConnectedBondsList(atom))) addAngle = Math.toRadians(180);
angle += addAngle;
Vector2d vec1 = new Vector2d(Math.cos(angle), Math.sin(angle));
@@ -919,6 +911,54 @@ public class AtomPlacer {
return prev;
}
+ /**
+ * -C#N
+ * -[N+]#[C-]
+ * -C=[N+]=N
+ * -N=[N+]=N
+ */
+ boolean isColinear(IAtom atom, List<IBond> bonds) {
+ if (bonds.size() != 2)
+ return false;
+
+ int numSgl = atom.getImplicitHydrogenCount();
+ int numDbl = 0;
+ int numTpl = 0;
+
+ for (IBond bond : bonds) {
+ switch (bond.getOrder()) {
+ case SINGLE:
+ numSgl++;
+ break;
+ case DOUBLE:
+ numDbl++;
+ break;
+ case TRIPLE:
+ numTpl++;
+ break;
+ case QUADRUPLE:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ switch (atom.getAtomicNumber()) {
+ case 6:
+ case 7:
+ case 14:
+ case 32:
+ if (numTpl == 1 && numSgl == 1)
+ return true;
+ if (numDbl == 2 && numSgl == 0)
+ return true;
+ break;
+ }
+
+ return false;
+ }
+
+ @Deprecated
static public boolean shouldBeLinear(IAtom atom, IAtomContainer molecule) {
int sum = 0;
List bonds = molecule.getConnectedBondsList(atom); | Slightly better check for laying out co-linear chains. Useful for cumulenes and azides. | cdk_cdk | train |
a723c591d1ca628180fe52ac7feb226582729363 | diff --git a/nomad/eval_broker.go b/nomad/eval_broker.go
index <HASH>..<HASH> 100644
--- a/nomad/eval_broker.go
+++ b/nomad/eval_broker.go
@@ -281,6 +281,14 @@ func (b *EvalBroker) waitForSchedulers(schedulers []string, timeoutCh <-chan tim
}
}
+// Outstanding checks if an EvalID has been delivered but not acknowledged
+func (b *EvalBroker) Outstanding(evalID string) bool {
+ b.l.RLock()
+ defer b.l.RUnlock()
+ _, ok := b.unack[evalID]
+ return ok
+}
+
// Ack is used to positively acknowledge handling an evaluation
func (b *EvalBroker) Ack(evalID string) error {
b.l.Lock()
diff --git a/nomad/eval_broker_test.go b/nomad/eval_broker_test.go
index <HASH>..<HASH> 100644
--- a/nomad/eval_broker_test.go
+++ b/nomad/eval_broker_test.go
@@ -66,6 +66,10 @@ func TestEvalBroker_Enqueue_Dequeue_Nack_Ack(t *testing.T) {
t.Fatalf("bad : %#v", out)
}
+ if !b.Outstanding(out.ID) {
+ t.Fatalf("should be outstanding")
+ }
+
// Check the stats
stats = b.Stats()
if stats.TotalReady != 0 {
@@ -87,6 +91,10 @@ func TestEvalBroker_Enqueue_Dequeue_Nack_Ack(t *testing.T) {
t.Fatalf("err: %v", err)
}
+ if b.Outstanding(out.ID) {
+ t.Fatalf("should not be outstanding")
+ }
+
// Check the stats
stats = b.Stats()
if stats.TotalReady != 1 {
@@ -111,12 +119,20 @@ func TestEvalBroker_Enqueue_Dequeue_Nack_Ack(t *testing.T) {
t.Fatalf("bad : %#v", out2)
}
+ if !b.Outstanding(out.ID) {
+ t.Fatalf("should be outstanding")
+ }
+
// Ack finally
err = b.Ack(eval.ID)
if err != nil {
t.Fatalf("err: %v", err)
}
+ if b.Outstanding(out.ID) {
+ t.Fatalf("should not be outstanding")
+ }
+
// Check the stats
stats = b.Stats()
if stats.TotalReady != 0 { | nomad: method to test if outstanding evaluation | hashicorp_nomad | train |
896a0f4df7d48ce08570f300ce78f10e1694bd1f | diff --git a/packages/vaex-core/vaex/file/s3fs.py b/packages/vaex-core/vaex/file/s3fs.py
index <HASH>..<HASH> 100644
--- a/packages/vaex-core/vaex/file/s3fs.py
+++ b/packages/vaex-core/vaex/file/s3fs.py
@@ -1,5 +1,6 @@
import vaex.utils
import pyarrow.fs
+import warnings
s3fs = vaex.utils.optional_import('s3fs')
import vaex.file.cache | 🐛 s3fs.py missed a warnings import (#<I>)
you use the `warnings` library without importing it | vaexio_vaex | train |
3116a1220bda3a5e1a81ba3b0c6a8ad8ea7b0634 | diff --git a/js/data/DataSource.js b/js/data/DataSource.js
index <HASH>..<HASH> 100644
--- a/js/data/DataSource.js
+++ b/js/data/DataSource.js
@@ -221,7 +221,7 @@ define(["require", "js/core/Component", "js/conf/Configuration", "js/core/Base",
} else if (value instanceof Collection) {
return this._composeCollection(value, action, options);
} else if (value instanceof Entity) {
- return value.compose(action, options);
+ return value.compose(this.$datasource,action, options);
} else if (value instanceof List) {
var ret = [];
var self = this;
diff --git a/js/data/Entity.js b/js/data/Entity.js
index <HASH>..<HASH> 100644
--- a/js/data/Entity.js
+++ b/js/data/Entity.js
@@ -50,6 +50,12 @@ define(['require', 'js/core/Bindable', 'js/core/List', 'js/data/TypeResolver', '
return this.$context.$datasource.getContextForChild(childFactory, this);
},
+ createEntity: function(childFactory,id){
+ var context = this.getContextForChild(childFactory);
+
+ return context.createEntity(childFactory,id);
+ },
+
_isChildFactoryDependentObject: function (childFactory) {
return childFactory && childFactory.prototype.$isDependentObject;
},
@@ -191,12 +197,13 @@ define(['require', 'js/core/Bindable', 'js/core/List', 'js/data/TypeResolver', '
/***
* composes the data for serialisation
+ * @param dataSource
* @param action
* @param options
* @return {Object} all data that should be serialized
*/
- compose: function (action, options) {
- var processor = this.$context.$datasource.getProcessorForModel(this, options);
+ compose: function (dataSource, action, options) {
+ var processor = dataSource.getProcessorForModel(this, options);
return processor.compose(this, action, options);
},
diff --git a/js/data/Model.js b/js/data/Model.js
index <HASH>..<HASH> 100644
--- a/js/data/Model.js
+++ b/js/data/Model.js
@@ -154,7 +154,8 @@ define(["js/data/Entity", "js/core/List", "flow", "underscore"], function (Entit
});
}
} else if (value instanceof Object) {
- fetchSubModels(value, subModelTypes, delegates);
+ // TODO: causes in some cases an unfinity loop
+ // fetchSubModels(value, subModelTypes, delegates);
}
});
}
diff --git a/js/data/RestDataSource.js b/js/data/RestDataSource.js
index <HASH>..<HASH> 100644
--- a/js/data/RestDataSource.js
+++ b/js/data/RestDataSource.js
@@ -280,7 +280,7 @@ define(["js/data/DataSource", "js/core/Base", "js/data/Model", "underscore", "fl
// TODO: create hook, which can modify url and queryParameter
// compose data in model and in processor
- var data = model.compose(action, options);
+ var data = model.compose(self,action, options);
// format payload
var payload = formatProcessor.serialize(data); | compose method now get's datasource as input ... | rappid_rAppid.js | train |
6a1a69709ee8fef11399a97e7a4a02797aa029e5 | diff --git a/plugins/agent.py b/plugins/agent.py
index <HASH>..<HASH> 100755
--- a/plugins/agent.py
+++ b/plugins/agent.py
@@ -62,8 +62,8 @@ class Agent(BaseHTTPRequestHandler):
query = parse_qs(urlparse(self.path).query)
command = query['command'][0].split(' ')
- async = bool(int(query.get('async', [False])[0]))
- output = run_command(command, asynchronous=async)
+ asyn = bool(int(query.get('asyn', [False])[0]))
+ output = run_command(command, asynchronous=asyn)
self.respond(output)
@@ -73,12 +73,12 @@ class Agent(BaseHTTPRequestHandler):
query = parse_qs(urlparse(self.path).query)
sample = query['sample'][0]
- async = bool(int(query.get('async', [False])[0]))
+ asyn = bool(int(query.get('asyn', [False])[0]))
path = self.store_file(mkdtemp(), sample)
command = query['command'][0].format(sample=path).split(' ')
- output = run_command(command, asynchronous=async)
+ output = run_command(command, asynchronous=asyn)
self.respond(output) | change async to asyn
Since python <I> async is a reserved keyword | F-Secure_see | train |
a433c16feb2bc0703a160ad931b13dc65b93760d | diff --git a/jax/experimental/jax2tf/tests/primitive_harness.py b/jax/experimental/jax2tf/tests/primitive_harness.py
index <HASH>..<HASH> 100644
--- a/jax/experimental/jax2tf/tests/primitive_harness.py
+++ b/jax/experimental/jax2tf/tests/primitive_harness.py
@@ -905,10 +905,10 @@ lax_conv_general_dilated = tuple( # Validate dtypes and precision
# This first harness runs the tests for all dtypes and precisions using
# default values for all the other parameters. Variations of other parameters
# can thus safely skip testing their corresponding default value.
- _make_conv_harness("dtype_precision", dtype=dtype, precision=precision)
- for dtype in jtu.dtypes.all_inexact
- for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,
- lax.Precision.HIGHEST]
+ # _make_conv_harness("dtype_precision", dtype=dtype, precision=precision)
+ # for dtype in jtu.dtypes.all_inexact
+ # for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,
+ # lax.Precision.HIGHEST]
) + tuple( # Validate variations of feature_group_count and batch_group_count
_make_conv_harness("group_counts", lhs_shape=lhs_shape, rhs_shape=rhs_shape,
feature_group_count=feature_group_count, | [jax2tf] Disable some convolution tests (#<I>) | tensorflow_probability | train |
2d6b6806d9ec301d2d3fed7a41bd2b6934bab178 | diff --git a/js/plugins/spreadsheet.js b/js/plugins/spreadsheet.js
index <HASH>..<HASH> 100644
--- a/js/plugins/spreadsheet.js
+++ b/js/plugins/spreadsheet.js
@@ -123,7 +123,7 @@ Flotr.addPlugin('spreadsheet', {
html.push('<tr>');
for (i = 0; i < s.length+1; ++i) {
var tag = 'td',
- content = (datagrid[j][i] !== null ? Math.round(datagrid[j][i]*100000)/100000 : '');
+ content = (!_.isUndefined(datagrid[j][i]) ? Math.round(datagrid[j][i]*100000)/100000 : '');
if (i === 0) {
tag = 'th'; | if values are not contained in the serie, they are undefined, not null | HumbleSoftware_Flotr2 | train |
dca4c7575219a14240ef2f21fe7ab29a16ae025a | diff --git a/src/pikepdf/models/image.py b/src/pikepdf/models/image.py
index <HASH>..<HASH> 100644
--- a/src/pikepdf/models/image.py
+++ b/src/pikepdf/models/image.py
@@ -608,11 +608,7 @@ class PdfImage(PdfImageBase):
im = Image.frombuffer('L', self.size, buffer, "raw", 'L', stride, ystep)
- shift = 8 - self.bits_per_component
- if self.mode == 'L' and self.bits_per_component < 8:
- output = im.tobytes()
- im = Image.frombytes('L', self.size, bytes(output))
- elif self.mode == 'P' and self.palette is not None:
+ if self.mode == 'P' and self.palette is not None:
base_mode, palette = self.palette
if base_mode == 'RGB':
im.putpalette(palette, rawmode=base_mode)
@@ -621,6 +617,7 @@ class PdfImage(PdfImageBase):
# Convert to RGB palette.
gray_palette = palette
palette = b''
+ shift = 8 - self.bits_per_component
for entry in gray_palette:
palette += bytes([entry << shift]) * 3
im.putpalette(palette, rawmode='RGB')
diff --git a/tests/test_image_access.py b/tests/test_image_access.py
index <HASH>..<HASH> 100644
--- a/tests/test_image_access.py
+++ b/tests/test_image_access.py
@@ -958,6 +958,11 @@ def test_random_image(bpc, width, height, colorspace, imbytes, tmp_path_factory)
outprefix = f'{width}x{height}x{im.mode}-'
tmpdir = tmp_path_factory.mktemp(outprefix)
pdf.save(tmpdir / 'pdf.pdf')
+
+ # We don't have convenient CMYK checking tools
+ if im.mode == 'CMYK':
+ return
+
im.save(tmpdir / 'pikepdf.png')
Path(tmpdir / 'imbytes.bin').write_bytes(imbytes)
run( | image: eliminate now-unnecessary image tobytes/frombytes | pikepdf_pikepdf | train |
f43e6f82c0006084ccdb08ba9edfbdbaca433d31 | diff --git a/test/behaviour/typeql/TypeQLSteps.java b/test/behaviour/typeql/TypeQLSteps.java
index <HASH>..<HASH> 100644
--- a/test/behaviour/typeql/TypeQLSteps.java
+++ b/test/behaviour/typeql/TypeQLSteps.java
@@ -506,8 +506,8 @@ public class TypeQLSteps {
}
@Then("each answer does not satisfy")
- public void each_answer_does_not_satisfy(String templatedGraqlQuery) {
- String templatedQuery = String.join("\n", templatedGraqlQuery);
+ public void each_answer_does_not_satisfy(String templatedTypeQLQuery) {
+ String templatedQuery = String.join("\n", templatedTypeQLQuery);
for (ConceptMap answer : answers) {
String queryString = applyQueryTemplate(templatedQuery, answer);
TypeQLMatch query = TypeQL.parseQuery(queryString).asMatch(); | Renamed 'Graql' to 'TypeQL' | graknlabs_grakn | train |
d0c6969731aae9fd9ca96b6696cd47eaf7d14bc8 | diff --git a/vendor/refinerycms/core/public/javascripts/rails.js b/vendor/refinerycms/core/public/javascripts/rails.js
index <HASH>..<HASH> 100644
--- a/vendor/refinerycms/core/public/javascripts/rails.js
+++ b/vendor/refinerycms/core/public/javascripts/rails.js
@@ -1,6 +1,6 @@
/*
Taken from http://github.com/rails/jquery-ujs
- At version http://github.com/rails/jquery-ujs/blob/abe2f8c2f4fa53391ed954c38a596c2754a78509/src/rails.js
+ At version http://github.com/rails/jquery-ujs/blob/f991faf0074487b43a061168cdbfd102ee0c182c/src/rails.js
(Because that was the current master version)
*/
@@ -66,14 +66,28 @@ jQuery(function ($) {
/**
* confirmation handler
*/
- $('a[data-confirm],input[data-confirm]').live('click', function () {
- var el = $(this);
- if (el.triggerAndReturn('confirm')) {
- if (!confirm(el.attr('data-confirm'))) {
- return false;
- }
- }
- });
+ var jqueryVersion = $().jquery;
+
+ if ( (jqueryVersion === '1.4') || (jqueryVersion === '1.4.1') || (jqueryVersion === '1.4.2')){
+ $('a[data-confirm],input[data-confirm]').live('click', function () {
+ var el = $(this);
+ if (el.triggerAndReturn('confirm')) {
+ if (!confirm(el.attr('data-confirm'))) {
+ return false;
+ }
+ }
+ });
+ } else {
+ $('body').delegate('a[data-confirm],input[data-confirm]', 'click', function () {
+ var el = $(this);
+ if (el.triggerAndReturn('confirm')) {
+ if (!confirm(el.attr('data-confirm'))) {
+ return false;
+ }
+ }
+ });
+ }
+
/** | updating rails.js for jQuery (closes issue 8 on refinerycms-inquiries) | refinery_refinerycms | train |
5469a00188e30bbe9607339c4b7a4d6621365d9c | diff --git a/holoviews/core/overlay.py b/holoviews/core/overlay.py
index <HASH>..<HASH> 100644
--- a/holoviews/core/overlay.py
+++ b/holoviews/core/overlay.py
@@ -22,7 +22,7 @@ class Overlayable(object):
"""
def __mul__(self, other):
- if isinstance(other, UniformNdMapping):
+ if isinstance(other, UniformNdMapping) and not isinstance(other, CompositeOverlay):
items = [(k, self * v) for (k, v) in other.items()]
return other.clone(items) | Fixed bug where __mul__ would result in NdOverlays instead of Overlays | pyviz_holoviews | train |
cdbfce0bed694dd0b6c6ece2f8edc89075f818a0 | diff --git a/public/js/render/saved-history-preview.js b/public/js/render/saved-history-preview.js
index <HASH>..<HASH> 100644
--- a/public/js/render/saved-history-preview.js
+++ b/public/js/render/saved-history-preview.js
@@ -58,6 +58,9 @@ if ($('#history').length) (function () {
}
});
+ // Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't
+ // completely remove it (and parse the date using the local timezone).
+ $('#history a').attr('pubdate', $('#history a').attr('pubdate').replace('Z', '+0000'));
$('#history a').prettyDate();
setInterval(function(){ $('#history td.created a').prettyDate(); }, 30 * 1000); | Update history preview to parse the dates in the correct timezone
This was previously using the users local timezone which meant
dates could be out. Ticket #<I>. | jsbin_jsbin | train |
223a4f929392cff689ba266c4d69c54b6e11df49 | diff --git a/src/App.js b/src/App.js
index <HASH>..<HASH> 100644
--- a/src/App.js
+++ b/src/App.js
@@ -6,7 +6,7 @@ class App extends Component {
render() {
return (
<div style={{ width: "500px", height: "300px" }}>
- <Piano startNote="c4" endNote="c5" />
+ <Piano startNote="c4" endNote="c6" />
</div>
);
}
diff --git a/src/Piano.js b/src/Piano.js
index <HASH>..<HASH> 100644
--- a/src/Piano.js
+++ b/src/Piano.js
@@ -30,11 +30,15 @@ function noteToMidiNumber(note) {
const offset = NOTE_ARRAY.indexOf(basenote);
return MIDI_NUMBER_C0 + offset + NOTES_IN_OCTAVE * parseInt(octave, 10);
}
-function midiNumberToNote(number) {
+function getMidiNumberAttributes(number) {
const offset = (number - MIDI_NUMBER_C0) % NOTES_IN_OCTAVE;
const octave = Math.floor((number - MIDI_NUMBER_C0) / NOTES_IN_OCTAVE);
const basenote = NOTE_ARRAY[offset];
- return `${basenote}${octave}`;
+ return {
+ offset,
+ octave,
+ basenote
+ };
}
function Key(props) {
@@ -71,20 +75,19 @@ class Piano extends React.Component {
background: "#555",
zIndex: 1
},
- // TODO: include MIDI note number https://en.wikipedia.org/wiki/Scientific_pitch_notation#Table_of_note_frequencies
noteConfig: {
- c: { offset: 0, isBlackKey: false },
- db: { offset: 0.55, isBlackKey: true },
- d: { offset: 1, isBlackKey: false },
- eb: { offset: 1.8, isBlackKey: true },
- e: { offset: 2, isBlackKey: false },
- f: { offset: 3, isBlackKey: false },
- gb: { offset: 3.5, isBlackKey: true },
- g: { offset: 4, isBlackKey: false },
- ab: { offset: 4.7, isBlackKey: true },
- a: { offset: 5, isBlackKey: false },
- bb: { offset: 5.85, isBlackKey: true },
- b: { offset: 6, isBlackKey: false }
+ c: { offsetFromC: 0, isBlackKey: false },
+ db: { offsetFromC: 0.55, isBlackKey: true },
+ d: { offsetFromC: 1, isBlackKey: false },
+ eb: { offsetFromC: 1.8, isBlackKey: true },
+ e: { offsetFromC: 2, isBlackKey: false },
+ f: { offsetFromC: 3, isBlackKey: false },
+ gb: { offsetFromC: 3.5, isBlackKey: true },
+ g: { offsetFromC: 4, isBlackKey: false },
+ ab: { offsetFromC: 4.7, isBlackKey: true },
+ a: { offsetFromC: 5, isBlackKey: false },
+ bb: { offsetFromC: 5.85, isBlackKey: true },
+ b: { offsetFromC: 6, isBlackKey: false }
}
};
@@ -93,35 +96,41 @@ class Piano extends React.Component {
};
render() {
+ const startNum = noteToMidiNumber(this.props.startNote);
const midiNumbers = _.range(
- noteToMidiNumber(this.props.startNote),
+ startNum,
noteToMidiNumber(this.props.endNote) + 1
);
- const notes = midiNumbers.map(num => {
- const note = midiNumberToNote(num);
- return note.substring(0, note.length - 1);
- });
-
- const numWhiteKeys = notes.filter(
- note => !this.props.noteConfig[note].isBlackKey
- ).length;
+ const numWhiteKeys = midiNumbers.filter(num => {
+ const { basenote } = getMidiNumberAttributes(num);
+ return !this.props.noteConfig[basenote].isBlackKey;
+ }).length;
const whiteKeyWidth = 1 / numWhiteKeys;
+ const octaveWidth = 7;
+
return (
<div style={{ position: "relative", width: "100%", height: "100%" }}>
- {notes.map(note => {
- const noteConfig = this.props.noteConfig[note];
+ {midiNumbers.map(num => {
+ // TODO: refactor
+ const { octave, offset, basenote } = getMidiNumberAttributes(num);
+ const noteConfig = this.props.noteConfig[basenote];
const keyConfig = noteConfig.isBlackKey
? this.props.blackKeyConfig
: this.props.whiteKeyConfig;
+ const startNoteAttrs = getMidiNumberAttributes(startNum);
+ const leftRatio =
+ noteConfig.offsetFromC -
+ this.props.noteConfig[startNoteAttrs.basenote].offsetFromC +
+ octaveWidth * (octave - startNoteAttrs.octave);
return (
<Key
- left={ratioToPercentage(noteConfig.offset * whiteKeyWidth)}
+ left={ratioToPercentage(leftRatio * whiteKeyWidth)}
width={ratioToPercentage(keyConfig.widthRatio * whiteKeyWidth)}
height={ratioToPercentage(keyConfig.heightRatio)}
border={keyConfig.border}
background={keyConfig.background}
zIndex={keyConfig.zIndex}
- key={note}
+ key={num}
/>
);
})} | get startNote/endNote working | kevinsqi_react-piano | train |
6d03c1caab238168c7d091bec82db7a10fd87a2e | diff --git a/lib/pork/imp.rb b/lib/pork/imp.rb
index <HASH>..<HASH> 100644
--- a/lib/pork/imp.rb
+++ b/lib/pork/imp.rb
@@ -44,17 +44,18 @@ module Pork
assertions = stat.assertions
context = new(stat, desc)
seed = Pork.reseed
+
stat.reporter.case_start(context)
+
run_protected(stat, desc, test, seed) do
env.run_before(context)
context.instance_eval(&test)
+ env.run_after(context)
raise Error.new('Missing assertions') if assertions == stat.assertions
stat.reporter.case_pass
end
- ensure
+
stat.incr_tests
- run_protected(stat, desc, test, seed){ env.run_after(context) }
- stat.reporter.case_end
end
def run_protected stat, desc, test, seed
diff --git a/lib/pork/report.rb b/lib/pork/report.rb
index <HASH>..<HASH> 100644
--- a/lib/pork/report.rb
+++ b/lib/pork/report.rb
@@ -9,7 +9,6 @@ module Pork
end
def case_start _; end
- def case_end ; end
def case_pass ; io.print msg_pass ; end
def case_skip ; io.print msg_skip ; end
def case_failed ; io.print msg_failed ; end
diff --git a/lib/pork/report/description.rb b/lib/pork/report/description.rb
index <HASH>..<HASH> 100644
--- a/lib/pork/report/description.rb
+++ b/lib/pork/report/description.rb
@@ -32,7 +32,7 @@ module Pork
self.last_executor = executor
end
- def case_end
+ def case_pass
io.puts
end
end
diff --git a/lib/pork/report/progressbar.rb b/lib/pork/report/progressbar.rb
index <HASH>..<HASH> 100644
--- a/lib/pork/report/progressbar.rb
+++ b/lib/pork/report/progressbar.rb
@@ -75,12 +75,11 @@ module Pork
end
end
- def case_pass ; end
def case_skip ; end
def case_failed ; self.failed = true; end
def case_errored; self.failed = true; end
- def case_end
+ def case_pass
bar.tick
end
diff --git a/test/test_nested.rb b/test/test_nested.rb
index <HASH>..<HASH> 100644
--- a/test/test_nested.rb
+++ b/test/test_nested.rb
@@ -78,3 +78,22 @@ describe Pork::Context do
expect(pork_description).eq desc
end
end
+
+describe 'assertion in after block' do
+ after do
+ ok
+ end
+
+ would do
+ end
+end
+
+would 'raise missing assertion' do
+ stat = Pork::Stat.new(Pork.report_class.new(StringIO.new))
+ executor = Class.new(Pork::Executor){init}
+ executor.would{}
+ stat = executor.execute(Pork.execute_mode, stat)
+ err, _, _ = stat.exceptions.first
+ expect(err).kind_of?(Pork::Error)
+ expect(err.message).eq 'Missing assertions'
+end
diff --git a/test/test_stat.rb b/test/test_stat.rb
index <HASH>..<HASH> 100644
--- a/test/test_stat.rb
+++ b/test/test_stat.rb
@@ -54,6 +54,7 @@ describe Pork::Stat do
err.set_backtrace([])
expect(err).kind_of?(Pork::Error)
+ expect(err.message).eq 'Missing assertions'
expect(@stat.reporter.send(:show_backtrace, test, err)).not.empty?
end | only check if we're missing assertions after after block:
also eliminate case_end because we're not really using it. | godfat_pork | train |
9837940fbd5301da964fdf4b994fef2cccf1bdb9 | diff --git a/bin/echo.php b/bin/echo.php
index <HASH>..<HASH> 100644
--- a/bin/echo.php
+++ b/bin/echo.php
@@ -2,4 +2,4 @@
print json_encode(array_slice($argv,1));
-exit(0);
\ No newline at end of file
+exit(0);
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -13,7 +13,9 @@
"webforge/common": "1.4.x@dev"
},
"require-dev":{
- "webforge/testplate": ">=1.3"
+ "webforge/testplate": ">=1.3",
+ "symfony/console":"2.3.*",
+ "mockery/mockery": "0.8.*@stable"
},
"autoload":{
"psr-0":{
diff --git a/lib/Webforge/Process/System.php b/lib/Webforge/Process/System.php
index <HASH>..<HASH> 100644
--- a/lib/Webforge/Process/System.php
+++ b/lib/Webforge/Process/System.php
@@ -5,13 +5,20 @@ namespace Webforge\Process;
use Webforge\Common\System\System as SystemInterface;
use Symfony\Component\Process\Process As SymfonyProcess;
use Webforge\Common\System\Util as SystemUtil;
+use Webforge\Common\System\Container as SystemContainer;
class System implements SystemInterface {
protected $os;
- public function __construct() {
+ protected $container;
+
+ protected $executables;
+
+ public function __construct(SystemContainer $container) {
$this->os = SystemUtil::isWindows() ? self::WINDOWS : self::UNIX;
+ $this->container = $container;
+ $this->executables = $this->container->getExecutableFinder();
}
/**
@@ -52,6 +59,21 @@ class System implements SystemInterface {
return $process;
}
+ /**
+ * @return Webforge\Process\ProcessBuilder
+ */
+ public function buildProcess() {
+ return ProcessBuilder::create(array());
+ }
+
+ /**
+ * @return Webforge\Process\ProcessBuilder
+ */
+ public function buildPHPProcess() {
+ return ProcessBuilder::create(array(
+ $this->executables->getExecutable('php')
+ ));
+ }
/**
* @inherit-doc
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index <HASH>..<HASH> 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -15,4 +15,8 @@
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
+
+ <listeners>
+ <listener class="\Mockery\Adapter\Phpunit\TestListener"></listener>
+ </listeners>
</phpunit>
\ No newline at end of file
diff --git a/tests/Webforge/Process/SystemTest.php b/tests/Webforge/Process/SystemTest.php
index <HASH>..<HASH> 100644
--- a/tests/Webforge/Process/SystemTest.php
+++ b/tests/Webforge/Process/SystemTest.php
@@ -3,6 +3,8 @@
namespace Webforge\Process;
use Webforge\Common\System\Util as SystemUtil;
+use Mockery as m;
+use Webforge\Common\System\ExecutableFinder;
/**
*
@@ -16,7 +18,10 @@ class SystemTest extends \Webforge\Code\Test\Base {
$this->chainClass = 'Webforge\\Process\\System';
parent::setUp();
- $this->system = new System();
+ $this->systemContainer = m::mock('Webforge\Common\System\Container');
+ $this->systemContainer->shouldReceive('getExecutableFinder')->byDefault()->andReturn(new ExecutableFinder(array()));
+
+ $this->system = new System($this->systemContainer);
if (SystemUtil::isWindows()) {
$this->ls = 'dir';
@@ -64,4 +69,20 @@ class SystemTest extends \Webforge\Code\Test\Base {
public function testProcessWillReturnASymfonyProcess() {
$this->assertInstanceOf('Symfony\Component\Process\Process', $this->system->process($this->ls));
}
+
+ public function testBuildProcessReturnsAProcessBuilder() {
+ $this->assertInstanceOf('Webforge\Process\ProcessBuilder', $this->system->buildProcess());
+ }
+
+
+ public function testBuildPHPProcessReturnsAProcessBuilder_Preconfigured() {
+ $this->assertInstanceOf('Webforge\Process\ProcessBuilder', $builder = $this->system->buildPHPProcess());
+
+ $process = $builder->add('-v')->getProcess();
+
+ $this->assertContains('php', $process->getCommandLine(), 'i expect to find php as an executable in the commandline');
+
+ $this->assertSame(0, $process->run(), $process->getErrorOutput());
+ $this->assertStringStartsWith('PHP '.PHP_VERSION, $process->getOutput(), 'little more acceptance here');
+ }
} | add a buildProcess and a buildPHPProcess function to system | webforge-labs_webforge-process | train |
047872c25eee9f70b5e9e2a67eded2714556e2a7 | diff --git a/packages/@vue/cli-plugin-babel/index.js b/packages/@vue/cli-plugin-babel/index.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-plugin-babel/index.js
+++ b/packages/@vue/cli-plugin-babel/index.js
@@ -40,7 +40,6 @@ module.exports = (api, options) => {
'@babel/core': require('@babel/core/package.json').version,
'@vue/babel-preset-app': require('@vue/babel-preset-app/package.json').version,
'babel-loader': require('babel-loader/package.json').version,
- modern: !!process.env.VUE_CLI_MODERN_BUILD,
browserslist: api.service.pkg.browserslist
}, [
'babel.config.js',
diff --git a/packages/@vue/cli-plugin-typescript/index.js b/packages/@vue/cli-plugin-typescript/index.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-plugin-typescript/index.js
+++ b/packages/@vue/cli-plugin-typescript/index.js
@@ -30,8 +30,7 @@ module.exports = (api, options) => {
loader: 'cache-loader',
options: api.genCacheConfig('ts-loader', {
'ts-loader': require('ts-loader/package.json').version,
- 'typescript': require('typescript/package.json').version,
- modern: !!process.env.VUE_CLI_MODERN_BUILD
+ 'typescript': require('typescript/package.json').version
}, 'tsconfig.json')
})
diff --git a/packages/@vue/cli-service/lib/PluginAPI.js b/packages/@vue/cli-service/lib/PluginAPI.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-service/lib/PluginAPI.js
+++ b/packages/@vue/cli-service/lib/PluginAPI.js
@@ -139,8 +139,7 @@ class PluginAPI {
partialIdentifier,
'cli-service': require('../package.json').version,
'cache-loader': require('cache-loader/package.json').version,
- env: process.env.NODE_ENV,
- test: !!process.env.VUE_CLI_TEST,
+ env: process.env,
config: [
this.service.projectOptions.chainWebpack,
this.service.projectOptions.configureWebpack | fix: take all env variables into account in `genCacheConfig`
fixes #<I> | vuejs_vue-cli | train |
b326c86b4594dfad920e1779c868feb6b9bf0631 | diff --git a/views/js/qtiCommonRenderer/renderers/interactions/ChoiceInteraction.js b/views/js/qtiCommonRenderer/renderers/interactions/ChoiceInteraction.js
index <HASH>..<HASH> 100755
--- a/views/js/qtiCommonRenderer/renderers/interactions/ChoiceInteraction.js
+++ b/views/js/qtiCommonRenderer/renderers/interactions/ChoiceInteraction.js
@@ -300,7 +300,7 @@ define([
var $container = containerHelper.get(interaction);
try{
- _.forEach(pciResponse.unserialize(response, interaction), function(identifier){
+ _.forEach(pciResponse.unserialize(response, interaction), function(identifier){
var $input = $container.find('.real-label > input[value=' + identifier + ']').prop('checked', true);
$input.closest('.qti-choice').toggleClass('user-selected', true);
});
@@ -327,6 +327,16 @@ define([
};
/**
+ * Check if a choice interaction is choice-eliminable
+ *
+ * @param {Object} interaction
+ * @returns {boolean}
+ */
+ var isEliminable = function isEliminable(interaction){
+ return (/\beliminable\b/).test(interaction.attr('class'));
+ };
+
+ /**
* Set additional data to the template (data that are not really part of the model).
* @param {Object} interaction - the interaction
* @param {Object} [data] - interaction custom data
@@ -342,16 +352,6 @@ define([
};
/**
- * Check if a choice interaction is choice-eliminable
- *
- * @param {Object} interaction
- * @returns {boolean}
- */
- var isEliminable = function isEliminable(interaction){
- return (/\beliminable\b/).test(interaction.attr('class'));
- };
-
- /**
* Destroy the interaction by leaving the DOM exactly in the same state it was before loading the interaction.
* @param {Object} interaction - the interaction
*/
@@ -412,9 +412,9 @@ define([
//restore eliminated choices
if(isEliminable(interaction) && _.isArray(state.eliminated) && state.eliminated.length){
- _.forEach(state.eliminated, function(identifier){
+ _.forEach(state.eliminated, function(identifier){
$container.find('.qti-simpleChoice[data-identifier=' + identifier + ']').addClass('eliminated');
- })
+ });
}
}
}; | Eslint issues only
tao-<I> | oat-sa_extension-tao-itemqti | train |
2a68c5d9b94a7f218bc86f2727a5389b289e70df | diff --git a/admin/maintenance.php b/admin/maintenance.php
index <HASH>..<HASH> 100644
--- a/admin/maintenance.php
+++ b/admin/maintenance.php
@@ -59,10 +59,6 @@
echo '</div>';
echo '</form>';
echo '</div>';
-
- if ($usehtmleditor) {
- use_html_editor();
- }
}
admin_externalpage_print_footer();
diff --git a/admin/roles/manage.php b/admin/roles/manage.php
index <HASH>..<HASH> 100755
--- a/admin/roles/manage.php
+++ b/admin/roles/manage.php
@@ -500,10 +500,6 @@
include_once('manage.html');
print_simple_box_end();
- if ($usehtmleditor) {
- use_html_editor('description');
- }
-
} else {
print_heading_with_help(get_string('roles', 'role'), 'roles');
diff --git a/admin/settings.php b/admin/settings.php
index <HASH>..<HASH> 100644
--- a/admin/settings.php
+++ b/admin/settings.php
@@ -163,10 +163,6 @@ if (empty($SITE->fullname)) {
echo '</tr></table>';
}
-if (!empty($CFG->adminusehtmleditor)) {
- use_html_editor();
-}
-
print_footer();
?>
diff --git a/admin/upgradesettings.php b/admin/upgradesettings.php
index <HASH>..<HASH> 100644
--- a/admin/upgradesettings.php
+++ b/admin/upgradesettings.php
@@ -63,10 +63,6 @@ echo '<div class="form-buttons"><input class="form-submit" type="submit" value="
echo '</div>';
echo '</form>';
-if (!empty($CFG->adminusehtmleditor)) {
- use_html_editor();
-}
-
print_footer();
?>
diff --git a/blocks/html/config_instance.html b/blocks/html/config_instance.html
index <HASH>..<HASH> 100755
--- a/blocks/html/config_instance.html
+++ b/blocks/html/config_instance.html
@@ -13,7 +13,3 @@
<input type="submit" value="<?php print_string('savechanges') ?>" /></td>
</tr>
</table>
-<?php if ($usehtmleditor) {
- use_html_editor();
- }
-?>
diff --git a/calendar/event.php b/calendar/event.php
index <HASH>..<HASH> 100644
--- a/calendar/event.php
+++ b/calendar/event.php
@@ -519,9 +519,6 @@
}
else {
include('event_new.html');
- if ($usehtmleditor) {
- use_html_editor("description");
- }
}
break;
diff --git a/lib/questionlib.php b/lib/questionlib.php
index <HASH>..<HASH> 100644
--- a/lib/questionlib.php
+++ b/lib/questionlib.php
@@ -1674,10 +1674,6 @@ function question_print_comment_box($question, $state, $attempt, $url) {
echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
echo '</form>';
-
- if ($usehtmleditor) {
- use_html_editor();
- }
}
/** | MDL-<I>: remove a few calls use_html_editor() (more to come) | moodle_moodle | train |
0b52654a590888144b9814449135cc295c972c2b | diff --git a/okcupyd/user.py b/okcupyd/user.py
index <HASH>..<HASH> 100644
--- a/okcupyd/user.py
+++ b/okcupyd/user.py
@@ -11,7 +11,7 @@ from .photo import PhotoUploader
from .profile import Profile
from .profile_copy import Copy
from .question import Questions
-from .search import SearchFetchable, search
+from .html_search import SearchFetchable, search
from .session import Session
from .xpath import xpb
diff --git a/tests/search_filters_test.py b/tests/search_filters_test.py
index <HASH>..<HASH> 100644
--- a/tests/search_filters_test.py
+++ b/tests/search_filters_test.py
@@ -1,4 +1,4 @@
-from okcupyd.search_filters import search_filters
+from okcupyd.json_search import search_filters
def test_gentation(): | Fix import errors from last two changes. | IvanMalison_okcupyd | train |
d46d23d814d5c8163940fdaad5106e2e158d5b68 | diff --git a/lib/dicom/d_read.rb b/lib/dicom/d_read.rb
index <HASH>..<HASH> 100755
--- a/lib/dicom/d_read.rb
+++ b/lib/dicom/d_read.rb
@@ -223,7 +223,7 @@ module DICOM
# Create an ordinary Data Element:
@current_element = Element.new(tag, value, :bin => bin, :name => name, :parent => @current_parent, :vr => vr)
# Check that the data stream didnt end abruptly:
- raise "The actual length of the value (#{@current_element.bin.length}) does not match the specified length (#{length}) for Data Element #{@current_element.tag}" if length != @current_element.bin.length
+ raise "The actual length of the value (#{@current_element.bin.length}) does not match its specified length (#{length}) for Data Element #{@current_element.tag}" if length != @current_element.bin.length
end
# Return true to indicate success:
return true | A minor tweak to an error message. | dicom_ruby-dicom | train |
abbf668b4f2b099d1a8c5497fed7d65b8b638cfd | diff --git a/salt/modules/status.py b/salt/modules/status.py
index <HASH>..<HASH> 100644
--- a/salt/modules/status.py
+++ b/salt/modules/status.py
@@ -3,19 +3,19 @@
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
-from __future__ import absolute_import
# Import python libs
import os
import re
import fnmatch
+from __future__ import absolute_import
+from six.moves import range
# Import salt libs
import salt.utils
from salt.utils.network import remote_port_tcp as _remote_port_tcp
import salt.utils.event
import salt.config
-from six.moves import range
__opts__ = {}
@@ -105,7 +105,7 @@ def custom():
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
- for key, val in list(conf.items()):
+ for key, val in conf.items():
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123 | List call not needed. Changing it back to what it was | saltstack_salt | train |
cb40ae38c1f650846570ad9e3c1b047797e879f6 | diff --git a/activesupport/lib/active_support/core_ext/object/json.rb b/activesupport/lib/active_support/core_ext/object/json.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/object/json.rb
+++ b/activesupport/lib/active_support/core_ext/object/json.rb
@@ -49,6 +49,12 @@ end
klass.prepend(ActiveSupport::ToJsonWithActiveSupportEncoder)
end
+class Module
+ def as_json(options = nil) #:nodoc:
+ name
+ end
+end
+
class Object
def as_json(options = nil) #:nodoc:
if respond_to?(:to_hash)
diff --git a/activesupport/test/json/encoding_test_cases.rb b/activesupport/test/json/encoding_test_cases.rb
index <HASH>..<HASH> 100644
--- a/activesupport/test/json/encoding_test_cases.rb
+++ b/activesupport/test/json/encoding_test_cases.rb
@@ -68,6 +68,10 @@ module JSONTest
[ :this, %("this") ],
[ :"a b", %("a b") ]]
+ ModuleTests = [[ Module, %("Module") ],
+ [ Class, %("Class") ],
+ [ ActiveSupport, %("ActiveSupport") ],
+ [ ActiveSupport::MessageEncryptor, %("ActiveSupport::MessageEncryptor") ]]
ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
HashlikeTests = [[ Hashlike.new, %({\"bar\":\"world\",\"foo\":\"hello\"}) ]]
StructTests = [[ MyStruct.new(:foo, "bar"), %({\"name\":\"foo\",\"value\":\"bar\"}) ], | Allow any module or class to be converted to JSON in a simple way | rails_rails | train |
a31e61fe60a4c0d0d96adcd4d59366f5089fac71 | diff --git a/src/Mordilion/Configurable/Configurable.php b/src/Mordilion/Configurable/Configurable.php
index <HASH>..<HASH> 100644
--- a/src/Mordilion/Configurable/Configurable.php
+++ b/src/Mordilion/Configurable/Configurable.php
@@ -33,16 +33,17 @@ trait Configurable
* This method will add the provided configuration to the object configuration.
*
* @param mixed $configuration
+ * @param boolean $configure
*
* @return ConfigurableInterface
*/
- public function addConfiguration($configuration)
+ public function addConfiguration($configuration, $configure = true)
{
if (!$configuration instanceof ConfigurationInterface) {
$configuration = new Configuration($configuration);
}
- $config = $this->configuration;
+ $config = $this->getConfiguration();
if ($config instanceof ConfigurationInterface) {
$config->merge($configuration);
@@ -50,7 +51,21 @@ trait Configurable
$config = $configuration;
}
- $this->setConfiguration($config);
+ $this->setConfiguration($config, $configure);
+ }
+
+ /**
+ * Configures the object with the current configuration.
+ *
+ * @return void
+ */
+ public function configure()
+ {
+ $configuration = $this->getConfiguration();
+
+ if ($configuration instanceof ConfigurationInterface) {
+ $this->configuration->configure($this);
+ }
}
/**
@@ -67,20 +82,22 @@ trait Configurable
* This method will configure the object with the provided configuration.
*
* @param mixed $configuration
+ * @param boolean $configure
*
* @return ConfigurableInterface
*/
- public function setConfiguration($configuration)
+ public function setConfiguration($configuration, $configure = true)
{
if (!$configuration instanceof ConfigurationInterface) {
$configuration = new Configuration($configuration);
}
- if ($this->configuration instanceof ConfigurationInterface) {
- unset($this->configuration); // destroy the old one
- }
+ unset($this->configuration); // destroy the old one
$this->configuration = $configuration;
- $this->configuration->configure($this);
+
+ if ($configure) {
+ $this->configure();
+ }
}
}
\ No newline at end of file
diff --git a/tests/Mordilion/Configurable/ConfigurableTest.php b/tests/Mordilion/Configurable/ConfigurableTest.php
index <HASH>..<HASH> 100644
--- a/tests/Mordilion/Configurable/ConfigurableTest.php
+++ b/tests/Mordilion/Configurable/ConfigurableTest.php
@@ -41,6 +41,32 @@ class ConfigurableTest extends TestCase
$this->assertEquals($configurationArray['param4'], $valueBoolean);
}
+ public function testSetConfigurationWithArrayAndConfigureFalse()
+ {
+ $object = new TestTrait();
+
+ $valueString = 'That\'s a String';
+
+ $object->setConfiguration(array(
+ 'property1' => $valueString
+ ), false);
+
+ $configuration = $object->getConfiguration();
+ $configurationArray = $configuration->toArray();
+
+ $this->assertInstanceOf(Configuration::class, $configuration);
+ $this->assertFalse(isset($object->property1));
+ $this->assertEquals($configurationArray['property1'], $valueString);
+
+ $object->configure();
+
+ $configuration = $object->getConfiguration();
+ $configurationArray = $configuration->toArray();
+
+ $this->assertTrue(isset($object->property1));
+ $this->assertEquals($object->property1, $valueString);
+ }
+
public function testSetConfigurationWithConfigurationObject()
{
$mock = $this->getMockForTrait(Configurable::class);
@@ -151,4 +177,11 @@ class ConfigurableTest extends TestCase
$this->assertEquals($configurationArray['param5'], $valueString);
$this->assertEquals($configurationArray['param6'], $valueInteger);
}
+}
+
+class TestTrait
+{
+ use Configurable;
+
+ public $property1 = null;
}
\ No newline at end of file | added support to just add the configuration with out configure the object | mordilion_Configurable | train |
50628518f0cfdfef21187d7a8a6c18d8bae1c23a | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ You can find and compare releases at the [GitHub release page](https://github.co
- Clarify semantics of combining `@search` with other directives https://github.com/nuwave/lighthouse/pull/1691
- Move Scout related classes into `\Nuwave\Lighthouse\Scout` https://github.com/nuwave/lighthouse/pull/1698
- `BaseDirective` loads all arguments and caches them after the first `directiveHasArgument`/`directiveArgValue` call https://github.com/nuwave/lighthouse/pull/1707
+- `@can` will pass the message given in a `\Illuminate\Auth\Access\AuthorizationException` response returned by a policy method to the thrown GraphQL error https://github.com/nuwave/lighthouse/pull/1715
### Deprecated
diff --git a/src/Schema/Directives/CanDirective.php b/src/Schema/Directives/CanDirective.php
index <HASH>..<HASH> 100644
--- a/src/Schema/Directives/CanDirective.php
+++ b/src/Schema/Directives/CanDirective.php
@@ -15,6 +15,7 @@ use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\SoftDeletes\ForceDeleteDirective;
use Nuwave\Lighthouse\SoftDeletes\RestoreDirective;
use Nuwave\Lighthouse\SoftDeletes\TrashedDirective;
+use Nuwave\Lighthouse\Support\AppVersion;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Nuwave\Lighthouse\Support\Utils;
@@ -176,10 +177,24 @@ GRAPHQL;
// should be [modelClassName, additionalArg, additionalArg...]
array_unshift($arguments, $model);
- if (! $gate->check($ability, $arguments)) {
- throw new AuthorizationException(
- "You are not authorized to access {$this->nodeName()}"
+ // Gate responses were introduced in Laravel 6
+ if (AppVersion::atLeast(6.0)) {
+ Utils::applyEach(
+ function ($ab) use ($gate, $arguments) {
+ $response = $gate->inspect($ab, $arguments);
+
+ if ($response->denied()) {
+ throw new AuthorizationException($response->message(), $response->code());
+ }
+ },
+ $ability
);
+ } else {
+ if (! $gate->check($ability, $arguments)) {
+ throw new AuthorizationException(
+ "You are not authorized to access {$this->nodeName()}"
+ );
+ }
}
}
diff --git a/tests/Unit/Schema/Directives/CanDirectiveTest.php b/tests/Unit/Schema/Directives/CanDirectiveTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/Schema/Directives/CanDirectiveTest.php
+++ b/tests/Unit/Schema/Directives/CanDirectiveTest.php
@@ -35,6 +35,80 @@ class CanDirectiveTest extends TestCase
')->assertGraphQLErrorCategory(AuthorizationException::CATEGORY);
}
+ public function testThrowsWithCustomMessageIfNotAuthorized(): void
+ {
+ if (AppVersion::below(6.0)) {
+ $this->markTestSkipped('Version less than 6.0 do not support gate responses.');
+ }
+
+ $this->be(new User);
+
+ $this->schema = /** @lang GraphQL */ '
+ type Query {
+ user: User!
+ @can(ability: "superAdminOnly")
+ @mock
+ }
+
+ type User {
+ name: String
+ }
+ ';
+
+ $response = $this->graphQL(/** @lang GraphQL */ '
+ {
+ user {
+ name
+ }
+ }
+ ');
+ $response->assertGraphQLErrorCategory(AuthorizationException::CATEGORY);
+ $response->assertJson([
+ 'errors' => [
+ [
+ 'message' => UserPolicy::SUPER_ADMINS_ONLY_MESSAGE,
+ ],
+ ],
+ ]);
+ }
+
+ public function testThrowsFirstWithCustomMessageIfNotAuthorized(): void
+ {
+ if (AppVersion::below(6.0)) {
+ $this->markTestSkipped('Version less than 6.0 do not support gate responses.');
+ }
+
+ $this->be(new User);
+
+ $this->schema = /** @lang GraphQL */ '
+ type Query {
+ user: User!
+ @can(ability: ["superAdminOnly", "adminOnly"])
+ @mock
+ }
+
+ type User {
+ name: String
+ }
+ ';
+
+ $response = $this->graphQL(/** @lang GraphQL */ '
+ {
+ user {
+ name
+ }
+ }
+ ');
+ $response->assertGraphQLErrorCategory(AuthorizationException::CATEGORY);
+ $response->assertJson([
+ 'errors' => [
+ [
+ 'message' => UserPolicy::SUPER_ADMINS_ONLY_MESSAGE,
+ ],
+ ],
+ ]);
+ }
+
public function testPassesAuthIfAuthorized(): void
{
$user = new User;
diff --git a/tests/Utils/Policies/UserPolicy.php b/tests/Utils/Policies/UserPolicy.php
index <HASH>..<HASH> 100644
--- a/tests/Utils/Policies/UserPolicy.php
+++ b/tests/Utils/Policies/UserPolicy.php
@@ -2,17 +2,30 @@
namespace Tests\Utils\Policies;
+use Illuminate\Auth\Access\Response;
use Tests\Utils\Models\User;
class UserPolicy
{
+ public const SUPER_ADMIN = 'super admin';
public const ADMIN = 'admin';
+ public const SUPER_ADMINS_ONLY_MESSAGE = 'Only super admins allowed';
+
public function adminOnly(User $user): bool
{
return $user->name === self::ADMIN;
}
+ public function superAdminOnly(User $user): Response
+ {
+ if ($user->name === self::SUPER_ADMIN) {
+ return Response::allow();
+ }
+
+ return Response::deny(self::SUPER_ADMINS_ONLY_MESSAGE);
+ }
+
public function alwaysTrue(): bool
{
return true; | Use gate response in authorization errors of `@can` directive (#<I>) | nuwave_lighthouse | train |
d8b4c630f16f08cd27c14d11e45a7a9d435621a8 | diff --git a/lib/dpl/provider/heroku/git.rb b/lib/dpl/provider/heroku/git.rb
index <HASH>..<HASH> 100644
--- a/lib/dpl/provider/heroku/git.rb
+++ b/lib/dpl/provider/heroku/git.rb
@@ -19,9 +19,14 @@ module DPL
end
def check_app
- info = api.get_app(option(:app)).body
- options[:git] ||= info['git_url']
- log "found app #{info['name']}"
+ begin
+ log "checking for app '#{option(:app)}'"
+ info = api.get_app(option(:app)).body
+ options[:git] ||= info['git_url']
+ log "found app '#{info['name']}'"
+ rescue ::Heroku::API::Errors::Forbidden => error
+ raise Error, "#{error.message} (does the app '#{option(:app)}' exist and does #{user} have access to it?)", error.backtrace
+ end
end
def setup_key(file)
@@ -56,4 +61,4 @@ module DPL
end
end
end
-end
\ No newline at end of file
+end | Adding additional info and error handling when attempting to discover a heroku app. This helps resolve an issue where the app may be mispelled or otherwise incorrect in .travis.yml and will now provide a more useful error than <I> Forbidden | travis-ci_dpl | train |
782aafd16a1cc88b701d78b8fc7e442e319030ad | diff --git a/react-packager/src/SocketInterface/index.js b/react-packager/src/SocketInterface/index.js
index <HASH>..<HASH> 100644
--- a/react-packager/src/SocketInterface/index.js
+++ b/react-packager/src/SocketInterface/index.js
@@ -18,7 +18,7 @@ const path = require('path');
const tmpdir = require('os').tmpdir();
const {spawn} = require('child_process');
-const CREATE_SERVER_TIMEOUT = 10000;
+const CREATE_SERVER_TIMEOUT = 30000;
const SocketInterface = {
getOrCreateSocketFor(options) { | [react-native] bump create server timeout | facebook_metro | train |
4cc2dde30c7bf61a2ab548269522bcdc8beac3d7 | diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php
index <HASH>..<HASH> 100644
--- a/modules/saml/lib/Auth/Source/SP.php
+++ b/modules/saml/lib/Auth/Source/SP.php
@@ -252,6 +252,9 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source {
$ar->setExtensions($state['saml:Extensions']);
}
+ // save IdP entity ID as part of the state
+ $state['ExpectedIssuer'] = $idpMetadata->getString('entityid');
+
$id = SimpleSAML_Auth_State::saveState($state, 'saml:sp:sso', TRUE);
$ar->setId($id);
diff --git a/modules/saml/www/sp/saml2-acs.php b/modules/saml/www/sp/saml2-acs.php
index <HASH>..<HASH> 100644
--- a/modules/saml/www/sp/saml2-acs.php
+++ b/modules/saml/www/sp/saml2-acs.php
@@ -58,6 +58,12 @@ if (!empty($stateId)) {
if ($state['saml:sp:AuthId'] !== $sourceId) {
throw new SimpleSAML_Error_Exception('The authentication source id in the URL does not match the authentication source which sent the request.');
}
+
+ /* Check that the issuer is the one we are expecting. */
+ assert('array_key_exists("ExpectedIssuer", $state)');
+ if ($state['ExpectedIssuer'] !== $idp) {
+ throw new SimpleSAML_Error_Exception('The issuer of the response does not match to the identity provider we sent the request to.');
+ }
} else {
/* This is an unsolicited response. */
$state = array( | The issuer of an AuthnResponse is now validated to check if we get the response from the same entity ID we sent the request to. | simplesamlphp_saml2 | train |
6b448cffe55a79637b9dee0beac55904c307fdb0 | diff --git a/cmd/bleve/cmd/root.go b/cmd/bleve/cmd/root.go
index <HASH>..<HASH> 100644
--- a/cmd/bleve/cmd/root.go
+++ b/cmd/bleve/cmd/root.go
@@ -27,6 +27,10 @@ var cfgFile string
var idx bleve.Index
+// DefaultOpenReadOnly allows some distributions of this command to default
+// to always opening the index read-only
+var DefaultOpenReadOnly = false
+
const canMutateBleveIndex = "canMutateBleveIndex"
// CanMutateBleveIndex returns true if the command is capable
@@ -52,8 +56,11 @@ var RootCmd = &cobra.Command{
if len(args) < 1 {
return fmt.Errorf("must specify path to index")
}
+ runtimeConfig := map[string]interface{}{
+ "read_only": DefaultOpenReadOnly,
+ }
var err error
- idx, err = bleve.Open(args[0])
+ idx, err = bleve.OpenUsing(args[0], runtimeConfig)
if err != nil {
return fmt.Errorf("error opening bleve index: %v", err)
} | add ability change default open read-only flag
this change allows an alternate distribution of the bleve
command-line tool to change the default behavior and always
open the index read-only | blevesearch_bleve | train |
8d912779828dc4893d8428c2276bfafc41921fb5 | diff --git a/src/core/class-papi-core-property.php b/src/core/class-papi-core-property.php
index <HASH>..<HASH> 100644
--- a/src/core/class-papi-core-property.php
+++ b/src/core/class-papi-core-property.php
@@ -691,8 +691,8 @@ class Papi_Core_Property {
$type = papi_get_meta_type( $type );
- // Register option fields with the new `register_setting` function.
- if ( $type === 'option' ) {
+ // Register option fields with the new `register_setting` function and only for WordPress 4.7.
+ if ( $type === 'option' && version_compare( get_bloginfo( 'version' ), '4.7', '>=' ) ) {
// The `type` will be the same for each fields, this is just to get it out
// to the REST API, the output will be different for different fields and are
// handled later on.
diff --git a/tests/cases/rest-api/class-papi-rest-api-settings-test.php b/tests/cases/rest-api/class-papi-rest-api-settings-test.php
index <HASH>..<HASH> 100644
--- a/tests/cases/rest-api/class-papi-rest-api-settings-test.php
+++ b/tests/cases/rest-api/class-papi-rest-api-settings-test.php
@@ -8,6 +8,10 @@ class Papi_REST_API_Settings_Test extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
+ if ( version_compare( get_bloginfo( 'version' ), '4.7', '<' ) ) {
+ $this->markTestSkipped( '`register_settings` is only supported in WordPress 4.7 and later' );
+ }
+
add_filter( 'papi/settings/directories', function () {
return PAPI_FIXTURE_DIR . '/page-types/options';
} ); | Only run register_settings tests on <I> or newer | wp-papi_papi | train |
7298d97f1f52b7a89fc99a0ac193495d14fd6fc0 | diff --git a/raven/utils/stacks.py b/raven/utils/stacks.py
index <HASH>..<HASH> 100644
--- a/raven/utils/stacks.py
+++ b/raven/utils/stacks.py
@@ -131,7 +131,7 @@ def iter_traceback_frames(tb):
while tb:
# support for __traceback_hide__ which is used by a few libraries
# to hide internal frames.
- f_locals = tb.tb_frame.f_locals
+ f_locals = getattr(tb.tb_frame, 'f_locals', {})
if not _getitem_from_frame(f_locals, '__traceback_hide__'):
yield tb.tb_frame
tb = tb.tb_next
@@ -146,7 +146,7 @@ def iter_stack_frames(frames=None):
if not frames:
frames = inspect.stack()[1:]
for frame in (f[0] for f in frames):
- f_locals = frame.f_locals
+ f_locals = getattr(frame, 'f_locals', {})
if _getitem_from_frame(f_locals, '__traceback_hide__'):
continue
yield frame
@@ -160,15 +160,16 @@ def get_stack_info(frames):
results = []
for frame in frames:
# Support hidden frames
- f_locals = frame.f_locals
+ f_locals = getattr(frame, 'f_locals', {})
if _getitem_from_frame(f_locals, '__traceback_hide__'):
continue
+ f_globals = getattr(frame, 'f_globals', {})
abs_path = frame.f_code.co_filename
function = frame.f_code.co_name
lineno = frame.f_lineno - 1
- loader = frame.f_globals.get('__loader__')
- module_name = frame.f_globals.get('__name__')
+ loader = f_globals.get('__loader__')
+ module_name = f_globals.get('__name__')
pre_context, context_line, post_context = get_lines_from_file(abs_path, lineno, 3, loader, module_name)
# Try to pull a relative file path
@@ -180,14 +181,12 @@ def get_stack_info(frames):
filename = abs_path
if context_line:
- f_locals = frame.f_locals
- if not isinstance(f_locals, dict):
+ if f_locals is not None and not isinstance(f_locals, dict):
# XXX: Genshi (and maybe others) have broken implementations of
# f_locals that are not actually dictionaries
try:
f_locals = to_dict(f_locals)
- except Exception, e:
- print e
+ except Exception:
f_locals = '<invalid local scope>'
results.append({
'abs_path': abs_path, | Handle frames that are missing f_globals and f_locals (fixes GH-<I>) | elastic_apm-agent-python | train |
f46c0b5219b028aca8c44f8665dd08a2e51179c8 | diff --git a/src/sap.m/src/sap/m/Menu.js b/src/sap.m/src/sap/m/Menu.js
index <HASH>..<HASH> 100644
--- a/src/sap.m/src/sap/m/Menu.js
+++ b/src/sap.m/src/sap/m/Menu.js
@@ -16,7 +16,6 @@ sap.ui.define([
'sap/ui/unified/MenuItem',
'sap/ui/Device',
'sap/ui/core/EnabledPropagator',
- 'sap/ui/core/CustomData',
"sap/ui/thirdparty/jquery"
],
function(
@@ -32,7 +31,6 @@ sap.ui.define([
UfdMenuItem,
Device,
EnabledPropagator,
- CustomData,
jQuery
) {
"use strict";
@@ -453,26 +451,15 @@ sap.ui.define([
};
Menu.prototype._createVisualMenuItemFromItem = function(oItem) {
- var oUfdMenuItem = new UfdMenuItem({
- id : this._generateUnifiedMenuItemId(oItem.getId()),
+ return new UfdMenuItem({
+ id: this._generateUnifiedMenuItemId(oItem.getId()),
icon: oItem.getIcon(),
text: oItem.getText(),
startsSection: oItem.getStartsSection(),
tooltip: oItem.getTooltip(),
visible: oItem.getVisible(),
enabled: oItem.getEnabled()
- }),
- aCustomData = oItem.getCustomData();
-
- aCustomData.forEach(function(oData) {
- oUfdMenuItem.addCustomData(new CustomData({
- key: oData.getKey(),
- value: oData.getValue(),
- writeToDom: oData.getWriteToDom()
- }));
});
-
- return oUfdMenuItem;
};
Menu.prototype._addVisualMenuItemFromItem = function(oItem, oMenu, iIndex) {
diff --git a/src/sap.m/test/sap/m/qunit/Menu.qunit.js b/src/sap.m/test/sap/m/qunit/Menu.qunit.js
index <HASH>..<HASH> 100755
--- a/src/sap.m/test/sap/m/qunit/Menu.qunit.js
+++ b/src/sap.m/test/sap/m/qunit/Menu.qunit.js
@@ -1192,25 +1192,4 @@ sap.ui.define([
// Assert
assert.strictEqual(oUfdMenu.enhanceAccessibilityState(oButton, oAriaProps).controls, "sControlId", "Should return also the additional mAriaProps if a custom function is set");
});
-
- QUnit.test("Custom data is propagated properly", function (oAssert) {
- var oItem = new MenuItem(),
- oUfdItem,
- oUfdItemCustomData;
-
- // Arrange
- oItem.addCustomData(new CustomData({
- key: "customKey",
- value: "customValue",
- writeToDom: true
- }));
-
- oUfdItem = this.oMenu._createVisualMenuItemFromItem(oItem);
- oUfdItemCustomData = oUfdItem.getCustomData()[0];
-
- // Assert
- assert.strictEqual(oUfdItemCustomData.getKey(), "customKey", "Custom data's key is propagated properly to the Unified menu item");
- assert.strictEqual(oUfdItemCustomData.getValue(), "customValue", "Custom data's value is propagated properly to the Unified menu item");
- assert.strictEqual(oUfdItemCustomData.getWriteToDom(), true, "Custom data's writeToDom is propagated properly to the Unified menu item");
- });
});
\ No newline at end of file | [FIX] sap.m.Menu: Custom data is not propagated to the visual items
The sap.m.Menu uses another control for its visual interface. It does
not need to pass custom data to its rendered items.
Change-Id: I7ef0cfe<I>f<I>c<I>c<I>e3a7d9e0caf<I>b<I>
BCP: <I> | SAP_openui5 | train |
4572ac73a728fd5235981d45cc3fc28fc32dcff5 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -37,7 +37,7 @@ setup(
packages=find_packages(),
include_package_data=True,
install_requires=[
- 'Click',
+ 'Click>=3.3',
'rfc3987',
],
entry_points=''' | Denote that latest version of click is required (#<I>) | msanders_cider | train |
4d96bdd624b9287526dd12a2b3bb12d7154a4f91 | diff --git a/tests/frontend/org/voltdb/dtxn/TestHashMismatches.java b/tests/frontend/org/voltdb/dtxn/TestHashMismatches.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/dtxn/TestHashMismatches.java
+++ b/tests/frontend/org/voltdb/dtxn/TestHashMismatches.java
@@ -519,6 +519,12 @@ public class TestHashMismatches extends JUnit4LocalClusterTest {
long mprows = vt.asScalarLong();
client.drain();
+ File tempDir = new File(TMPDIR);
+ if (!tempDir.exists()) {
+ assertTrue(tempDir.mkdirs());
+ }
+ deleteTestFiles(TESTNONCE);
+
System.out.println("Saving snapshot...");
ClientResponse resp = client.callProcedure("@SnapshotSave", TMPDIR, TESTNONCE, (byte) 1);
vt = resp.getResults()[0]; | ENG-<I>:
Fix up unit test that does not initialize or clean up the snapshot dir shared by another test in the same suite. | VoltDB_voltdb | train |
da3e36675865486cb3c7ddc4ce05c82e64a06402 | diff --git a/modules/ve2/ui/tools/ve.ui.ClearButtonTool.js b/modules/ve2/ui/tools/ve.ui.ClearButtonTool.js
index <HASH>..<HASH> 100644
--- a/modules/ve2/ui/tools/ve.ui.ClearButtonTool.js
+++ b/modules/ve2/ui/tools/ve.ui.ClearButtonTool.js
@@ -39,7 +39,6 @@ ve.ui.ClearButtonTool.prototype.onClick = function() {
var surfaceView = this.toolbar.getSurfaceView(),
model = surfaceView.getModel();
- model.annotate( 'clear', this.getAnnotation() );
surfaceView.showSelection( model.getSelection() );
//surfaceView.clearInsertionAnnotations();
surfaceView.contextView.closeInspector();
diff --git a/modules/ve2/ui/ve.ui.Toolbar.js b/modules/ve2/ui/ve.ui.Toolbar.js
index <HASH>..<HASH> 100644
--- a/modules/ve2/ui/ve.ui.Toolbar.js
+++ b/modules/ve2/ui/ve.ui.Toolbar.js
@@ -16,55 +16,9 @@ ve.ui.Toolbar = function( $container, surfaceView, config ) {
this.$groups = $( '<div class="es-toolbarGroups"></div>' ).prependTo( this.$ );
this.tools = [];
- // Listen to the model for selection event
- this.surfaceView.model.on( 'select', function( e ){
-
- var model = _this.surfaceView.getModel(),
- doc = model.getDocument(),
- annotations,
- nodes = [],
- startNode,
- endNode;
-
- if( e !== null ) {
- if ( e.from === e.to ){
- nodes.push( doc.getNodeFromOffset( e.from ) );
- } else {
- startNode = doc.getNodeFromOffset( e.from );
- endNode = doc.getNodeFromOffset ( e.end );
- // These should be different, alas just in case.
- if ( startNode === endNode ) {
- nodes.push( startNode );
-
- } else {
- model.getDocument().getDocumentNode().traverseLeafNodes( function( node ) {
- nodes.push( node );
- if( node === endNode ) {
- return false;
- }
- }, startNode );
- }
- }
- // Update Context
- if ( e.getLength() > 0 ) {
- _this.surfaceView.contextView.set();
- } else {
- _this.surfaceView.contextView.clear();
- }
-
- annotations = doc.getAnnotationsFromRange( e );
- // Update state
- for ( i = 0; i < _this.tools.length; i++ ) {
- _this.tools[i].updateState( annotations, nodes );
- }
- } else {
- // Clear state
- _this.surfaceView.contextView.clear();
- for ( i = 0; i < _this.tools.length; i++ ) {
- _this.tools[i].clearState();
- }
- }
- });
+ // Update tools on selection, and transactions.
+ this.surfaceView.model.on( 'select', ve.proxy( this.updateTools, this ) );
+ this.surfaceView.model.on( 'transact', ve.proxy( this.updateTools, this ) );
this.config = config || [
{ 'name': 'history', 'items' : ['undo', 'redo'] },
@@ -78,6 +32,60 @@ ve.ui.Toolbar = function( $container, surfaceView, config ) {
/* Methods */
+ve.ui.Toolbar.prototype.updateTools = function( e ) {
+ var _this = this,
+ model = _this.surfaceView.getModel(),
+ doc = model.getDocument(),
+ annotations,
+ nodes = [],
+ startNode,
+ endNode;
+
+ // if not a select event, update from selection
+ if (e.from === undefined) {
+ e = model.getSelection();
+ }
+
+ if( e !== null ) {
+ if ( e.from === e.to ){
+ nodes.push( doc.getNodeFromOffset( e.from ) );
+ } else {
+ startNode = doc.getNodeFromOffset( e.from );
+ endNode = doc.getNodeFromOffset ( e.end );
+ // These should be different, alas just in case.
+ if ( startNode === endNode ) {
+ nodes.push( startNode );
+
+ } else {
+ model.getDocument().getDocumentNode().traverseLeafNodes( function( node ) {
+ nodes.push( node );
+ if( node === endNode ) {
+ return false;
+ }
+ }, startNode );
+ }
+ }
+ // Update Context
+ if ( e.getLength() > 0 ) {
+ _this.surfaceView.contextView.set();
+ } else {
+ _this.surfaceView.contextView.clear();
+ }
+
+ annotations = doc.getAnnotationsFromRange( e );
+ // Update state
+ for ( i = 0; i < _this.tools.length; i++ ) {
+ _this.tools[i].updateState( annotations, nodes );
+ }
+ } else {
+ // Clear state
+ _this.surfaceView.contextView.clear();
+ for ( i = 0; i < _this.tools.length; i++ ) {
+ _this.tools[i].clearState();
+ }
+ }
+};
+
ve.ui.Toolbar.prototype.getSurfaceView = function() {
return this.surfaceView;
}; | Updating tools on transactions. Working towards finishing clear
button
Change-Id: I7b6f8cae<I>fc<I>b7c8c<I>d<I>e<I>e<I> | wikimedia_parsoid | train |
1e7b2a8df2d411e5d02ffda73938f3cdf8a95cf2 | diff --git a/src/Lucid/Model/index.js b/src/Lucid/Model/index.js
index <HASH>..<HASH> 100644
--- a/src/Lucid/Model/index.js
+++ b/src/Lucid/Model/index.js
@@ -954,10 +954,19 @@ class Model extends BaseModel {
payload = whereClause
}
+ const query = this.query()
+
+ /**
+ * If trx is defined then use it for operation
+ */
+ if (trx) {
+ query.transacting(trx)
+ }
+
/**
* Find a row using where clause
*/
- const row = await this.query().where(whereClause).first()
+ const row = await query.where(whereClause).first()
if (row) {
return row
}
diff --git a/test/unit/lucid.spec.js b/test/unit/lucid.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/lucid.spec.js
+++ b/test/unit/lucid.spec.js
@@ -1657,6 +1657,26 @@ test.group('Model', (group) => {
assert.equal(user.username, 'foo')
})
+ test('create a new row when unable to find one using trx', async (assert) => {
+ class User extends Model {
+ static boot () {
+ super.boot()
+ }
+ }
+
+ User._bootIfNotBooted()
+
+ const count = await ioc.use('Database').table('users').count('* as total')
+ assert.equal(count[0].total, 0)
+
+ const trx = await ioc.use('Database').beginTransaction()
+ const user = await User.findOrCreate({ username: 'foo' }, { username: 'virk' }, trx)
+ await trx.commit()
+
+ assert.isTrue(user.$persisted)
+ assert.equal(user.username, 'virk')
+ })
+
test('return existing row when found one', async (assert) => {
class User extends Model {
}
@@ -1673,6 +1693,29 @@ test.group('Model', (group) => {
assert.equal(helpers.formatQuery(usersQuery.sql), helpers.formatQuery('select * from "users" where "username" = ? limit ?'))
})
+ test('return existing row when found one using trx', async (assert) => {
+ class User extends Model {
+ static boot () {
+ super.boot()
+ }
+ }
+
+ User._bootIfNotBooted()
+
+ let usersQuery = null
+ User.onQuery((query) => (usersQuery = query))
+
+ await ioc.use('Database').table('users').insert({ username: 'foo' })
+
+ const trx = await ioc.use('Database').beginTransaction()
+ const user = await User.findOrCreate({ username: 'foo' }, { username: 'virk' }, trx)
+ await trx.commit()
+
+ assert.isTrue(user.$persisted)
+ assert.equal(user.username, 'foo')
+ assert.equal(helpers.formatQuery(usersQuery.sql), helpers.formatQuery('select * from "users" where "username" = ? limit ?'))
+ })
+
test('pass different payload for create', async (assert) => {
class User extends Model {
} | feat(transaction): add support for transactions in findOrCreate
* Added trx support to findOrCreate
Conditionally use trx when exists in findOrCreate method
* Code style fixes in PR code (trx on findOrCreate)
* Created the test 'create a new row when unable to find one using trx'
* Creating test 'return existing row when found one using trx' | adonisjs_adonis-lucid | train |
e94367ceda47797b404443c55b56d3180d2e5bd7 | diff --git a/install.py b/install.py
index <HASH>..<HASH> 100644
--- a/install.py
+++ b/install.py
@@ -417,15 +417,6 @@ class Downloader(object):
def _get_candidate_archive_dicts(self):
archive_dicts = []
- if self.rpm_py_version.is_release:
- url = self._get_rpm_org_archive_url()
- top_dir_name = self._get_rpm_org_archive_top_dir_name()
- archive_dicts.append({
- 'site': 'rpm.org',
- 'url': url,
- 'top_dir_name': top_dir_name,
- })
-
tag_names = self._predict_candidate_git_tag_names()
for tag_name in tag_names:
url = self._get_git_hub_archive_url(tag_name)
@@ -436,6 +427,17 @@ class Downloader(object):
'top_dir_name': top_dir_name,
})
+ # Set rpm.org server as a secondary server, because it takes long time
+ # to download an archive. GitHub is better to download the archive.
+ if self.rpm_py_version.is_release:
+ url = self._get_rpm_org_archive_url()
+ top_dir_name = self._get_rpm_org_archive_top_dir_name()
+ archive_dicts.append({
+ 'site': 'rpm.org',
+ 'url': url,
+ 'top_dir_name': top_dir_name,
+ })
+
return archive_dicts
def _get_rpm_org_archive_url(self):
diff --git a/tests/test_install.py b/tests/test_install.py
index <HASH>..<HASH> 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -563,12 +563,6 @@ def test_downloader_download_and_expand_from_archive_url(
'4.13.0',
[
{
- 'site': 'rpm.org',
- 'url': 'http://ftp.rpm.org/releases/'
- 'rpm-4.13.x/rpm-4.13.0.tar.gz',
- 'top_dir_name': 'rpm-4.13.0',
- },
- {
'site': 'github',
'url': 'https://github.com/rpm-software-management/rpm'
'/archive/rpm-4.13.0-release.tar.gz',
@@ -580,6 +574,12 @@ def test_downloader_download_and_expand_from_archive_url(
'/archive/rpm-4.13.0.tar.gz',
'top_dir_name': 'rpm-rpm-4.13.0',
},
+ {
+ 'site': 'rpm.org',
+ 'url': 'http://ftp.rpm.org/releases/'
+ 'rpm-4.13.x/rpm-4.13.0.tar.gz',
+ 'top_dir_name': 'rpm-4.13.0',
+ },
],
),
( | Change downloading server priority to 1st: GitHub 2nd: rpm.org
Because rpm.org sever is heavy to download.
It takes <I>+ seconds to download the RPM source archive. | junaruga_rpm-py-installer | train |
10f3b8f007652f168e19770a5219389c3eff83cc | diff --git a/lib/double_entry/reporting/aggregate.rb b/lib/double_entry/reporting/aggregate.rb
index <HASH>..<HASH> 100644
--- a/lib/double_entry/reporting/aggregate.rb
+++ b/lib/double_entry/reporting/aggregate.rb
@@ -25,7 +25,7 @@ module DoubleEntry
end
end
- def formatted_amount(value = amount())
+ def formatted_amount(value = amount)
value ||= 0
if function == 'count'
value | call methods without () when not providing args | envato_double_entry | train |
678e0014bb6dc4d09c62068058da20777d08f367 | diff --git a/devices/tuya.js b/devices/tuya.js
index <HASH>..<HASH> 100644
--- a/devices/tuya.js
+++ b/devices/tuya.js
@@ -466,7 +466,8 @@ module.exports = [
{modelID: 'TS0505B', manufacturerName: '_TZ3210_qxenlrin'},
{modelID: 'TS0505B', manufacturerName: '_TZ3210_iwbaamgh'},
{modelID: 'TS0505B', manufacturerName: '_TZ3210_klv2wul0'},
- {modelID: 'TS0505B', manufacturerName: '_TZ3210_rcggc0ys'}],
+ {modelID: 'TS0505B', manufacturerName: '_TZ3210_rcggc0ys'},
+ {modelID: 'TS0505B', manufacturerName: '_TZ3210_s6zec0of'}],
model: 'TS0505B',
vendor: 'TuYa',
description: 'Zigbee RGB+CCT light', | Add manufacturer name '_TZ<I>_s6zec0of' to model 'TS<I>B'. (#<I>) | Koenkk_zigbee-shepherd-converters | train |
15ead55c56d2cac0fe0ed4ef69ca8f127ce82136 | diff --git a/src/fixes/node-fixes/class-smart-quotes-fix.php b/src/fixes/node-fixes/class-smart-quotes-fix.php
index <HASH>..<HASH> 100644
--- a/src/fixes/node-fixes/class-smart-quotes-fix.php
+++ b/src/fixes/node-fixes/class-smart-quotes-fix.php
@@ -52,7 +52,7 @@ class Smart_Quotes_Fix extends Abstract_Node_Fix {
const DOUBLE_QUOTED_NUMBERS = '/(?<=\W|\A)"([^"]*\d+)"(?=\W|\Z)/S';
const COMMA_QUOTE = '/(?<=\s|\A),(?=\S)/S';
const APOSTROPHE_WORDS = "/(?<=\w)'(?=\w)/S";
- const APOSTROPHE_DECADES = "/'(\d\d\b)/S";
+ const APOSTROPHE_DECADES = "/'(\d\d(s|er)?\b)/S"; // Allow both English '80s and German '80er.
const SINGLE_QUOTE_OPEN = "/(?: '(?=\w) ) | (?: (?<=\s|\A)'(?=\S) )/Sx"; // Alternative is for expressions like _'¿hola?'_.
const SINGLE_QUOTE_CLOSE = "/(?: (?<=\w)' ) | (?: (?<=\S)'(?=\s|\Z) )/Sx";
const DOUBLE_QUOTE_OPEN = '/(?: "(?=\w) ) | (?: (?<=\s|\A)"(?=\S) )/Sx';
diff --git a/tests/class-php-typography-test.php b/tests/class-php-typography-test.php
index <HASH>..<HASH> 100644
--- a/tests/class-php-typography-test.php
+++ b/tests/class-php-typography-test.php
@@ -497,6 +497,7 @@ class PHP_Typography_Test extends PHP_Typography_Testcase {
[ '3/4 of 10/12/89', '<sup class="numerator"><span class="numbers">3</span></sup>⁄<sub class="denominator"><span class="numbers">4</span></sub> of <span class="numbers">10</span>/<span class="numbers">12</span>/<span class="numbers">89</span>', false ],
[ 'Certain HTML entities', 'Cer­tain <span class="caps">HTML</span> entities', false ],
[ 'during WP-CLI commands', 'dur­ing <span class="caps">WP-CLI</span> commands', false ],
+ [ 'from the early \'60s, American engagement', 'from the ear­ly <span class="push-single"></span>​<span class="pull-single">’</span><span class="numbers">60</span>s, Amer­i­can engagement', 'from the early ’60s, American engagement' ],
];
}
diff --git a/tests/fixes/node-fixes/class-smart-quotes-fix-test.php b/tests/fixes/node-fixes/class-smart-quotes-fix-test.php
index <HASH>..<HASH> 100644
--- a/tests/fixes/node-fixes/class-smart-quotes-fix-test.php
+++ b/tests/fixes/node-fixes/class-smart-quotes-fix-test.php
@@ -79,6 +79,7 @@ class Smart_Quotes_Fix_Test extends Node_Fix_Testcase {
[ 'Some "word")', 'Some “word”)' ],
[ '"So \'this\'", she said', '“So ‘this’ ”, she said' ],
[ '"\'This\' is it?"', '“ ‘This’ is it?”' ],
+ [ 'from the early \'60s, American', 'from the early ’60s, American' ],
];
} | Preserve apostrophe in decades like '<I>s (English) and '<I>er (German) | mundschenk-at_php-typography | train |
ffa04007603a8ce96aaf88605545694f5e696561 | diff --git a/delphi/program_analysis/autoTranslate/scripts/pyTranslate.py b/delphi/program_analysis/autoTranslate/scripts/pyTranslate.py
index <HASH>..<HASH> 100644
--- a/delphi/program_analysis/autoTranslate/scripts/pyTranslate.py
+++ b/delphi/program_analysis/autoTranslate/scripts/pyTranslate.py
@@ -1,23 +1,23 @@
#!/usr/bin/python
"""
-
+
File: pyTranslate.py
Purpose: Convert a Fortran AST representation into a Python
script having the same functionalities and performing
the same operations as the original Fortran file.
-
- Usage: This script is executed by the autoTranslate script as one
- of the steps in converted a Fortran source file to Python
+
+ Usage: This script is executed by the autoTranslate script as one
+ of the steps in converted a Fortran source file to Python
file. For standalone execution:
python pyTranslate -f <pickle_file> -g <python_file>
-
+
pickle_file: Pickled file containing the ast represenatation
- of the Fortran file along with other non-source
+ of the Fortran file along with other non-source
code information.
- python_file: The Python file on which to write the resulting
+ python_file: The Python file on which to write the resulting
python script.
"""
@@ -207,7 +207,7 @@ def printDo(pyFile, node, printState):
def printIndex(pyFile, node, printState):
# pyFile.write("{0} in range({1}, {2}+1)".format(node['name'], node['low'], node['high'])) Don't use this
# pyFile.write(f"{node['name']}[0] in range(") Use this instead
- pyFile.write("{0}[0] in range(".format(node["name"]))
+ pyFile.write(f"{node['name']}[0] in range(")
printAst(
pyFile,
node["low"], | Removed additional whitespace, switched a format statement to an f-string | ml4ai_delphi | train |
73ef0be41ffeccd20f78b45c84af823372edfd35 | diff --git a/blocks/admin_bookmarks/block_admin_bookmarks.php b/blocks/admin_bookmarks/block_admin_bookmarks.php
index <HASH>..<HASH> 100644
--- a/blocks/admin_bookmarks/block_admin_bookmarks.php
+++ b/blocks/admin_bookmarks/block_admin_bookmarks.php
@@ -32,8 +32,6 @@ class block_admin_bookmarks extends block_base {
/** @var string */
public $blockname = null;
- /** @var bool */
- protected $contentgenerated = false;
/** @var bool|null */
protected $docked = null;
@@ -74,9 +72,10 @@ class block_admin_bookmarks extends block_base {
global $CFG;
// First check if we have already generated, don't waste cycles
- if ($this->contentgenerated === true) {
+ if ($this->content !== null) {
return $this->content;
}
+
$this->content = new stdClass();
if (get_user_preferences('admin_bookmarks')) {
diff --git a/blocks/admin_bookmarks/create.php b/blocks/admin_bookmarks/create.php
index <HASH>..<HASH> 100644
--- a/blocks/admin_bookmarks/create.php
+++ b/blocks/admin_bookmarks/create.php
@@ -30,7 +30,8 @@ $context = context_system::instance();
$PAGE->set_context($context);
$adminroot = admin_get_root(false, false); // settings not required - only pages
-if ($section = optional_param('section', '', PARAM_SAFEDIR) and confirm_sesskey()) {
+// We clean section with safe path here for compatibility with external pages that include a slash in their name.
+if ($section = optional_param('section', '', PARAM_SAFEPATH) and confirm_sesskey()) {
if (get_user_preferences('admin_bookmarks')) {
$bookmarks = explode(',', get_user_preferences('admin_bookmarks'));
diff --git a/blocks/admin_bookmarks/delete.php b/blocks/admin_bookmarks/delete.php
index <HASH>..<HASH> 100644
--- a/blocks/admin_bookmarks/delete.php
+++ b/blocks/admin_bookmarks/delete.php
@@ -31,7 +31,8 @@ $context = context_system::instance();
$PAGE->set_context($context);
$adminroot = admin_get_root(false, false); // settings not required - only pages
-if ($section = optional_param('section', '', PARAM_SAFEDIR) and confirm_sesskey()) {
+// We clean section with safe path here for compatibility with external pages that include a slash in their name.
+if ($section = optional_param('section', '', PARAM_SAFEPATH) and confirm_sesskey()) {
if (get_user_preferences('admin_bookmarks')) { | MDL-<I> block_admin_bookmarks: slightly relax section cleaning.
Allow '/' character in external page names. | moodle_moodle | train |
6dd6e8e88fa01967c7708c5a77847894ba65f1e9 | diff --git a/tests/Geokit/Tests/Geometry/Transformer/WKTTransformerTest.php b/tests/Geokit/Tests/Geometry/Transformer/WKTTransformerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Geokit/Tests/Geometry/Transformer/WKTTransformerTest.php
+++ b/tests/Geokit/Tests/Geometry/Transformer/WKTTransformerTest.php
@@ -263,6 +263,34 @@ class WKTTransformerTest extends \PHPUnit_Framework_TestCase
return $data;
}
+ public function testMultipointWithoutPointParens()
+ {
+ $transformer = new WKTTransformer();
+
+ $points = array();
+ for ($i = 0; $i < 3; $i++) {
+ $points[] = new Point(mt_rand(0, 100), mt_rand(0, 100));
+ }
+
+ $multipoint = new MultiPoint(array(
+ $points[0],
+ $points[1],
+ $points[2]
+ ));
+
+ $str = sprintf(
+ "MULTIPOINT(%F %F,%F %F,%F %F)",
+ $points[0]->getX(),
+ $points[0]->getY(),
+ $points[1]->getX(),
+ $points[1]->getY(),
+ $points[2]->getX(),
+ $points[2]->getY()
+ );
+
+ $this->assertEquals($multipoint, $transformer->reverseTransform($str), 'reverseTransform() correctly processes MultiPoint without parens around Points');
+ }
+
public function testUnknownGeometry()
{
$transformer = new WKTTransformer(); | Add test for MultiPoint without parens around Points | jsor_geokit | train |
f70530ee2ba698ffa06f8cefd360fac3d4b6ef01 | diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -65,6 +65,9 @@ RSpec.configure do |config|
config.filter_run :focus => true
config.filter_run_excluding :external => true
+ # Tests that randomly fail, but may have value.
+ config.filter_run_excluding :volatile => true
+
# Add jruby filters here
config.filter_run_excluding :windows_only => true unless windows?
config.filter_run_excluding :not_supported_on_win2k3 => true if windows_win2k3?
diff --git a/spec/stress/win32/security_spec.rb b/spec/stress/win32/security_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/stress/win32/security_spec.rb
+++ b/spec/stress/win32/security_spec.rb
@@ -48,14 +48,14 @@ describe 'Chef::ReservedNames::Win32::Security', :windows_only do
FileUtils.rm_rf(@test_tempdir)
end
- it "should not leak when retrieving and reading the ACE from a file" do
+ it "should not leak when retrieving and reading the ACE from a file", :volatile do
lambda {
sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select { |ace| ace.sid }
GC.start
}.should_not leak_memory(:warmup => 50, :iterations => 100)
end
- it "should not leak when creating a new ACL and setting it on a file" do
+ it "should not leak when creating a new ACL and setting it on a file", :volatile do
securable_object = Security::SecurableObject.new(@monkeyfoo)
lambda {
securable_object.dacl = Security::ACL.create([ | Stress tests randomly fail in Ci. Exclude them
...until someone has a chance to look at them in-depth and make them
more stable. | chef_chef | train |
f34576e311bd6311752fca216dfd7528ca51efc8 | diff --git a/src/angular-selector.js b/src/angular-selector.js
index <HASH>..<HASH> 100755
--- a/src/angular-selector.js
+++ b/src/angular-selector.js
@@ -273,6 +273,7 @@
scope.open = function () {
scope.isOpen = true;
scope.dropdownPosition();
+ $timeout(scope.scrollToHighlighted);
};
scope.close = function () {
scope.isOpen = false;
@@ -424,10 +425,8 @@
var selectedValues = angular.isArray(scope.selectedValues) ? scope.selectedValues : [scope.selectedValues];
return !scope.inOptions(selectedValues, option);
});
- if (scope.highlighted >= scope.filteredOptions.length)
- scope.highlight(scope.filteredOptions.length - 1);
- if (scope.highlighted == -1 && scope.filteredOptions.length > 0)
- scope.highlight(0);
+ else
+ scope.highlight(scope.filteredOptions.indexOf(scope.selectedValues[0]));
};
// Input width utilities | Fix to highlight selected item (#<I>)
* Code review comments
* Fixed lint errors | indrimuska_angular-selector | train |
53629cad0d18b81652de3f022c6346ccce5a9b11 | diff --git a/gridtk/manager.py b/gridtk/manager.py
index <HASH>..<HASH> 100644
--- a/gridtk/manager.py
+++ b/gridtk/manager.py
@@ -35,19 +35,19 @@ def try_remove_files(filename, recurse, verbose):
if os.path.exists(k):
os.unlink(k)
if verbose: print verbose + ("removed `%s'" % k)
- d = os.path.dirname(k)
- if recurse and not os.listdir(d):
- os.removedirs(d)
- if verbose: print verbose + ("recursively removed `%s'" % d)
+ d = os.path.dirname(k)
+ if recurse and not os.listdir(d):
+ os.removedirs(d)
+ if verbose: print verbose + ("recursively removed `%s'" % d)
else:
if os.path.exists(filename):
os.unlink(filename)
if verbose: print verbose + ("removed `%s'" % filename)
d = os.path.dirname(filename)
- if recurse and not os.listdir(d):
- os.removedirs(d)
- if verbose: print verbose + ("recursively removed `%s'" % d)
+ if recurse and not os.listdir(d):
+ os.removedirs(d)
+ if verbose: print verbose + ("recursively removed `%s'" % d)
class Job:
"""The job class describes a job""" | Remove log directories even if there are no log files (bug fix) | bioidiap_gridtk | train |
d490a8570648f4d471db227f70d0408c7e84813d | diff --git a/core/commands/add.go b/core/commands/add.go
index <HASH>..<HASH> 100644
--- a/core/commands/add.go
+++ b/core/commands/add.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"path"
+ "sort"
cmds "github.com/jbenet/go-ipfs/commands"
core "github.com/jbenet/go-ipfs/core"
@@ -82,6 +83,8 @@ remains to be implemented.
return nil, u.ErrCast()
}
+ sort.Stable(val)
+
var buf bytes.Buffer
for i, obj := range val.Objects {
if val.Quiet {
@@ -197,3 +200,16 @@ func addDagnode(output *AddOutput, name string, dn *dag.Node) error {
output.Names = append(output.Names, name)
return nil
}
+
+// Sort interface implementation to sort add output by name
+
+func (a AddOutput) Len() int {
+ return len(a.Names)
+}
+func (a AddOutput) Swap(i, j int) {
+ a.Names[i], a.Names[j] = a.Names[j], a.Names[i]
+ a.Objects[i], a.Objects[j] = a.Objects[j], a.Objects[i]
+}
+func (a AddOutput) Less(i, j int) bool {
+ return a.Names[i] < a.Names[j]
+} | Make sure ipfs add output is sorted by name
License: MIT | ipfs_go-ipfs | train |
c8f6b4cf28da655a59c5d2a3fc53f063fcca76a4 | diff --git a/can/bus.py b/can/bus.py
index <HASH>..<HASH> 100644
--- a/can/bus.py
+++ b/can/bus.py
@@ -12,7 +12,6 @@ import logging
import threading
from time import time
from collections import namedtuple
-import logging
from .broadcastmanager import ThreadBasedCyclicSendTask
@@ -85,7 +84,8 @@ class BusABC(object):
elif timeout is None:
continue
- # try next one only if there still is time, and with reduced timeout
+ # try next one only if there still is time, and with
+ # reduced timeout
else:
time_left = timeout - (time() - start)
@@ -116,9 +116,9 @@ class BusABC(object):
.. note::
- The second return value (whether filtering was already done) may change
- over time for some interfaces, like for example in the Kvaser interface.
- Thus it cannot be simplified to a constant value.
+ The second return value (whether filtering was already done) may
+ change over time for some interfaces, like for example in the
+ Kvaser interface. Thus it cannot be simplified to a constant value.
:param float timeout: seconds to wait for a message,
see :meth:`~can.BusABC.send`
@@ -145,7 +145,7 @@ class BusABC(object):
Override this method to enable the transmit path.
:param can.Message msg: A message object.
-
+
:type timeout: float or None
:param timeout:
If > 0, wait up to this many seconds for message to be ACK'ed or
@@ -184,7 +184,8 @@ class BusABC(object):
if not hasattr(self, "_lock_send_periodic"):
# Create a send lock for this bus
self._lock_send_periodic = threading.Lock()
- return ThreadBasedCyclicSendTask(self, self._lock_send_periodic, msg, period, duration)
+ return ThreadBasedCyclicSendTask(
+ self, self._lock_send_periodic, msg, period, duration)
def __iter__(self):
"""Allow iteration on messages as they are received.
@@ -217,22 +218,23 @@ class BusABC(object):
"""Apply filtering to all messages received by this Bus.
All messages that match at least one filter are returned.
- If `filters` is `None` or a zero length sequence, all
+ If `filters` is `None` or a zero length sequence, all
messages are matched.
Calling without passing any filters will reset the applied
filters to `None`.
:param filters:
- A iterable of dictionaries each containing a "can_id", a "can_mask",
- and an optional "extended" key.
+ A iterable of dictionaries each containing a "can_id",
+ a "can_mask", and an optional "extended" key.
>>> [{"can_id": 0x11, "can_mask": 0x21, "extended": False}]
- A filter matches, when ``<received_can_id> & can_mask == can_id & can_mask``.
+ A filter matches, when
+ ``<received_can_id> & can_mask == can_id & can_mask``.
If ``extended`` is set as well, it only matches messages where
- ``<received_is_extended> == extended``. Else it matches every messages based
- only on the arbitration ID and mask.
+ ``<received_is_extended> == extended``. Else it matches every
+ messages based only on the arbitration ID and mask.
"""
self._filters = filters or None
self._apply_filters(self._filters)
@@ -267,14 +269,15 @@ class BusABC(object):
for _filter in self._filters:
# check if this filter even applies to the message
if 'extended' in _filter and \
- _filter['extended'] != msg.is_extended_id:
+ _filter['extended'] != msg.is_extended_id:
continue
# then check for the mask and id
can_id = _filter['can_id']
can_mask = _filter['can_mask']
- # basically, we compute `msg.arbitration_id & can_mask == can_id & can_mask`
+ # basically, we compute
+ # `msg.arbitration_id & can_mask == can_id & can_mask`
# by using the shorter, but equivalent from below:
if (can_id ^ msg.arbitration_id) & can_mask == 0:
return True | Resolve pylint issues (#<I>)
Remove double import on logging, fix indentation and shorten too
long lines. | hardbyte_python-can | train |
cbd97c7875cfac7c8c46e912cb85d531a6faa95a | diff --git a/core-bundle/src/Resources/contao/drivers/DC_Table.php b/core-bundle/src/Resources/contao/drivers/DC_Table.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/drivers/DC_Table.php
+++ b/core-bundle/src/Resources/contao/drivers/DC_Table.php
@@ -4288,27 +4288,26 @@ Backend.makeParentViewSortable("ul_' . CURRENT_ID . '");
$arrPanels = $this->preparePanelArray();
// prepare the default panels
- $arrDefaultPanels = array('filter', 'search', 'limit', 'sort');
foreach ($arrPanels as $k => $arrSubPanels)
{
- foreach ($arrSubPanels as $strSubPanelKey => $strSubPanelHtml)
+ foreach ($arrSubPanels as $kk => $strSubPanelKey)
{
- if (in_array($strSubPanelKey, $arrDefaultPanels))
+ switch ($strSubPanelKey)
{
- $arrPanels[$k][$strSubPanelKey] = $this->{$strSubPanelKey . 'Menu'}();
- }
- }
- }
-
- // call the panelLayout_callbacck
- if (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['panelLayout_callback']))
- {
- foreach ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['panelLayout_callback'] as $callback)
- {
- if (is_array($callback))
- {
- $this->import($callback[0]);
- $arrPanels = $this->$callback[0]->$callback[1]($arrPanels, $this);
+ case 'filter':
+ case 'search':
+ case 'limit':
+ case 'sort':
+ $arrPanels[$k][$kk] = $this->{$strSubPanelKey . 'Menu'}();
+
+ // call the panelLayout_callbacck
+ default:
+ $arrCallback = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['panelLayout_callback'][$strSubPanelKey];
+ if (is_array($arrCallback))
+ {
+ $this->import($arrCallback[0]);
+ $arrPanels[$k][$kk] = $this->$arrCallback[0]->$arrCallback[1]($this);
+ }
}
}
}
@@ -4383,7 +4382,7 @@ Backend.makeParentViewSortable("ul_' . CURRENT_ID . '");
continue;
}
- $arrReturn[$intPanelKey][$strSubPanel] = '';
+ $arrReturn[$intPanelKey][$intSubPanelKey] = $strSubPanel;
}
} | [Core] the callback is now defined for a certain panelLayout-key | contao_contao | train |
fec6b2716b734387b638e1aa28ed3c2f9940b72d | diff --git a/salt/states/file.py b/salt/states/file.py
index <HASH>..<HASH> 100644
--- a/salt/states/file.py
+++ b/salt/states/file.py
@@ -2485,138 +2485,6 @@ def blockreplace(
return ret
-def sed(name,
- before,
- after,
- limit='',
- backup='.bak',
- options='-r -e',
- flags='g',
- negate_match=False):
- '''
- .. deprecated:: 0.17.0
- Use the :mod:`file.replace <salt.states.file.replace>` state instead.
-
- Maintain a simple edit to a file
-
- The file will be searched for the ``before`` pattern before making the
- edit. In general the ``limit`` pattern should be as specific as possible
- and ``before`` and ``after`` should contain the minimal text to be changed.
-
- before
- A pattern that should exist in the file before the edit.
- after
- A pattern that should exist in the file after the edit.
- limit
- An optional second pattern that can limit the scope of the before
- pattern.
- backup : '.bak'
- The extension for the backed-up version of the file before the edit. If
- no backups is desired, pass in the empty string: ''
- options : ``-r -e``
- Any options to pass to the ``sed`` command. ``-r`` uses extended
- regular expression syntax and ``-e`` denotes that what follows is an
- expression that sed will execute.
- flags : ``g``
- Any flags to append to the sed expression. ``g`` specifies the edit
- should be made globally (and not stop after the first replacement).
- negate_match : False
- Negate the search command (``!``)
-
- .. versionadded:: 0.17.0
-
- Usage:
-
- .. code-block:: yaml
-
- # Disable the epel repo by default
- /etc/yum.repos.d/epel.repo:
- file.sed:
- - before: 1
- - after: 0
- - limit: ^enabled=
-
- # Remove ldap from nsswitch
- /etc/nsswitch.conf:
- file.sed:
- - before: 'ldap'
- - after: ''
- - limit: '^passwd:'
-
- .. versionadded:: 0.9.5
- '''
- name = os.path.expanduser(name)
-
- ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
-
- check_res, check_msg = _check_file(name)
- if not check_res:
- return _error(ret, check_msg)
-
- # Mandate that before and after are strings
- before = str(before)
- after = str(after)
-
- # Look for the pattern before attempting the edit
- if not __salt__['file.sed_contains'](name,
- before,
- limit=limit,
- flags=flags):
- # Pattern not found; don't try to guess why, just tell the user there
- # were no changes made, as the changes should only be made once anyway.
- # This makes it so users can use backreferences without the state
- # coming back as failed all the time.
- ret['comment'] = '"before" pattern not found, no changes made'
- ret['result'] = True
- return ret
-
- if __opts__['test']:
- ret['comment'] = 'File {0} is set to be updated'.format(name)
- ret['result'] = None
- return ret
-
- with salt.utils.fopen(name, 'rb') as fp_:
- slines = fp_.readlines()
-
- # should be ok now; perform the edit
- retcode = __salt__['file.sed'](path=name,
- before=before,
- after=after,
- limit=limit,
- backup=backup,
- options=options,
- flags=flags,
- negate_match=negate_match)['retcode']
-
- if retcode != 0:
- ret['result'] = False
- ret['comment'] = ('There was an error running sed. '
- 'Return code {0}').format(retcode)
- return ret
-
- with salt.utils.fopen(name, 'rb') as fp_:
- nlines = fp_.readlines()
-
- if slines != nlines:
- if not salt.utils.istextfile(name):
- ret['changes']['diff'] = 'Replace binary file'
- else:
- # Changes happened, add them
- ret['changes']['diff'] = ''.join(difflib.unified_diff(slines,
- nlines))
-
- # Don't check the result -- sed is not designed to be able to check
- # the result, because of backreferences and so forth. Just report
- # that sed was run, and assume it was successful (no error!)
- ret['result'] = True
- ret['comment'] = 'sed ran without error'
- else:
- ret['result'] = True
- ret['comment'] = 'sed ran without error, but no changes were made'
-
- return ret
-
-
def comment(name, regex, char='#', backup='.bak'):
'''
Comment out specified lines in a file. | Remove now-deprecated file.sed | saltstack_salt | train |
5bc91333d7d2b59194bbe771f99bd2ca0a1eff47 | diff --git a/src/Money.php b/src/Money.php
index <HASH>..<HASH> 100644
--- a/src/Money.php
+++ b/src/Money.php
@@ -690,6 +690,14 @@ class Money implements MoneyContainer
}
/**
+ * {@inheritdoc}
+ */
+ public function getValue($currency, CurrencyConverter $converter)
+ {
+ return $converter->convert($this, $currency);
+ }
+
+ /**
* Handles the special case of monies in methods like `plus()`, `minus()`, etc.
*
* @param Money|BigNumber|number|string $that
diff --git a/src/MoneyBag.php b/src/MoneyBag.php
index <HASH>..<HASH> 100644
--- a/src/MoneyBag.php
+++ b/src/MoneyBag.php
@@ -39,14 +39,17 @@ class MoneyBag implements MoneyContainer
}
/**
- * Returns the total of the monies contained in this bag, in the given currency.
- *
- * @param Currency|string $currency The currency to get the total in.
- * @param CurrencyConverter $converter The currency converter to use.
- *
- * @return Money The total in the given currency.
+ * {@inheritdoc}
*/
- public function getTotal($currency, CurrencyConverter $converter)
+ public function getMonies()
+ {
+ return array_values($this->monies);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getValue($currency, CurrencyConverter $converter)
{
$currency = Currency::of($currency);
$total = Money::zero($currency);
@@ -61,14 +64,6 @@ class MoneyBag implements MoneyContainer
}
/**
- * {@inheritdoc}
- */
- public function getMonies()
- {
- return array_values($this->monies);
- }
-
- /**
* Adds monies to this bag.
*
* @param MoneyContainer $that The `Money` or `MoneyBag` to add.
diff --git a/src/MoneyContainer.php b/src/MoneyContainer.php
index <HASH>..<HASH> 100644
--- a/src/MoneyContainer.php
+++ b/src/MoneyContainer.php
@@ -13,4 +13,14 @@ interface MoneyContainer
* @return Money[]
*/
public function getMonies();
+
+ /**
+ * Returns the value of this money container, in the given currency.
+ *
+ * @param Currency|string $currency The currency to get the value in.
+ * @param CurrencyConverter $converter The currency converter to use.
+ *
+ * @return Money The value in the given currency.
+ */
+ public function getValue($currency, CurrencyConverter $converter);
} | Add MoneyContainer::getValue() method
Methods accepting either a Money or a MoneyBag can therefore use a common interface to get its value in a given currency.
BC BREAK: MoneyBag::getTotal() is renamed to getValue()! | brick_money | train |
456738bd7f63655284a7b647caeb0180d38a73e9 | diff --git a/packages/perspective/src/js/config/constants.js b/packages/perspective/src/js/config/constants.js
index <HASH>..<HASH> 100644
--- a/packages/perspective/src/js/config/constants.js
+++ b/packages/perspective/src/js/config/constants.js
@@ -43,6 +43,7 @@ const NUMBER_AGGREGATES = [
"last by index",
"last",
"high",
+ "join",
"low",
"mean",
"median",
@@ -54,7 +55,7 @@ const NUMBER_AGGREGATES = [
"unique"
];
-const STRING_AGGREGATES = ["any", "count", "distinct count", "distinct leaf", "dominant", "first by index", "last by index", "last", "unique"];
+const STRING_AGGREGATES = ["any", "count", "distinct count", "distinct leaf", "dominant", "first by index", "join", "last by index", "last", "unique"];
const BOOLEAN_AGGREGATES = ["any", "count", "distinct count", "distinct leaf", "dominant", "first by index", "last by index", "last", "unique"];
diff --git a/packages/perspective/test/js/pivots.js b/packages/perspective/test/js/pivots.js
index <HASH>..<HASH> 100644
--- a/packages/perspective/test/js/pivots.js
+++ b/packages/perspective/test/js/pivots.js
@@ -228,6 +228,24 @@ module.exports = perspective => {
table.delete();
});
+ it("['z'], join", async function() {
+ var table = await perspective.table(data);
+ var view = await table.view({
+ row_pivots: ["z"],
+ columns: ["x"],
+ aggregates: {x: "join"}
+ });
+ var answer = [
+ {__ROW_PATH__: [], x: "1, 2, 3, 4, "},
+ {__ROW_PATH__: [false], x: "2, 4, "},
+ {__ROW_PATH__: [true], x: "1, 3, "}
+ ];
+ let result = await view.to_json();
+ expect(result).toEqual(answer);
+ view.delete();
+ table.delete();
+ });
+
it("['z'], first by index with appends", async function() {
var table = await perspective.table(data, {index: "y"});
var view = await table.view({ | adding js test for join aggregate function | finos_perspective | train |
Subsets and Splits