hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
93cc515882e53c87f414fd6b53962603d4862c11
diff --git a/src/main/java/graphql/language/Directive.java b/src/main/java/graphql/language/Directive.java index <HASH>..<HASH> 100644 --- a/src/main/java/graphql/language/Directive.java +++ b/src/main/java/graphql/language/Directive.java @@ -18,7 +18,7 @@ import static graphql.Assert.assertNotNull; import static graphql.collect.ImmutableKit.emptyList; import static graphql.collect.ImmutableKit.emptyMap; import static graphql.language.NodeChildrenContainer.newNodeChildrenContainer; -import static graphql.language.NodeUtil.argumentsByName; +import static graphql.language.NodeUtil.nodeByName; @PublicApi public class Directive extends AbstractNode<Directive> implements NamedNode<Directive> { @@ -60,7 +60,7 @@ public class Directive extends AbstractNode<Directive> implements NamedNode<Dire public Map<String, Argument> getArgumentsByName() { // the spec says that args MUST be unique within context - return argumentsByName(arguments); + return nodeByName(arguments); } public Argument getArgument(String argumentName) { diff --git a/src/main/java/graphql/language/NodeUtil.java b/src/main/java/graphql/language/NodeUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/graphql/language/NodeUtil.java +++ b/src/main/java/graphql/language/NodeUtil.java @@ -19,17 +19,6 @@ import static graphql.util.FpKit.mergeFirst; @Internal public class NodeUtil { - public static boolean isEqualTo(String thisStr, String thatStr) { - if (null == thisStr) { - if (null != thatStr) { - return false; - } - } else if (!thisStr.equals(thatStr)) { - return false; - } - return true; - } - public static <T extends NamedNode<T>> T findNodeByName(List<T> namedNodes, String name) { for (T namedNode : namedNodes) { if (Objects.equals(namedNode.getName(), name)) { @@ -43,10 +32,11 @@ public class NodeUtil { return FpKit.groupingBy(directives, Directive::getName); } - public static Map<String, Argument> argumentsByName(List<Argument> arguments) { - return FpKit.getByName(arguments, Argument::getName, mergeFirst()); + public static <T extends NamedNode<T>> Map<String, T> nodeByName(List<T> nameNode) { + return FpKit.getByName(nameNode, NamedNode::getName, mergeFirst()); } + public static class GetOperationResult { public OperationDefinition operationDefinition; public Map<String, FragmentDefinition> fragmentsByName;
minor change for NodeUtil (#<I>)
graphql-java_graphql-java
train
fd47d1d7efe966813be75dab4bbb7af0ee912d8f
diff --git a/guacamole-common-js/src/main/webapp/modules/Keyboard.js b/guacamole-common-js/src/main/webapp/modules/Keyboard.js index <HASH>..<HASH> 100644 --- a/guacamole-common-js/src/main/webapp/modules/Keyboard.js +++ b/guacamole-common-js/src/main/webapp/modules/Keyboard.js @@ -1208,6 +1208,30 @@ Guacamole.Keyboard = function(element) { }, true); /** + * Returns whether the given string is fully composed. A string is fully + * composed if it does not end with combining characters. + * + * @private + * @param {String} str + * The string to test. + * + * @returns {Boolean} + * true of the string is fully composed, false otherwise. + */ + var isComposed = function isComposed(str) { + + // The empty string is fully composed + if (!str) + return true; + + // Test whether the last character is within the "Combining + // Diacritical Marks" Unicode block (U+0300 through U+036F) + var lastCodepoint = str.charCodeAt(str.length - 1); + return !(lastCodepoint >= 0x0300 && lastCodepoint <= 0x036F); + + }; + + /** * Handles the given "input" event, typing the data within the input text. * If the event is complete (text is provided), handling of "compositionend" * events is suspended, as such events may conflict with input events. @@ -1222,7 +1246,7 @@ Guacamole.Keyboard = function(element) { if (!guac_keyboard.onkeydown && !guac_keyboard.onkeyup) return; // Type all content written - if (e.data) { + if (e.data && isComposed(e.data)) { element.removeEventListener("compositionend", handleComposition, false); guac_keyboard.type(e.data); } @@ -1245,7 +1269,7 @@ Guacamole.Keyboard = function(element) { if (!guac_keyboard.onkeydown && !guac_keyboard.onkeyup) return; // Type all content written - if (e.data) { + if (e.data && isComposed(e.data)) { element.removeEventListener("input", handleInput, false); guac_keyboard.type(e.data); }
GUACAMOLE-<I>: Only attempt to type fully-composed strings.
glyptodon_guacamole-client
train
691db3694ef49c08bb042858286e12ad9d9db325
diff --git a/credhub/auth/uaa.go b/credhub/auth/uaa.go index <HASH>..<HASH> 100644 --- a/credhub/auth/uaa.go +++ b/credhub/auth/uaa.go @@ -1,7 +1,9 @@ package auth import ( + "bytes" "encoding/json" + "io/ioutil" "net/http" ) @@ -38,9 +40,14 @@ func (a *Uaa) Do(req *http.Request) (*http.Response, error) { req.Header.Set("Authorization", "Bearer "+a.AccessToken) resp, err := a.ApiClient.Do(req) - if err == nil && tokenExpired(resp) { - a.Refresh() + if err != nil { + return resp, err + } + expired, err := tokenExpired(resp) + + if err == nil && expired { + a.Refresh() req.Header.Set("Authorization", "Bearer "+a.AccessToken) resp, err = a.ApiClient.Do(req) } @@ -48,20 +55,30 @@ func (a *Uaa) Do(req *http.Request) (*http.Response, error) { return resp, err } -func tokenExpired(resp *http.Response) bool { +func tokenExpired(resp *http.Response) (bool, error) { if resp.StatusCode < 400 { - return false + return false, nil } var errResp map[string]string + buf, err := ioutil.ReadAll(resp.Body) + + if err != nil { + return false, err + } + + resp.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) + + decoder := json.NewDecoder(bytes.NewBuffer(buf)) + err = decoder.Decode(&errResp) - decoder := json.NewDecoder(resp.Body) - err := decoder.Decode(&errResp) if err != nil { - return false + // Since we fail to decode the error response + // we cannot ensure that the token is invalid + return false, nil } - return errResp["error"] == "access_token_expired" + return errResp["error"] == "access_token_expired", nil } // Refresh the access token diff --git a/credhub/auth/uaa_test.go b/credhub/auth/uaa_test.go index <HASH>..<HASH> 100644 --- a/credhub/auth/uaa_test.go +++ b/credhub/auth/uaa_test.go @@ -24,7 +24,7 @@ var _ = Describe("Uaa", func() { Context("Do()", func() { It("should add the bearer token to the request header", func() { - expectedResponse := &http.Response{StatusCode: 539} + expectedResponse := &http.Response{StatusCode: 539, Body: ioutil.NopCloser(strings.NewReader(""))} expectedError := errors.New("some error") dc := &DummyClient{Response: expectedResponse, Error: expectedError} @@ -117,6 +117,39 @@ var _ = Describe("Uaa", func() { Expect(string(body)).To(Equal("Success!")) }) }) + + Context("when a non-auth error has occurred", func() { + It("should forward the response untouched", func() { + fhc := &authfakes.FakeHttpClient{} + fhc.DoStub = func(req *http.Request) (*http.Response, error) { + resp := &http.Response{} + resp.StatusCode = 573 + resp.Body = ioutil.NopCloser(strings.NewReader(`{"error": "some other error"}`)) + return resp, nil + } + + uaa := auth.Uaa{ + AccessToken: "old-access-token", + RefreshToken: "old-refresh-token", + ClientId: "client-id", + ClientSecret: "client-secret", + ApiClient: fhc, + UaaClient: dummyUaa, + } + + request, _ := http.NewRequest("GET", "https://some-endpoint.com/path/", nil) + + response, err := uaa.Do(request) + + Expect(err).ToNot(HaveOccurred()) + + body, err := ioutil.ReadAll(response.Body) + + Expect(err).ToNot(HaveOccurred()) + Expect(body).To(MatchJSON(`{"error": "some other error"}`)) + }) + }) + }) Context("Refresh()", func() {
UAA Do() will now clone the response body when checking for a expired token
cloudfoundry-incubator_credhub-cli
train
7fdff8e46e0a6bddf2b0672354f118aafbd6a86e
diff --git a/lib/chicago/database/dataset_builder.rb b/lib/chicago/database/dataset_builder.rb index <HASH>..<HASH> 100644 --- a/lib/chicago/database/dataset_builder.rb +++ b/lib/chicago/database/dataset_builder.rb @@ -7,7 +7,7 @@ module Chicago def initialize(db, query) @base_table = query.table @query = query - @dataset = db[query.table.table_name] + @dataset = db[query.table.table_name.as(query.table.name)] @joined_tables = Set.new @selected_columns = [] end diff --git a/spec/query_spec.rb b/spec/query_spec.rb index <HASH>..<HASH> 100644 --- a/spec/query_spec.rb +++ b/spec/query_spec.rb @@ -112,7 +112,7 @@ describe Chicago::Query do end it "should select from the right table" do - @q.dataset.first_source.should == :facts_sales + @q.dataset.sql.should =~ /FROM `facts_sales` AS `sales`/ end it "should select a column from the fact table" do
Fix bug with table naming in reworked Query. The FROM table was not being aliased correctly.
notonthehighstreet_chicago
train
e05fe29e12907417a27d3d37347fd25d7648baf1
diff --git a/lib/garner/strategies/binding/key/binding_index.rb b/lib/garner/strategies/binding/key/binding_index.rb index <HASH>..<HASH> 100644 --- a/lib/garner/strategies/binding/key/binding_index.rb +++ b/lib/garner/strategies/binding/key/binding_index.rb @@ -26,6 +26,7 @@ module Garner # @return [String] A cache key string. def self.fetch_cache_key_for(binding) canonical_binding = fetch_canonical_binding_for(binding) + return nil unless canonical_binding key = index_key_for(canonical_binding) Garner.config.cache.fetch(key) { new_cache_key_for(canonical_binding) } end @@ -36,6 +37,7 @@ module Garner # @return [String] A cache key string. def self.write_cache_key_for(binding) canonical_binding = fetch_canonical_binding_for(binding) + return nil unless canonical_binding key = index_key_for(canonical_binding) value = new_cache_key_for(canonical_binding) value.tap { |v| Garner.config.cache.write(key, v) } diff --git a/spec/garner/strategies/binding/key/binding_index_spec.rb b/spec/garner/strategies/binding/key/binding_index_spec.rb index <HASH>..<HASH> 100644 --- a/spec/garner/strategies/binding/key/binding_index_spec.rb +++ b/spec/garner/strategies/binding/key/binding_index_spec.rb @@ -94,6 +94,24 @@ describe Garner::Strategies::Binding::Key::BindingIndex do :proxied_binding => "Mocker/id=4" }).should == @mock_key end + + context "whose canonical binding is nil" do + before(:each) do + @persisted_mock_alias.stub(:proxy_binding) { nil } + end + + it "returns a nil cache key" do + subject.fetch_cache_key_for(@persisted_mock_alias).should be_nil + end + + it "does not store the cache key to cache" do + subject.fetch_cache_key_for(@persisted_mock_alias) + Garner.config.cache.read({ + :strategy => subject, + :proxied_binding => "" + }).should be_nil + end + end end end @@ -108,6 +126,16 @@ describe Garner::Strategies::Binding::Key::BindingIndex do it "returns a cache key string" do subject.write_cache_key_for(@persisted_mock_alias).should == @mock_key end + + context "whose canonical binding is nil" do + before(:each) do + @persisted_mock_alias.stub(:proxy_binding) { nil } + end + + it "returns a nil cache key" do + subject.write_cache_key_for(@persisted_mock_alias).should be_nil + end + end end end @@ -171,7 +199,11 @@ describe Garner::Strategies::Binding::Key::BindingIndex do end it_behaves_like "Garner::Strategies::Binding::Key strategy" do - let(:known_bindings) { [Monger.create, Monger.identify("m1"), Monger] } + let(:known_bindings) do + document = Monger.create({ :name => "M1" }) + identity = Monger.identify("m1") + [Monger, document, identity] + end let(:unknown_bindings) { [] } end diff --git a/spec/integration/mongoid_spec.rb b/spec/integration/mongoid_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/mongoid_spec.rb +++ b/spec/integration/mongoid_spec.rb @@ -56,6 +56,20 @@ describe "Mongoid integration" do @object.destroy Monger.garnered_find("m1").should be_nil end + + context "with case-insensitive find" do + before(:each) do + _find = Monger.method(:find) + Monger.stub(:find) do |param| + _find.call(param.to_s.downcase) + end + end + + it "does not cache a nil identity" do + Monger.garnered_find("M1").should == @object + Monger.garnered_find("foobar").should be_nil + end + end end [:find, :identify].each do |selection_method|
Fix for #<I>: Don't store bindings in the BindingIndex unless they have a canonical binding present
artsy_garner
train
cf2f2b8db93c757e93536a9fc29b0b4a2b3aa602
diff --git a/dipper/sources/MGI.py b/dipper/sources/MGI.py index <HASH>..<HASH> 100644 --- a/dipper/sources/MGI.py +++ b/dipper/sources/MGI.py @@ -56,6 +56,7 @@ class MGI(PostgreSQLSource): { 'query': '../../resources/sql/mgi_dbinfo.sql', 'outfile': 'mgi_dbinfo' + 'Force' : True }, { 'query': '../../resources/sql/gxd_genotype_view.sql', @@ -284,7 +285,11 @@ class MGI(PostgreSQLSource): query_fh = open(os.path.join( os.path.dirname(__file__), query_map['query']), 'r') query = query_fh.read() - self.fetch_query_from_pgdb(query_map['outfile'], query, None, cxn) + force = False + if 'Force' in query_map; + force = query_map['Force'] + self.fetch_query_from_pgdb( + query_map['outfile'], query, None, cxn, force) # always get this - it has the verion info self.fetch_transgene_genes_from_db(cxn)
try to get the db info updated
monarch-initiative_dipper
train
ab6c3d1e25a41fc5e4819d3032d967c28c2800b4
diff --git a/xlsxwriter.class.php b/xlsxwriter.class.php index <HASH>..<HASH> 100644 --- a/xlsxwriter.class.php +++ b/xlsxwriter.class.php @@ -224,7 +224,7 @@ class XLSXWriter public function writeSheetHead($row_count, $column_count, $sheet_name='', array $header_types=array() ) { trigger_error ( __FUNCTION__ . " is deprecated and will be removed in future releases.", E_USER_DEPRECATED); - $this->writeSheetHeader($this->current_sheet, $header_types); + $this->writeSheetHeader($this->current_sheet=$sheet_name, $header_types); } public function writeSheetCurrentRow($row) //formerly named writeSheetRow
making deprecated writeSheetHead() backwards compatible with last nights commit
mk-j_PHP_XLSXWriter
train
592ea91c0b8067a752f07e2a57080f0d3b18f66d
diff --git a/client/src/main/java/io/pravega/client/stream/impl/CheckpointState.java b/client/src/main/java/io/pravega/client/stream/impl/CheckpointState.java index <HASH>..<HASH> 100644 --- a/client/src/main/java/io/pravega/client/stream/impl/CheckpointState.java +++ b/client/src/main/java/io/pravega/client/stream/impl/CheckpointState.java @@ -147,8 +147,14 @@ public class CheckpointState { return !uncheckpointedHosts.isEmpty(); } + /** + * Get the number of outstanding Checkpoints. It should not take silent Checkpoints into account. + * @return the number of outstanding Checkpoints. + */ int getOutstandingCheckpoints() { - return checkpoints.size(); + return (int) checkpoints.stream() + .filter(checkpoint -> !(isCheckpointSilent(checkpoint) || isCheckpointComplete(checkpoint))) + .count(); } void clearCheckpointsBefore(String checkpointId) { diff --git a/client/src/test/java/io/pravega/client/stream/impl/CheckpointStateTest.java b/client/src/test/java/io/pravega/client/stream/impl/CheckpointStateTest.java index <HASH>..<HASH> 100644 --- a/client/src/test/java/io/pravega/client/stream/impl/CheckpointStateTest.java +++ b/client/src/test/java/io/pravega/client/stream/impl/CheckpointStateTest.java @@ -16,6 +16,7 @@ import java.util.Collections; import java.util.Map; import org.junit.Test; +import static io.pravega.client.stream.impl.ReaderGroupImpl.SILENT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -87,6 +88,35 @@ public class CheckpointStateTest { assertFalse(state.getPositionsForLatestCompletedCheckpoint().isPresent()); } + @Test + public void testOutstandingCheckpoint() { + CheckpointState state = new CheckpointState(); + state.beginNewCheckpoint("1", ImmutableSet.of("a"), Collections.emptyMap()); + state.beginNewCheckpoint("2", ImmutableSet.of("a"), Collections.emptyMap()); + state.beginNewCheckpoint("3"+ SILENT, ImmutableSet.of("a"), Collections.emptyMap()); + state.beginNewCheckpoint("4", ImmutableSet.of("a"), Collections.emptyMap()); + // Silent checkpoint should not be counted as part of CheckpointState#getOutstandingCheckpoints. + assertEquals(3, state.getOutstandingCheckpoints()); + + //Complete checkpoint "2" + state.readerCheckpointed("2", "a", ImmutableMap.of(getSegment("S1"), 1L)); + assertTrue(state.isCheckpointComplete("2")); + assertEquals( ImmutableMap.of(getSegment("S1"), 1L), state.getPositionsForCompletedCheckpoint("2")); + state.clearCheckpointsBefore("2"); + // All check points before checkpoint id "2" are completed. + assertTrue(state.isCheckpointComplete("1")); + // Only checkpoint "4" is outstanding as checkpoints "1" and "2" are complete and silent checkpoints are ignored. + assertEquals(1, state.getOutstandingCheckpoints()); + + state.readerCheckpointed("3"+SILENT, "a", Collections.emptyMap()); + assertTrue(state.isCheckpointComplete("4"+SILENT)); + assertEquals(1, state.getOutstandingCheckpoints()); // Checkpoint 4 is outstanding. + + state.readerCheckpointed("4", "a", Collections.emptyMap()); + assertTrue(state.isCheckpointComplete("4")); + assertEquals(0, state.getOutstandingCheckpoints()); + } + private Segment getSegment(String name) { return new Segment("ExampleScope", name, 0); }
Issue <I>: Bugfix for outstanding checkpoint count. (#<I>) * Silent checkpoints should not be considered while computing the number of outstanding checkpoints.
pravega_pravega
train
a9e3e47b3091d11c18b560a3fc15650e7d730cfc
diff --git a/src/qwest.js b/src/qwest.js index <HASH>..<HASH> 100644 --- a/src/qwest.js +++ b/src/qwest.js @@ -112,6 +112,10 @@ module.exports = function() { } } } + // Set timeout + if(xhr2 || xdr) { + xhr.timeout = options.timeout; + } // Open connection if(xdr) { xhr.open(method, url); @@ -142,10 +146,16 @@ module.exports = function() { if(xhr2 || xdr) { xhr.onload = handleResponse; xhr.onerror = handleError; + xhr.ontimeout = handleError; } else { + var timeout = setTimeout(function() { + xmlhttp.abort(); + handleError(new Error('Timeout ('+url+')')); + }, options.timeout); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { + clearTimeout(timeout); handleResponse(); } };
Update qwest.js Add abort by timeout
pyrsmk_qwest
train
c0f5ec4b5285d8ba64e5d54fb8d7cadb03900ca5
diff --git a/Task/Base.php b/Task/Base.php index <HASH>..<HASH> 100644 --- a/Task/Base.php +++ b/Task/Base.php @@ -2,7 +2,7 @@ /** * @file - * Contains the base Task class. + * Contains ModuleBuider\Task. */ namespace ModuleBuider\Task; @@ -23,7 +23,7 @@ namespace ModuleBuider\Task; * appending the version number to the class name. The unversioned class should * also exist as a parent class. * - * Task objects are instantiated by ModuleBuilderFactory::getTask(). + * Task objects should be instantiated by \ModuleBuilder\Factory::getTask(). */ class Base { @@ -42,6 +42,8 @@ class Base { * * @return * A sanity level string to pass to the environment's verifyEnvironment(). + * + * @see \ModuleBuilder\Environment\EnvironmentInterface::verifyEnvironment() */ function getSanityLevel() { return $this->sanity_level;
Fixed docs in base Task class.
drupal-code-builder_drupal-code-builder
train
11d76a92979341311962cf0cf1ad52dff656842b
diff --git a/nodeconductor/server/admin/dashboard.py b/nodeconductor/server/admin/dashboard.py index <HASH>..<HASH> 100644 --- a/nodeconductor/server/admin/dashboard.py +++ b/nodeconductor/server/admin/dashboard.py @@ -98,7 +98,7 @@ class CustomIndexDashboard(FluentIndexDashboard): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ - result_module = modules.LinkList(title='Shared service settings in Erred state') + result_module = modules.LinkList(title='Shared service settings in erred state') result_module.template = 'admin/dashboard/erred_link_list.html' erred_state = structure_models.ServiceSettings.States.ERRED @@ -120,7 +120,7 @@ class CustomIndexDashboard(FluentIndexDashboard): """ Returns a list of links to resources which are in ERRED state and linked to a shared service settings. """ - result_module = modules.LinkList(title='Resources in Erred state') + result_module = modules.LinkList(title='Resources in erred state') erred_state = structure_models.NewResource.States.ERRED children = []
Change Erred to lower case [WAL-<I>]
opennode_waldur-core
train
ac77ed4cc65c94c56ec26b8769ff3602887151d9
diff --git a/languagetool-dev/src/main/java/org/languagetool/dev/httpchecker/CheckCallable.java b/languagetool-dev/src/main/java/org/languagetool/dev/httpchecker/CheckCallable.java index <HASH>..<HASH> 100644 --- a/languagetool-dev/src/main/java/org/languagetool/dev/httpchecker/CheckCallable.java +++ b/languagetool-dev/src/main/java/org/languagetool/dev/httpchecker/CheckCallable.java @@ -95,7 +95,7 @@ class CheckCallable implements Callable<File> { postData += token != null ? "&token=" + URLEncoder.encode(token, "UTF-8"): ""; String tokenInfo = token != null ? " with token" : " without token"; float progress = (float)i / allLines.size() * 100.0f; - printOut(String.format(Locale.ENGLISH, threadName + " - Posting " + tempLines.size() + " texts with " + textToCheck.length() + + printOut(String.format(Locale.ENGLISH, threadName + " - Posting " + tempLines.size() + " texts from " + file.getName() + " with " + textToCheck.length() + " chars to " + url + tokenInfo + ", %.1f%%", progress)); for (int retry = 1; true; retry++) { String pseudoFileName = HttpApiSentenceChecker.class.getSimpleName() + "-result-" + count + "-" + startLine + "-" + i;
more verbose output to see whether inputs are deterministic
languagetool-org_languagetool
train
8754c2549f4dcf2bcd0ac27effc5f89ce246ca01
diff --git a/core/polyaxon/polypod/common/containers.py b/core/polyaxon/polypod/common/containers.py index <HASH>..<HASH> 100644 --- a/core/polyaxon/polypod/common/containers.py +++ b/core/polyaxon/polypod/common/containers.py @@ -51,7 +51,9 @@ def patch_container( ports, check_none=True ) container.resources = container.resources or resources - container.image_pull_policy = container.image_pull_policy or image_pull_policy + container.image_pull_policy = ( + container.image_pull_policy or image_pull_policy or "IfNotPresent" + ) container.image = container.image or image if not any([container.command, container.args]): diff --git a/core/polyaxon/polypod/init/auth.py b/core/polyaxon/polypod/init/auth.py index <HASH>..<HASH> 100644 --- a/core/polyaxon/polypod/init/auth.py +++ b/core/polyaxon/polypod/init/auth.py @@ -19,6 +19,7 @@ from typing import List from polyaxon.auxiliaries import V1PolyaxonInitContainer from polyaxon.containers.names import INIT_AUTH_CONTAINER from polyaxon.k8s import k8s_schemas +from polyaxon.polypod.common.containers import patch_container from polyaxon.polypod.common.mounts import get_auth_context_mount from polyaxon.utils.list_utils import to_list @@ -27,7 +28,7 @@ def get_auth_context_container( polyaxon_init: V1PolyaxonInitContainer, env: List[k8s_schemas.V1EnvVar] = None ) -> k8s_schemas.V1Container: env = to_list(env, check_none=True) - return k8s_schemas.V1Container( + container = k8s_schemas.V1Container( name=INIT_AUTH_CONTAINER, image=polyaxon_init.get_image(), image_pull_policy=polyaxon_init.image_pull_policy, @@ -36,3 +37,4 @@ def get_auth_context_container( resources=polyaxon_init.get_resources(), volume_mounts=[get_auth_context_mount(read_only=False)], ) + return patch_container(container) diff --git a/core/polyaxon/polypod/init/file.py b/core/polyaxon/polypod/init/file.py index <HASH>..<HASH> 100644 --- a/core/polyaxon/polypod/init/file.py +++ b/core/polyaxon/polypod/init/file.py @@ -27,6 +27,7 @@ from polyaxon.containers.names import ( ) from polyaxon.k8s import k8s_schemas from polyaxon.polypod.common import constants +from polyaxon.polypod.common.containers import patch_container from polyaxon.polypod.common.env_vars import get_run_instance_env_var from polyaxon.polypod.common.mounts import ( get_auth_context_mount, @@ -63,7 +64,7 @@ def get_file_init_container( volume_mounts.append(get_auth_context_mount(read_only=True)) file_args.filename = file_args.filename or "file" - return k8s_schemas.V1Container( + container = k8s_schemas.V1Container( name=generate_container_name(INIT_FILE_CONTAINER_PREFIX), image=polyaxon_init.get_image(), image_pull_policy=polyaxon_init.image_pull_policy, @@ -78,3 +79,4 @@ def get_file_init_container( resources=polyaxon_init.get_resources(), volume_mounts=volume_mounts, ) + return patch_container(container) diff --git a/core/polyaxon/polypod/sidecar/container.py b/core/polyaxon/polypod/sidecar/container.py index <HASH>..<HASH> 100644 --- a/core/polyaxon/polypod/sidecar/container.py +++ b/core/polyaxon/polypod/sidecar/container.py @@ -19,6 +19,7 @@ from typing import List, Optional from polyaxon.auxiliaries import V1PolyaxonSidecarContainer from polyaxon.exceptions import PolypodException from polyaxon.k8s import k8s_schemas +from polyaxon.polypod.common.containers import patch_container from polyaxon.polypod.common.env_vars import ( get_connection_env_var, get_env_from_config_map, @@ -138,7 +139,7 @@ def get_sidecar_container( check_none=True, ) - return k8s_schemas.V1Container( + container = k8s_schemas.V1Container( name=SIDECAR_CONTAINER, image=polyaxon_sidecar.get_image(), image_pull_policy=polyaxon_sidecar.image_pull_policy, @@ -149,3 +150,5 @@ def get_sidecar_container( resources=polyaxon_sidecar.get_resources(), volume_mounts=volume_mounts, ) + + return patch_container(container)
Add sanitization for auxiliary containers
polyaxon_polyaxon
train
8fe45b732b4b61048de1de427145b6c46cf29fef
diff --git a/src/Auth/Controller/UsersController.php b/src/Auth/Controller/UsersController.php index <HASH>..<HASH> 100644 --- a/src/Auth/Controller/UsersController.php +++ b/src/Auth/Controller/UsersController.php @@ -11,7 +11,6 @@ namespace Auth\Controller; use Zend\Mvc\Controller\AbstractActionController; -use Zend\Session\Container; use Zend\View\Model\ViewModel; use Zend\View\Model\JsonModel; use Auth\Repository\User as UserRepository; @@ -20,6 +19,10 @@ use Core\Form\SummaryFormInterface; /** * List registered users * + * @author Carsten Bleek <[email protected]> + * @author Mathias Gelhausen <[email protected]> + * @author Anthonius Munthi <[email protected]> + * * @method \Core\Controller\Plugin\CreatePaginator pagination() */ class UsersController extends AbstractActionController @@ -32,13 +35,16 @@ class UsersController extends AbstractActionController protected $formManager; + protected $viewHelper; + /** * @param UserRepository $userRepository */ - public function __construct(UserRepository $userRepository,$formManager) + public function __construct(UserRepository $userRepository,$formManager,$viewHelper) { $this->userRepository = $userRepository; $this->formManager = $formManager; + $this->viewHelper = $viewHelper; } /** @@ -65,7 +71,7 @@ class UsersController extends AbstractActionController /** * Edit user * - * @return \Zend\Http\Response|ViewModel + * @return \Zend\Http\Response|ViewModel|array */ public function editAction() { @@ -112,18 +118,18 @@ class UsersController extends AbstractActionController ); } - $serviceLocator->get('repositories')->store($user); + $this->userRepository->store($user); if ('file-uri' === $params->fromPost('return')) { $content = $form->getHydrator()->getLastUploadedFile()->getUri(); } else { if ($form instanceof SummaryFormInterface) { $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY); - $viewHelper = 'summaryform'; + $viewHelper = 'summaryForm'; } else { $viewHelper = 'form'; } - $content = $serviceLocator->get('ViewHelperManager')->get($viewHelper)->__invoke($form); + $content = $this->viewHelper->get($viewHelper)->__invoke($form); } return new JsonModel( diff --git a/src/Auth/Factory/Controller/UsersControllerFactory.php b/src/Auth/Factory/Controller/UsersControllerFactory.php index <HASH>..<HASH> 100644 --- a/src/Auth/Factory/Controller/UsersControllerFactory.php +++ b/src/Auth/Factory/Controller/UsersControllerFactory.php @@ -11,7 +11,7 @@ namespace Auth\Factory\Controller; use Auth\Controller\UsersController; use Interop\Container\ContainerInterface; -use Zend\ServiceManager\FactoryInterface; +use Zend\ServiceManager\Factory\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class UsersControllerFactory implements FactoryInterface @@ -34,7 +34,8 @@ class UsersControllerFactory implements FactoryInterface /* @var $users \Auth\Repository\User */ $users = $container->get('repositories')->get('Auth/User'); $formManager = $container->get('forms'); - return new UsersController($users,$formManager); + $viewHelper = $container->get('ViewHelperManager'); + return new UsersController($users,$formManager,$viewHelper); } /**
[ZF3][Behat,Organization] fixed errors when user updating their Organization pages
yawik_auth
train
0715d794462e8d49388316b8118a3b911a22eed8
diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -17,6 +17,7 @@ testit('passes', function () { passes('\npublic'); passes('abc // my comment', {lineComment: true}); passes('() => a'); + passes('function (a = "default") {"use strict";}'); }); function error(src, line, col, options) { @@ -43,4 +44,5 @@ testit('fails', function () { error('\npublic', 2, 0, {strict: true}); error('abc // my comment', 1, 4); error('() => a', 1, 1, {ecmaVersion: 5}); + error('function (a = "default") {"use strict";}', 1, 26, {ecmaVersion: 7}); });
Add a test case for ES<I> features
pugjs_is-expression
train
40410f0485c8566f1c43868cde16e68d5f57eb80
diff --git a/bika/lims/content/artemplate.py b/bika/lims/content/artemplate.py index <HASH>..<HASH> 100644 --- a/bika/lims/content/artemplate.py +++ b/bika/lims/content/artemplate.py @@ -169,6 +169,8 @@ class ARTemplate(BaseContent): """ uid = None if value: + # Strip "Lab: " from sample point title + value = value.replace("%s: " % _("Lab"), '') bsc = getToolByName(self, 'bika_setup_catalog') items = bsc(portal_type = 'SamplePoint', title = value) if not items:
Strip "Lab: " prefix from lab sample points in AR Template add
senaite_senaite.core
train
324268cae808b0d04dcd6573eaebedc1de10fb73
diff --git a/src/test/php/net/stubbles/webapp/WebAppTestCase.php b/src/test/php/net/stubbles/webapp/WebAppTestCase.php index <HASH>..<HASH> 100644 --- a/src/test/php/net/stubbles/webapp/WebAppTestCase.php +++ b/src/test/php/net/stubbles/webapp/WebAppTestCase.php @@ -30,7 +30,7 @@ class TestWebApp extends WebApp return self::$methodName($param); } - public function callable(WebRequest $request, Response $response) + public function callableMethod(WebRequest $request, Response $response) { $response->addHeader('X-Binford', '6100 (More power!)'); } @@ -48,9 +48,9 @@ class TestWebApp extends WebApp $response->write('Hello world!'); } ) - ->preIntercept(array($this, 'callable')) + ->preIntercept(array($this, 'callableMethod')) ->postIntercept('some\PostInterceptor') - ->postIntercept(array($this, 'callable')) + ->postIntercept(array($this, 'callableMethod')) ->postIntercept(function(WebRequest $request, Response $response) { $response->addCookie(Cookie::create('foo', 'bar')); @@ -70,7 +70,7 @@ class TestWebApp extends WebApp } ) ->preIntercept('some\PreInterceptor') - ->preIntercept(array($this, 'callable')) + ->preIntercept(array($this, 'callableMethod')) ->preIntercept(function(WebRequest $request, Response $response) { $response->setStatusCode(508); @@ -91,7 +91,7 @@ class TestWebApp extends WebApp } ) ->preIntercept('some\PreInterceptor') - ->preIntercept(array($this, 'callable')) + ->preIntercept(array($this, 'callableMethod')) ->postIntercept(function(WebRequest $request, Response $response) { $response->setStatusCode(304); @@ -103,7 +103,7 @@ class TestWebApp extends WebApp $response->setStatusCode(418); } ) - ->preIntercept(array($this, 'callable')) + ->preIntercept(array($this, 'callableMethod')) ->postIntercept('some\PostInterceptor') ->postIntercept(function(WebRequest $request, Response $response) {
callable is reserved keyword in PHP <I>
stubbles_stubbles-webapp-core
train
e85fffa51f89f5fa20d5910dadc1ede8f9c69ac8
diff --git a/example/idp2/idp.py b/example/idp2/idp.py index <HASH>..<HASH> 100755 --- a/example/idp2/idp.py +++ b/example/idp2/idp.py @@ -516,7 +516,7 @@ def do_authentication(environ, start_response, authn_context, key, PASSWD = { "daev0001": "qwerty", - "haho0032": "qwerty", + "testuser": "qwerty", "roland": "dianakra", "babs": "howes", "upper": "crust"} diff --git a/example/idp2/idp_user.py b/example/idp2/idp_user.py index <HASH>..<HASH> 100644 --- a/example/idp2/idp_user.py +++ b/example/idp2/idp_user.py @@ -35,22 +35,22 @@ #USERS = LDAPDict(**ldap_settings) USERS = { - "haho0032": { - "sn": "Hoerberg", - "givenName": "Hasse", + "testuser": { + "sn": "Testsson", + "givenName": "Test", "eduPersonAffiliation": "student", "eduPersonScopedAffiliation": "[email protected]", - "eduPersonPrincipalName": "[email protected]", - "uid": "haho0032", + "eduPersonPrincipalName": "[email protected]", + "uid": "testuser", "eduPersonTargetedID": "one!for!all", "c": "SE", "o": "Example Co.", "ou": "IT", "initials": "P", "schacHomeOrganization": "example.com", - "email": "[email protected]", - "displayName": "Hans Hoerberg", - "labeledURL": "http://www.example.com/haho My homepage", + "email": "[email protected]", + "displayName": "Test Testsson", + "labeledURL": "http://www.example.com/test My homepage", "norEduPersonNIN": "SE199012315555" }, "roland": { diff --git a/example/sp-wsgi/sp.py b/example/sp-wsgi/sp.py index <HASH>..<HASH> 100755 --- a/example/sp-wsgi/sp.py +++ b/example/sp-wsgi/sp.py @@ -35,7 +35,7 @@ from saml2.s_utils import UnsupportedBinding from saml2.s_utils import sid from saml2.s_utils import rndstr #from srtest import exception_trace -from saml2.md import Extensions +from saml2.samlp import Extensions import xmldsig as ds logger = logging.getLogger("") diff --git a/src/saml2/s2repoze/plugins/sp.py b/src/saml2/s2repoze/plugins/sp.py index <HASH>..<HASH> 100644 --- a/src/saml2/s2repoze/plugins/sp.py +++ b/src/saml2/s2repoze/plugins/sp.py @@ -14,7 +14,7 @@ import traceback import saml2 import six from urlparse import parse_qs, urlparse -from saml2.md import Extensions +from saml2.samlp import Extensions from saml2 import xmldsig as ds from StringIO import StringIO
Fix to use the correct Extensions element.
IdentityPython_pysaml2
train
2dab655765499e9b05b8f097ab446ddee8f9adca
diff --git a/misc/write_fake_manifests.py b/misc/write_fake_manifests.py index <HASH>..<HASH> 100644 --- a/misc/write_fake_manifests.py +++ b/misc/write_fake_manifests.py @@ -65,7 +65,7 @@ class GenRandom(object): def _n_unique_strings(self, n): seen = set([None]) return [self._unique_string(seen, avg_options=3, p_suffix=0.4) - for _ in xrange(n)] + for _ in range(n)] def target_name(self): return self._unique_string(p_suffix=0, seen=self.seen_names) @@ -73,7 +73,7 @@ class GenRandom(object): def path(self): return os.path.sep.join([ self._unique_string(self.seen_names, avg_options=1, p_suffix=0) - for _ in xrange(1 + paretoint(0.6, alpha=4))]) + for _ in range(1 + paretoint(0.6, alpha=4))]) def src_obj_pairs(self, path, name): num_sources = paretoint(55, alpha=2) + 1 @@ -84,7 +84,7 @@ class GenRandom(object): def defines(self): return [ '-DENABLE_' + self._unique_string(self.seen_defines).upper() - for _ in xrange(paretoint(20, alpha=3))] + for _ in range(paretoint(20, alpha=3))] LIB, EXE = 0, 1 @@ -227,7 +227,7 @@ def random_targets(num_targets, src_dir): gen = GenRandom(src_dir) # N-1 static libraries, and 1 executable depending on all of them. - targets = [Target(gen, LIB) for i in xrange(num_targets - 1)] + targets = [Target(gen, LIB) for i in range(num_targets - 1)] for i in range(len(targets)): targets[i].deps = [t for t in targets[0:i] if random.random() < 0.05]
xrange() was removed in Python 3 in favor of range() (#<I>) <URL>
ninja-build_ninja
train
cf114a1642b2f8d1808711b13f24fb32413ca727
diff --git a/src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java b/src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java index <HASH>..<HASH> 100644 --- a/src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java +++ b/src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java @@ -729,7 +729,7 @@ public class BrowserTest extends SlimFixture { protected String getXPathForColumnIndex(String columnName) { // determine how many columns are before the column with the requested name // the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based) - return String.format("count(//tr/th[normalize-space(descendant-or-self::text())='%s']/preceding-sibling::th)+1", columnName); + return String.format("count(//tr/th/descendant-or-self::text()[normalize-space(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName); } protected WebElement getElement(String place) {
deal with mixed content elements in header, and deal with case that table is nested inside another table
fhoeben_hsac-fitnesse-fixtures
train
b1fa9be574f3544ea79eecc70b3495d8569f361a
diff --git a/lex/lexer.go b/lex/lexer.go index <HASH>..<HASH> 100644 --- a/lex/lexer.go +++ b/lex/lexer.go @@ -1150,12 +1150,19 @@ func LexIdentifierOfType(forToken TokenType) StateFn { //u.Debugf("quoted?: %v ", l.input[l.start:l.pos]) default: l.lastQuoteMark = 0 - if !isIdentifierFirstRune(firstChar) { + if !isIdentifierFirstRune(firstChar) && !isDigit(firstChar) { //u.Warnf("aborting LexIdentifier: '%v'", string(firstChar)) return l.errorToken("identifier must begin with a letter " + string(l.input[l.start:l.pos])) } + allDigits := isDigit(firstChar) for rune := l.Next(); isIdentifierRune(rune); rune = l.Next() { // iterate until we find non-identifer character + if allDigits && !isDigit(rune) { + allDigits = false + } + } + if allDigits { + return l.errorToken("identifier must begin with a letter " + string(l.input[l.start:l.pos])) } l.backup() }
support identities that start with digits as long as not all digits
araddon_qlbridge
train
f70deff840b1c95d28b314369238755e177c1119
diff --git a/pythainlp/tokenize/__init__.py b/pythainlp/tokenize/__init__.py index <HASH>..<HASH> 100644 --- a/pythainlp/tokenize/__init__.py +++ b/pythainlp/tokenize/__init__.py @@ -111,12 +111,14 @@ def word_tokenize(text, engine='newmm', custom_dict_trie=None): # wordcutpy ใช้ wordcutpy (https://github.com/veer66/wordcutpy) ในการตัดคำ from .wordcutpy import segment from wordcut import Wordcut - wordcut = Wordcut.bigthai() if trie is DEFAULT_DICT_TRIE else Wordcut(trie.keys()) + if trie is DEFAULT_DICT_TRIE: + wordcut = Wordcut.bigthai() + else: + wordcut = Wordcut(trie.keys()) + return segment(text, wordcut) if engine in TRIE_WORD_SEGMENT_ENGINES: return segment(text, trie) - elif engine == 'wordcutpy': - return segment(text, wordcut) return segment(text) def sent_tokenize(text,engine='whitespace+newline'):
fixed deeply nested control flow statements
PyThaiNLP_pythainlp
train
3678d06567752603999af8da8330a16679437218
diff --git a/tests/Unit/Stomp/StompTest.php b/tests/Unit/Stomp/StompTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/Stomp/StompTest.php +++ b/tests/Unit/Stomp/StompTest.php @@ -223,7 +223,7 @@ class StompTest extends PHPUnit_Framework_TestCase public function testLoginDataFromConstructorIsUsedIfNoLoginDataPassedToConnect() { $stomp = $this->getStompMockWithSendFrameCatcher($lastSendFrame, $lastSyncState); - $connection = $this->getMock('Stomp\Connection', [], [], '', false); + $connection = $this->getMock('Stomp\Connection', array(), array(), '', false); $stomp->__construct($connection, 'myUser', 'myPassword'); @@ -247,7 +247,7 @@ class StompTest extends PHPUnit_Framework_TestCase public function testLoginDataFromConstructorIsIgnoredIfLoginDataPassedToConnect() { $stomp = $this->getStompMockWithSendFrameCatcher($lastSendFrame, $lastSyncState); - $connection = $this->getMock('Stomp\Connection', [], [], '', false); + $connection = $this->getMock('Stomp\Connection', array(), array(), '', false); $stomp->__construct($connection, 'myUserFirst', 'myPasswordFirst');
fixed array syntax in order to allow usage in php-<I>
stomp-php_stomp-php
train
6c7523ce6236a18ba051edc3e5f07bb598ed16ce
diff --git a/ffn/core.py b/ffn/core.py index <HASH>..<HASH> 100644 --- a/ffn/core.py +++ b/ffn/core.py @@ -1721,14 +1721,32 @@ def rollapply(data, window, fn): return res +def _winsorize_wrapper(x, limits): + """ + Wraps scipy winsorize function to drop na's + """ + if hasattr(x, 'dropna'): + if len(x.dropna()) == 0: + return x + + x[~np.isnan(x)] = scipy.stats.mstats.winsorize(x[~np.isnan(x)], + limits=limits) + return x + else: + return scipy.stats.mstats.winsorize(x, limits=limits) + + def winsorize(x, axis=0, limits=0.01): """ Winsorize values based on limits """ + # operate on copy + x = x.copy() + if isinstance(x, pd.DataFrame): - return x.apply(scipy.stats.mstats.winsorize, axis=axis, args=(limits, )) + return x.apply(_winsorize_wrapper, axis=axis, args=(limits, )) else: - return pd.Series(scipy.stats.mstats.winsorize(x, limits=limits).data, + return pd.Series(_winsorize_wrapper(x, limits).values, index=x.index) diff --git a/tests/test_core.py b/tests/test_core.py index <HASH>..<HASH> 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -432,3 +432,30 @@ def test_rollapply(): assert all(actual.iloc[2] == 2) assert all(actual.iloc[3] == 3) assert all(actual.iloc[4] == 4) + + +def test_winsorize(): + x = pd.Series(range(20), dtype='float') + res = x.winsorize(limits=0.05) + assert res.iloc[0] == 1 + assert res.iloc[-1] == 18 + + # make sure initial values still intact + assert x.iloc[0] == 0 + assert x.iloc[-1] == 19 + + x = pd.DataFrame({ + 'a': pd.Series(range(20), dtype='float'), + 'b': pd.Series(range(20), dtype='float') + }) + res = x.winsorize(axis=0, limits=0.05) + + assert res['a'].iloc[0] == 1 + assert res['b'].iloc[0] == 1 + assert res['a'].iloc[-1] == 18 + assert res['b'].iloc[-1] == 18 + + assert x['a'].iloc[0] == 0 + assert x['b'].iloc[0] == 0 + assert x['a'].iloc[-1] == 19 + assert x['b'].iloc[-1] == 19
winsorize on copy of data + tests
pmorissette_ffn
train
071914e06f4dc910ee9eb1f04b843a324b813840
diff --git a/lib/maildown/markdown_engine.rb b/lib/maildown/markdown_engine.rb index <HASH>..<HASH> 100644 --- a/lib/maildown/markdown_engine.rb +++ b/lib/maildown/markdown_engine.rb @@ -49,8 +49,6 @@ module Maildown end def self.default_html_block - require 'kramdown' unless defined? Kramdown - ->(string) { Kramdown::Document.new(string).to_html } end @@ -59,3 +57,5 @@ module Maildown end end end + +Maildown::MarkdownEngine.autoload(:"Kramdown", "kramdown")
Close #<I> (#<I>) There is a race condition described in #<I> where two threads can require the same library.
schneems_maildown
train
5c1ba0d9ac9731c5b95e0328c14a84a2e3c31e5b
diff --git a/Routing/ImagineLoader.php b/Routing/ImagineLoader.php index <HASH>..<HASH> 100644 --- a/Routing/ImagineLoader.php +++ b/Routing/ImagineLoader.php @@ -25,7 +25,7 @@ class ImagineLoader extends Loader public function load($resource, $type = null) { - $requirements = array('_method' => 'GET', 'filter' => '[A-z0-9_\-]*', 'path' => '.+'); + $requirements = array('_method' => 'GET', 'filter' => '[A-z0-9_\-]*', 'path' => '.+'); $defaults = array('_controller' => 'imagine.controller:filterAction'); $routes = new RouteCollection(); @@ -33,8 +33,10 @@ class ImagineLoader extends Loader foreach ($this->filters as $filter => $options) { if (isset($options['path'])) { $pattern = '/'.trim($options['path'], '/').'/{path}'; - } else { + } elseif ('' !== $filter) { $pattern = '/'.trim($this->cachePrefix, '/').$filter.'/{path}'; + } else { + $pattern = '/'.trim($this->cachePrefix, '/').'{path}'; } $routes->add('_imagine_'.$filter, new Route(
allow a filter to be an empty string
liip_LiipImagineBundle
train
1caf1e87eb2d554831a4819db7ffc99848e7c052
diff --git a/effects/equalizer.go b/effects/equalizer.go index <HASH>..<HASH> 100644 --- a/effects/equalizer.go +++ b/effects/equalizer.go @@ -38,11 +38,11 @@ type ( // GB (bandwidth gain) is given in decibels [dB] and represents // the level at which the bandwidth is measured. That is, to // have a meaningful measure of bandwidth, we must define the - // level at which it is measured. See Figure 1. + // level at which it is measured. GB float64 // G0 (reference gain) is given in decibels [dB] and simply - // represents the level of the section’s offset. See Figure 1. + // represents the level of the section’s offset. G0 float64 //G (boost/cut gain) is given in decibels [dB] and prescribes
remove references to 'figure 1' from the blog post
faiface_beep
train
5aa77fdd7b438f64d1a86c5b1d1b5f7bb1707ff5
diff --git a/FlowCal/excel_ui.py b/FlowCal/excel_ui.py index <HASH>..<HASH> 100644 --- a/FlowCal/excel_ui.py +++ b/FlowCal/excel_ui.py @@ -872,7 +872,7 @@ def run(verbose=True, plot=True): table_list.append(('Beads', beads_table)) table_list.append(('Samples', samples_table)) table_list.append(('Histograms', histograms_table)) - table_list.append(('About FlowCal', about_table)) + table_list.append(('About Analysis', about_table)) # Write output excel file if verbose:
Changed sheet name from 'About FlowCal' to 'About Analysis'.
taborlab_FlowCal
train
bb8d35f4eef9082097ae112f74510d5fb66fd211
diff --git a/spec/twitter/client/search_spec.rb b/spec/twitter/client/search_spec.rb index <HASH>..<HASH> 100644 --- a/spec/twitter/client/search_spec.rb +++ b/spec/twitter/client/search_spec.rb @@ -20,6 +20,7 @@ describe Twitter::Client do end it "should return recent statuses related to a query with images and videos embedded" do search = @client.search('twitter') + search.should be_a Twitter::SearchResults search.results.should be_an Array search.results.first.should be_a Twitter::Status search.results.first.text.should == "@KaiserKuo from not too far away your new twitter icon looks like Vader."
Assert SearchResults are returned from a client#search
sferik_twitter
train
358e9fb9ccd1848ca6019057afc117fbde67698f
diff --git a/src/keo.js b/src/keo.js index <HASH>..<HASH> 100644 --- a/src/keo.js +++ b/src/keo.js @@ -5,7 +5,7 @@ */ import objectAssign from 'object-assign'; import {createClass} from 'react'; -import {compose as comp, composeDeferred as compDeferred} from 'funkel'; +import * as fnkl from 'funkel'; export {memoize, trace, partial} from 'funkel'; export {objectAssign}; @@ -154,7 +154,7 @@ export const wrap = object => { * @return {Function} */ export const compose = (...fns) => { - return comp(...fns.reverse()); + return fnkl.compose(...fns.reverse()); }; /** @@ -163,5 +163,5 @@ export const compose = (...fns) => { * @return {Promise} */ export const composeDeferred = (...fns) => { - return compDeferred(...fns.reverse()); + return fnkl.composeDeferred(...fns.reverse()); };
Mapped Funkel functions to fnkl keyword
Wildhoney_Keo
train
319b3a57d5f1fb0dcab901fc3ed004754e7241af
diff --git a/runtests.py b/runtests.py index <HASH>..<HASH> 100755 --- a/runtests.py +++ b/runtests.py @@ -24,6 +24,11 @@ def configure(nose_args=None): 'extra_views.tests', ], ROOT_URLCONF='', + MIDDLEWARE_CLASSES=( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.middleware.common.CommonMiddleware', + ), DEBUG=False, USE_TZ=False, NOSE_ARGS=nose_args @@ -55,7 +60,7 @@ if __name__ == '__main__': # If no args, then use 'progressive' plugin to keep the screen real estate # used down to a minimum. Otherwise, use the spec plugin - nose_args = ['-s', '-x'] + nose_args = ['-s', '-x',] if options.with_spec: nose_args.append('--spec-color')
Add MIDDLEWARE_CLASSES to runtests.py. Django <I> throws a warning.
AndrewIngram_django-extra-views
train
bbd5a8360c2a7bb45a445f9532805a31f1f1b5fc
diff --git a/puz.py b/puz.py index <HASH>..<HASH> 100644 --- a/puz.py +++ b/puz.py @@ -561,7 +561,7 @@ def unshift(s, key): return shift(s, [-k for k in key]) def shuffle(s): - mid = math.floor(len(s) / 2) + mid = int(math.floor(len(s) / 2)) items = functools.reduce(operator.add, zip(s[mid:], s[:mid])) return ''.join(items) + (s[-1] if len(s) % 2 else '')
Make sure mid value is always an integer when shuffling
alexdej_puzpy
train
5baf100fc4bd9d48392cfe2ab7e793dcd4fc4629
diff --git a/cocaine/decorators/servers.py b/cocaine/decorators/servers.py index <HASH>..<HASH> 100644 --- a/cocaine/decorators/servers.py +++ b/cocaine/decorators/servers.py @@ -72,7 +72,7 @@ def wsgi(function): 'CONTENT_TYPE': headers.get('CONTENT-TYPE', ''), 'CONTENT_LENGTH': headers.get('CONTENT_LENGTH', ''), 'REMOTE_ADDR': meta.get('remote_addr', ''), - 'REMOTE_PORT': meta.get('remote_port', ''),, + 'REMOTE_PORT': meta.get('remote_port', ''), 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': '',
fixed another typo, come on Inkvi, watch what you commit
cocaine_cocaine-framework-python
train
9584d334137d4b1fbcc21f52911b73bbfdb1b23b
diff --git a/includes/class-freemius.php b/includes/class-freemius.php index <HASH>..<HASH> 100644 --- a/includes/class-freemius.php +++ b/includes/class-freemius.php @@ -4119,19 +4119,10 @@ // Clear API cache on activation. FS_Api::clear_cache(); - if ( $this->is_registered() ) { $is_premium_version_activation = ( current_filter() !== ( 'activate_' . $this->_free_plugin_basename ) ); - if ( $is_premium_version_activation ) { - $this->reconnect_locally(); - } - $this->_logger->info( 'Activating ' . ( $is_premium_version_activation ? 'premium' : 'free' ) . ' plugin version.' ); - // Schedule re-activation event and sync. -// $this->sync_install( array(), true ); - $this->schedule_install_sync(); - // 1. If running in the activation of the FREE module, get the basename of the PREMIUM. // 2. If running in the activation of the PREMIUM module, get the basename of the FREE. $other_version_basename = $is_premium_version_activation ? @@ -4148,6 +4139,15 @@ deactivate_plugins( $other_version_basename ); } + if ( $this->is_registered() ) { + if ( $is_premium_version_activation ) { + $this->reconnect_locally(); + } + + // Schedule re-activation event and sync. +// $this->sync_install( array(), true ); + $this->schedule_install_sync(); + // If activating the premium module version, add an admin notice to congratulate for an upgrade completion. if ( $is_premium_version_activation ) { $this->_admin_notices->add(
[auto-deactivation] [bug-fix] The auto deactivation of the free/premium version upon an activation of the other version was only working for opted-in users.
Freemius_wordpress-sdk
train
732fc6e56499535eb8c5b894e187a91bf9496c3d
diff --git a/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsMarketDataService.java b/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsMarketDataService.java index <HASH>..<HASH> 100644 --- a/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsMarketDataService.java +++ b/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsMarketDataService.java @@ -10,6 +10,7 @@ import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trades; +import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.service.marketdata.MarketDataService; /** @@ -27,12 +28,7 @@ public class AbucoinsMarketDataService extends AbucoinsMarketDataServiceRaw impl @Override public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { - try { - return AbucoinsAdapters.adaptTicker(getAbucoinsTicker(AbucoinsAdapters.adaptCurrencyPairToProductID(currencyPair)), currencyPair); - } - catch (Exception e) { - throw new IOException("Unable to get ticker for " + currencyPair, e); - } + return AbucoinsAdapters.adaptTicker(getAbucoinsTicker(AbucoinsAdapters.adaptCurrencyPairToProductID(currencyPair)), currencyPair); } @Override diff --git a/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsTradeService.java b/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsTradeService.java index <HASH>..<HASH> 100644 --- a/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsTradeService.java +++ b/xchange-abucoins/src/main/java/org/knowm/xchange/abucoins/service/AbucoinsTradeService.java @@ -14,6 +14,7 @@ import org.knowm.xchange.abucoins.dto.marketdata.AbucoinsCreateOrderResponse; import org.knowm.xchange.abucoins.dto.trade.AbucoinsOrder; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.*; +import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; @@ -62,7 +63,7 @@ public class AbucoinsTradeService extends AbucoinsTradeServiceRaw implements Tra AbucoinsCreateMarketOrderRequest req = AbucoinsAdapters.adaptAbucoinsCreateMarketOrderRequest(marketOrder); AbucoinsCreateOrderResponse resp = createAbucoinsOrder(req); if ( resp.getMessage() != null ) - throw new IOException(resp.getMessage()); + throw new ExchangeException(resp.getMessage()); return resp.getId(); } @@ -71,7 +72,7 @@ public class AbucoinsTradeService extends AbucoinsTradeServiceRaw implements Tra AbucoinsCreateLimitOrderRequest req = AbucoinsAdapters.adaptAbucoinsCreateLimitOrderRequest(limitOrder); AbucoinsCreateOrderResponse resp = createAbucoinsOrder(req); if ( resp.getMessage() != null ) - throw new IOException(resp.getMessage()); + throw new ExchangeException(resp.getMessage()); return resp.getId(); }
[abucoins] removing 'catch-all' Exception One method was catching any exceptions and wrapping them as IOExceptions (even if the original exception was an IOException). Just simplified it to let the Exceptions propagate with out interrupting them. Also, switched to the preferred IOException in a couple other places.
knowm_XChange
train
27bffa826c44b2f6c9e84ac46c74e9f206649d6e
diff --git a/src/date.js b/src/date.js index <HASH>..<HASH> 100644 --- a/src/date.js +++ b/src/date.js @@ -186,4 +186,8 @@ Date.prototype.isOddMonth = function() { Date.prototype.equalsOnlyDate = function(date) { return this.compareDateOnlyTo(date) == 0; +} + +Date.prototype.isBetweenDates = function(start, end) { + return this.compareDateOnlyTo(start) >= 0 && this.compareDateOnlyTo(end) <= 0; } \ No newline at end of file diff --git a/src/jquery.continuous-calendar.js b/src/jquery.continuous-calendar.js index <HASH>..<HASH> 100644 --- a/src/jquery.continuous-calendar.js +++ b/src/jquery.continuous-calendar.js @@ -140,28 +140,31 @@ return date.isOddMonth() ? ' odd' : ''; } - //TODO refactor function selectRange() { - var date1 = rangeStart.data("date"); - var date2 = rangeEnd.data("date"); - var start = (date1.compareDateOnlyTo(date2) > 0) ? date2 : date1; - var end = (date1.compareDateOnlyTo(date2) > 0) ? date1 : date2; calendarContainer.find(".date").removeClass("selected").each(function() { var elem = arguments[1]; var date = $(elem).data("date"); - if (date.compareDateOnlyTo(start) >= 0 && date.compareDateOnlyTo(end) <= 0) { + if (date.isBetweenDates(earlierDate(), laterDate())) { $(elem).addClass("selected"); } }); } - function updateTextFields() { + function earlierDate() { + var date1 = rangeStart.data("date"); + var date2 = rangeEnd.data("date"); + return (date1.compareDateOnlyTo(date2) > 0) ? date2 : date1; + } + + function laterDate() { var date1 = rangeStart.data("date"); var date2 = rangeEnd.data("date"); - var start = (date1.compareDateOnlyTo(date2) > 0) ? date2 : date1; - var end = (date1.compareDateOnlyTo(date2) > 0) ? date1 : date2; - startField.val(start.format(params.dateFormat)); - endField.val(end.format(params.dateFormat)); + return (date1.compareDateOnlyTo(date2) > 0) ? date1 : date2; + } + + function updateTextFields() { + startField.val(earlierDate().format(params.dateFormat)); + endField.val(laterDate().format(params.dateFormat)); } function isRange() {
refactor start and end date verification
continuouscalendar_dateutils
train
9366530e3837ee86de1af6c6d809476d5d53916e
diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -54,8 +54,8 @@ <properties> - <selenium-version>3.2.0</selenium-version> - <testng-version>6.8.21</testng-version> + <selenium-version>3.11.0</selenium-version> + <testng-version>6.14.2</testng-version> <org.slf4j.version>1.7.25</org.slf4j.version> <org.springframework-version>4.2.4.RELEASE</org.springframework-version> <allure.version>1.4.14</allure.version> @@ -348,13 +348,13 @@ <artifactId>guava</artifactId> <groupId>com.google.guava</groupId> <type>jar</type> - <version>21.0</version> + <version>23.0</version> </dependency> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> - <version>5.0.0-BETA6</version> + <version>6.0.0-BETA4</version> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> diff --git a/src/main/java/com/wiley/autotest/spring/SeleniumTestExecutionListener.java b/src/main/java/com/wiley/autotest/spring/SeleniumTestExecutionListener.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/wiley/autotest/spring/SeleniumTestExecutionListener.java +++ b/src/main/java/com/wiley/autotest/spring/SeleniumTestExecutionListener.java @@ -58,9 +58,6 @@ public class SeleniumTestExecutionListener extends AbstractTestExecutionListener count.set(count.get() + 1); driverRestartCount.set(driverRestartCount.get() + 1); - //TODO NT - confirm if it the right place to call this method? - currentAlertCapability.set(alertCapability.get()); - boolean isRunWithGrid = settings.isRunTestsWithGrid(); Integer restartDriverCount = settings.getRestartDriverCount() != null ? settings.getRestartDriverCount() : 0; @@ -185,6 +182,9 @@ public class SeleniumTestExecutionListener extends AbstractTestExecutionListener quitWebDriver(); } + //TODO NT. Need to clarify it's right place or not. + currentAlertCapability.set(alertCapability.get()); + if (getWebDriver() == null) { prepareTestInstance(context); } diff --git a/src/main/java/com/wiley/autotest/spring/testexecution/capabilities/SafariTechPreviewCaps.java b/src/main/java/com/wiley/autotest/spring/testexecution/capabilities/SafariTechPreviewCaps.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/wiley/autotest/spring/testexecution/capabilities/SafariTechPreviewCaps.java +++ b/src/main/java/com/wiley/autotest/spring/testexecution/capabilities/SafariTechPreviewCaps.java @@ -15,7 +15,6 @@ public class SafariTechPreviewCaps extends TeasyCaps { public DesiredCapabilities get() { DesiredCapabilities caps = DesiredCapabilities.safari(); SafariOptions safariOptions = new SafariOptions(); - safariOptions.setUseCleanSession(true); safariOptions.setUseTechnologyPreview(true); caps.setCapability(SafariOptions.CAPABILITY, safariOptions); setLoggingPrefs(caps);
update selenium, testng, guava and appium versions
WileyLabs_teasy
train
58054ab1f1dfe09f1065ca3638ede673fb364a51
diff --git a/python/neuroglancer/static/__init__.py b/python/neuroglancer/static/__init__.py index <HASH>..<HASH> 100644 --- a/python/neuroglancer/static/__init__.py +++ b/python/neuroglancer/static/__init__.py @@ -19,7 +19,6 @@ static_content_filenames = set([ 'main.bundle.js', 'main.css', 'chunk_worker.bundle.js', - 'tfjs-library.bundle.js', 'async_computation.bundle.js', 'index.html', 'draco.bundle.js', diff --git a/python/setup.py b/python/setup.py index <HASH>..<HASH> 100755 --- a/python/setup.py +++ b/python/setup.py @@ -23,7 +23,6 @@ static_files = [ 'main.bundle.js', 'main.css', 'chunk_worker.bundle.js', - 'tfjs-library.bundle.js', 'async_computation.bundle.js', 'draco.bundle.js', 'index.html',
chore(python): fix build to not reference removed tfjs-library-bundle file
google_neuroglancer
train
432c851ffdce885c142bc449f9c43cb38ad81411
diff --git a/rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/ValidateWS.java b/rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/ValidateWS.java index <HASH>..<HASH> 100644 --- a/rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/ValidateWS.java +++ b/rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/ValidateWS.java @@ -73,6 +73,7 @@ public class ValidateWS extends AbstractRDFUnitWebService { throw new TestCaseExecutionException(null, "Cannot initialize test executor. Exiting"); } final SimpleTestExecutorMonitor testExecutorMonitor = new SimpleTestExecutorMonitor(); + testExecutorMonitor.setExecutionType(configuration.getTestCaseExecutionType()); testExecutor.addTestExecutorMonitor(testExecutorMonitor); // warning, caches intermediate results
handed down variable testcaseexecutiontype as it was causing a null pointer, since it was not set
AKSW_RDFUnit
train
74edcaf1e84aa8bf35e496b2bead833172a79fca
diff --git a/runtime/graphdriver/devmapper/deviceset.go b/runtime/graphdriver/devmapper/deviceset.go index <HASH>..<HASH> 100644 --- a/runtime/graphdriver/devmapper/deviceset.go +++ b/runtime/graphdriver/devmapper/deviceset.go @@ -864,7 +864,7 @@ func (devices *DeviceSet) MountDevice(hash, path string, mountLabel string) erro info.mountPath = path info.floating = false - return devices.setInitialized(hash) + return devices.setInitialized(info) } func (devices *DeviceSet) UnmountDevice(hash string, mode UnmountMode) error { @@ -955,12 +955,7 @@ func (devices *DeviceSet) HasActivatedDevice(hash string) bool { return devinfo != nil && devinfo.Exists != 0 } -func (devices *DeviceSet) setInitialized(hash string) error { - info := devices.Devices[hash] - if info == nil { - return fmt.Errorf("Unknown device %s", hash) - } - +func (devices *DeviceSet) setInitialized(info *DevInfo) error { info.Initialized = true if err := devices.saveMetadata(); err != nil { info.Initialized = false
devmapper: Pass info rather than hash to setInitialized We already have this at the caller, no need to look up again. Docker-DCO-<I>-
containers_storage
train
05eecfb3b17fc4a13861d059209063d8338f26f3
diff --git a/leaflet-search.js b/leaflet-search.js index <HASH>..<HASH> 100644 --- a/leaflet-search.js +++ b/leaflet-search.js @@ -24,7 +24,7 @@ L.Control.Search = L.Control.extend({ searchDelay: 300, //delay for searching after digit autoType: true, // Complete input with first suggested result and select this filled-in text. //TODO searchLimit: 100, //limit max results show in tooltip - autoPan: true, //auto panTo when click on tooltip + tipAutoSubmit: true, //auto map panTo when click on tooltip autoResize: true, //autoresize on input change //TODO autoCollapse: false, //collapse search control after result found animatePan: true, //animation after panTo @@ -178,7 +178,7 @@ L.Control.Search = L.Control.extend({ this._input.focus(); this._hideTooltip(); this._handleAutoresize(); - if(this.options.autoPan)//go to location + if(this.options.tipAutoSubmit)//go to location this._handleSubmit(); }, this);
renamed option autoPan in tipAutoSubmit
stefanocudini_leaflet-search
train
8c03ea31355894d2d9fb3625c5c731b8a621ebe8
diff --git a/sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java b/sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java index <HASH>..<HASH> 100644 --- a/sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java +++ b/sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java @@ -31,11 +31,8 @@ import org.sonar.core.persistence.Dto; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; + +import java.util.*; public final class RuleDto extends Dto<RuleKey> { @@ -141,16 +138,18 @@ public final class RuleDto extends Dto<RuleKey> { return this; } + @CheckForNull public Integer getSeverity() { return severity; } + @CheckForNull public String getSeverityString() { - return SeverityUtil.getSeverityFromOrdinal(severity); + return severity != null ? SeverityUtil.getSeverityFromOrdinal(severity) : null; } - public RuleDto setSeverity(String severity) { - return this.setSeverity(SeverityUtil.getOrdinalFromSeverity(severity)); + public RuleDto setSeverity(@Nullable String severity) { + return this.setSeverity(severity != null ? SeverityUtil.getOrdinalFromSeverity(severity) : null); } public RuleDto setSeverity(@Nullable Integer severity) {
Fix NPE when indexing manual rules
SonarSource_sonarqube
train
0cbd96594d9c444c86caf0358ab0b59761c4ea20
diff --git a/src/bundle/Resources/public/js/OnlineEditor/plugins/base/ez-custom-tag-base.js b/src/bundle/Resources/public/js/OnlineEditor/plugins/base/ez-custom-tag-base.js index <HASH>..<HASH> 100644 --- a/src/bundle/Resources/public/js/OnlineEditor/plugins/base/ez-custom-tag-base.js +++ b/src/bundle/Resources/public/js/OnlineEditor/plugins/base/ez-custom-tag-base.js @@ -144,12 +144,12 @@ const customTagBaseDefinition = { <div class="ez-custom-tag__header-btns"> <button class="btn ez-custom-tag__header-btn ez-custom-tag__header-btn--attributes" data-target="attributes"> <svg class="ez-icon ez-icon--small"> - <use xlink:href={window.eZ.helpers.icon.getIconPath('list')}></use> + <use xlink:href=${window.eZ.helpers.icon.getIconPath('list')}></use> </svg> </button> <button class="btn ez-custom-tag__header-btn ez-custom-tag__header-btn--content" data-target="content"> <svg class="ez-icon ez-icon--small"> - <use xlink:href={window.eZ.helpers.icon.getIconPath('edit')}></use> + <use xlink:href=${window.eZ.helpers.icon.getIconPath('edit')}></use> </svg> </button> </div>
EZP-<I>: Custom tags' switch between attributes and content is missing an icon (#<I>)
ezsystems_ezplatform-richtext
train
908513a2f0104ed527652d9344712912533b6ff7
diff --git a/app/controllers/railswiki/pages_controller.rb b/app/controllers/railswiki/pages_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/railswiki/pages_controller.rb +++ b/app/controllers/railswiki/pages_controller.rb @@ -79,11 +79,7 @@ module Railswiki title = params[:id] || params[:page_id] || params[:path] raise ActiveRecord::RecordNotFound, "Unknown page request" unless title - @page = Page.where(id: title).first || - Page.where(title: title).first || - Page.where(title: unprettify_title(title)).first || - Page.where(lowercase_title: title.downcase).first || - Page.where(lowercase_title: unprettify_title(title).downcase).first + @page = select_page(title) unless @page if user_can?(:create_page) diff --git a/app/helpers/railswiki/application_helper.rb b/app/helpers/railswiki/application_helper.rb index <HASH>..<HASH> 100644 --- a/app/helpers/railswiki/application_helper.rb +++ b/app/helpers/railswiki/application_helper.rb @@ -7,9 +7,7 @@ module Railswiki if page_or_title.is_a?(Page) page = page_or_title else - page = Page.where(id: page_or_title).first || - Page.where(title: page_or_title).first || - Page.where(lowercase_title: page_or_title.downcase).first + page = select_page(page_or_title) end return raw "<!-- no page #{page_or_title} -->" unless page @@ -17,6 +15,17 @@ module Railswiki return raw markdown.render page.content end + def select_page(page_or_title) + @select_pages ||= Hash.new do |hash, ref| + hash[ref] = Page.where(id: ref). + or(Page.where(title: [ref, unprettify_title(ref)]). + or(Page.where(lowercase_title: [ref.downcase, unprettify_title(ref.downcase)]))). + # joins("INNER JOIN railswiki_histories ON railswiki_pages.id=railswiki_histories.page_id AND railswiki_pages.latest_version_id=railswiki_histories.id"). + first + end + @select_pages[page_or_title] + end + def markdown # @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML.new()) @markdown ||= Redcarpet::Markdown.new(MarkdownRenderer.new()) diff --git a/app/models/railswiki/page.rb b/app/models/railswiki/page.rb index <HASH>..<HASH> 100644 --- a/app/models/railswiki/page.rb +++ b/app/models/railswiki/page.rb @@ -15,7 +15,7 @@ module Railswiki end def latest_version - histories.where(id: latest_version_id).first + @latest_version ||= histories.where(id: latest_version_id).first end def expose_json
Performance optimisations to page selection, caching
soundasleep_railswiki
train
3f71a8d71947c52895ad995f147233c0309e8197
diff --git a/src/Setup/SetupController.php b/src/Setup/SetupController.php index <HASH>..<HASH> 100644 --- a/src/Setup/SetupController.php +++ b/src/Setup/SetupController.php @@ -21,6 +21,13 @@ class SetupController implements SetupControllerInterface { */ protected $urls; + /** + * @var array + * A list of blocks to display on the setup page. Each item has: + * - file: string, relative path + * - class: string, a space-delimited list of CSS classes + * - is_active: bool + */ public $blocks; /** @@ -31,30 +38,37 @@ class SetupController implements SetupControllerInterface { $this->setup = $setup; $this->blocks = array( 'cvs-header' => array( + 'is_active' => TRUE, 'file' => 'block_header.php', 'class' => '', ), 'cvs-requirements' => array( + 'is_active' => TRUE, 'file' => 'block_requirements.php', 'class' => 'if-no-problems', ), 'cvs-l10n' => array( + 'is_active' => TRUE, 'file' => 'block_l10n.php', 'class' => 'if-no-errors', ), 'cvs-sample-data' => array( + 'is_active' => TRUE, 'file' => 'block_sample_data.php', 'class' => 'if-no-errors', ), 'cvs-components' => array( + 'is_active' => TRUE, 'file' => 'block_components.php', 'class' => 'if-no-errors', ), 'cvs-advanced' => array( + 'is_active' => TRUE, 'file' => 'block_advanced.php', 'class' => '', ), 'cvs-install' => array( + 'is_active' => TRUE, 'file' => 'block_install.php', 'class' => 'if-no-errors', ), @@ -281,10 +295,17 @@ class SetupController implements SetupControllerInterface { public function renderBlocks($_tpl_params) { $buf = ''; foreach ($this->blocks as $name => $block) { + if (!$block['is_active']) { + continue; + } + $block['name'] = $name; $buf .= sprintf("<div class=\"%s %s\">%s</div>", $name, $block['class'], - $this->render($this->getResourcePath($block['file']), $_tpl_params) + $this->render( + $this->getResourcePath($block['file']), + $_tpl_params + array('_tpl_block' => $block) + ) ); } return $buf;
SetupController - Add property 'is_active' for each block
civicrm_civicrm-setup
train
3be19ec08d3c6e2d44038f7ce8a934960c72064e
diff --git a/plugins/item_tasks/server/cli_parser.py b/plugins/item_tasks/server/cli_parser.py index <HASH>..<HASH> 100644 --- a/plugins/item_tasks/server/cli_parser.py +++ b/plugins/item_tasks/server/cli_parser.py @@ -40,11 +40,12 @@ _SLICER_TYPE_TO_GIRDER_MODEL_MAP = { def _validateParam(param): if param.channel == 'input' and param.typ not in _SLICER_TO_GIRDER_WORKER_INPUT_TYPE_MAP: - raise ValidationException('Input parameter type %s is currently not supported' % param.typ) + raise ValidationException( + 'Input parameter type %s is currently not supported.' % param.typ) if param.channel == 'output' and param.typ not in _SLICER_TO_GIRDER_WORKER_OUTPUT_TYPE_MAP: raise ValidationException( - 'Output parameter type %s is currently not supported' % param.typ) + 'Output parameter type %s is currently not supported.' % param.typ) def parseSlicerCliXml(fd): diff --git a/plugins/item_tasks/server/rest.py b/plugins/item_tasks/server/rest.py index <HASH>..<HASH> 100644 --- a/plugins/item_tasks/server/rest.py +++ b/plugins/item_tasks/server/rest.py @@ -102,10 +102,8 @@ class ItemTask(Resource): resource, resourceType=rtype, token=token, dataFormat='none') elif v['mode'] == 'inline': transformed[k] = { - 'mode': v['mode'], - 'data': v['data'], - 'type': 'none', - 'format': 'none' + 'mode': 'inline', + 'data': v['data'] } else: raise ValidationException('Invalid input mode: %s.' % v['mode']) diff --git a/plugins/item_tasks/web_client/main.js b/plugins/item_tasks/web_client/main.js index <HASH>..<HASH> 100644 --- a/plugins/item_tasks/web_client/main.js +++ b/plugins/item_tasks/web_client/main.js @@ -35,7 +35,7 @@ import taskItemLinkTemplate from './templates/taskItemLink.pug'; wrap(girder.plugins.jobs.views.JobDetailsWidget, 'render', function (render) { render.call(this); - if (this.job.has('itemTaskItemId')) { + if (this.job.has('itemTaskId')) { this.$('.g-job-info-value[property="title"]').html(taskItemLinkTemplate({ itemId: this.job.get('itemTaskId'), title: this.job.get('title') diff --git a/plugins/item_tasks/web_client/templates/jobDetails.pug b/plugins/item_tasks/web_client/templates/jobDetails.pug index <HASH>..<HASH> 100644 --- a/plugins/item_tasks/web_client/templates/jobDetails.pug +++ b/plugins/item_tasks/web_client/templates/jobDetails.pug @@ -4,7 +4,7 @@ each input, id in (job.get('itemTaskBindings').inputs || {}) li b.g-input-name #{id}:&nbsp; - if input.mode == 'inline' + if input.mode === 'inline' span.g-input-value= JSON.stringify(input.data) else if input.mode == 'girder' - a.g-input-value(href=`#${input.resource_type || 'file'}/${input.id}`) + a.g-input-value(href=`#${input.resource_type || 'file'}/${input.id}`) View #{input.resource_type} diff --git a/plugins/item_tasks/web_client/templates/taskItemLink.pug b/plugins/item_tasks/web_client/templates/taskItemLink.pug index <HASH>..<HASH> 100644 --- a/plugins/item_tasks/web_client/templates/taskItemLink.pug +++ b/plugins/item_tasks/web_client/templates/taskItemLink.pug @@ -1 +1 @@ -a(href=`#item/${itemId}`)= title +a(href=`#item_task/${itemId}/run`)= title
Fix links on job details view for task items
girder_girder
train
fb283e7769045289438cf343933c150918cda79e
diff --git a/lib/supreme.rb b/lib/supreme.rb index <HASH>..<HASH> 100644 --- a/lib/supreme.rb +++ b/lib/supreme.rb @@ -19,6 +19,14 @@ module Supreme mode.to_sym == :test end + def self.translate_hash_keys(translation, hash) + translated = {} + hash.each do |key, value| + new_key = translation[key.to_sym] || translation[key.to_s] ||key + translated[new_key.to_s] = value + end; translated + end + # Returns an instance of the API with settings from the Supreme class accessors. # # If you need to handle multiple accounts in your application you will need to diff --git a/lib/supreme/api.rb b/lib/supreme/api.rb index <HASH>..<HASH> 100644 --- a/lib/supreme/api.rb +++ b/lib/supreme/api.rb @@ -23,7 +23,10 @@ module Supreme def fetch(options) options = options.dup options[:partner_id] ||= partner_id - response = get('fetch', options) + response = get('fetch', Supreme.translate_hash_keys({ + :return_url => :returnurl, + :report_url => :reporturl + }, options)) if response.ok? Supreme::Transaction.new(response.body) end diff --git a/test/api_test.rb b/test/api_test.rb index <HASH>..<HASH> 100644 --- a/test/api_test.rb +++ b/test/api_test.rb @@ -17,7 +17,7 @@ class Supreme::APITest < Test::Unit::TestCase end def test_banklist_url - REST.stubs(:get).with(&@record_url) + REST.stubs(:get).with(&@record_url).returns(stub(:ok? => false)) @api.send(:get, 'banklist') uri = URI.parse(@url) @@ -44,9 +44,8 @@ class Supreme::APITest < Test::Unit::TestCase end def test_fetch_url - REST.stubs(:get).with(&@record_url) - @api.send(:get, 'fetch', @options) - + REST.stubs(:get).with(&@record_url).returns(stub(:ok? => false)) + @api.fetch(@options) uri = URI.parse(@url) assert_equal 'https', uri.scheme assert_equal 'secure.mollie.nl', uri.host @@ -60,8 +59,8 @@ class Supreme::APITest < Test::Unit::TestCase "bank_id" => "0031", "description" => "20 credits for your account", "partner_id" => "978234", - "return_url" => "http://example.com/payments/ad74hj23/thanks", - "report_url" => "http://example.com/payments/ad74hj23" + "returnurl" => "http://example.com/payments/ad74hj23/thanks", + "reporturl" => "http://example.com/payments/ad74hj23" }, parts) end diff --git a/test/supreme_test.rb b/test/supreme_test.rb index <HASH>..<HASH> 100644 --- a/test/supreme_test.rb +++ b/test/supreme_test.rb @@ -16,6 +16,15 @@ class SupremeTest < Test::Unit::TestCase assert !Supreme.test? end + def test_translate_hash_keys + assert_equal({}, Supreme.translate_hash_keys({}, {})) + assert_equal({'a' => 1}, Supreme.translate_hash_keys({}, {'a' => 1})) + assert_equal({'a' => 1, 'b' => 2}, Supreme.translate_hash_keys({'baby' => 'b'}, {'a' => 1, 'baby' => 2})) + assert_equal({'a' => 1, 'b' => 2}, Supreme.translate_hash_keys({:baby => 'b'}, {'a' => 1, 'baby' => 2})) + assert_equal({'a' => 1, 'b' => 2}, Supreme.translate_hash_keys({'baby' => 'b'}, {'a' => 1, :baby => 2})) + assert_equal({'a' => 1, 'b' => 2}, Supreme.translate_hash_keys({:baby => 'b'}, {:a => 1, :baby => 2})) + end + def test_holds_a_partner_id Supreme.partner_id = '678234' assert_equal '678234', Supreme.partner_id
Translate keys in the option hashes so we can have a nice(r) external API.
Fingertips_Supreme
train
21acfd03ea1f8b47c1a98d74ded54f34e31249d1
diff --git a/lib/git-runner/base.rb b/lib/git-runner/base.rb index <HASH>..<HASH> 100644 --- a/lib/git-runner/base.rb +++ b/lib/git-runner/base.rb @@ -12,6 +12,7 @@ module GitRunner Text.begin load_git_runner_gems + prepare_environment process_refs @@ -37,6 +38,10 @@ module GitRunner Gem::Specification._all.map(&:name).select { |gem| gem =~ /^git-runner-/ }.each { |name| require(name) } end + def prepare_environment + GitRunner::Command.execute('unset GIT_DIR') + end + def process_refs if refs && refs.is_a?(Array) repository_path = Dir.pwd
Unsetting the GIT_DIR environment variable, it was messing up git operations
jamesbrooks_git-runner
train
7374e12442379187fd577f19938a6540e21e6d86
diff --git a/tests/testapp/tests/test_resource.py b/tests/testapp/tests/test_resource.py index <HASH>..<HASH> 100644 --- a/tests/testapp/tests/test_resource.py +++ b/tests/testapp/tests/test_resource.py @@ -177,8 +177,7 @@ class TestResourceRelationship(TestCase): self.assertEqual( BResource.fields_to_one["aabstractone"]["name"], "a_abstract_one") - self.assertEqual( - BResource.fields_to_one["aone"]["name"], "a_one") + self.assertEqual(BResource.fields_to_one["aone"]["name"], "a_one") self.assertEqual( BResource.fields_to_one["aabstractone"]["related_resource"], @@ -189,6 +188,20 @@ class TestResourceRelationship(TestCase): AOneResource ) + def test_fields_to_one_other_model_foreign_key_default(self): + AResource = self.api.register(self.resources['A']) + AOneResource = self.api.register(self.resources['AOne']) + self.assertIn("as", AOneResource.fields_to_many) + self.assertEqual(AOneResource.fields_to_many["as"]["name"], "a_set") + self.assertEqual(AOneResource.fields_to_many["as"]["related_resource"], + AResource) + + def test_fields_to_one_other_model_foreign_key_related_name(self): + pass + + def test_fields_to_one_other_model_foreign_key_inheritance(self): + pass + class TestResource(TestCase): def test_resource_name(self):
add test for basic foreing key to current model lookup
pavlov99_jsonapi
train
a88f53890adcd20721a6afb6e36c4609da4a4fc5
diff --git a/src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java b/src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java +++ b/src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java @@ -136,7 +136,7 @@ public final class ProcessCompletions implements Runnable } int transferred = numberOfBytes.getValue(); - if (process.getStdoutPipe().ioCompletionKey == key) + if (process.getStdoutPipe() != null && process.getStdoutPipe().ioCompletionKey == key) { if (transferred > 0) { @@ -148,14 +148,14 @@ public final class ProcessCompletions implements Runnable process.readStdout(-1); } } - else if (process.getStdinPipe().ioCompletionKey == key) + else if (process.getStdinPipe() != null && process.getStdinPipe().ioCompletionKey == key) { if (process.writeStdin(transferred)) { queueWrite(process); } } - else if (process.getStderrPipe().ioCompletionKey == key) + else if (process.getStderrPipe() != null && process.getStderrPipe().ioCompletionKey == key) { if (transferred > 0) {
Add null pointer check. NPE can occur during JVM exit.
brettwooldridge_NuProcess
train
c41eedc3e01e5527a3d5c242fa1896f02ef0b261
diff --git a/lib/utils.js b/lib/utils.js index <HASH>..<HASH> 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -22,10 +22,7 @@ function arrayString(val) { if(i > 0) { result = result + ','; } - if(val[i] instanceof Date) { - result = result + JSON.stringify(val[i]); - } - else if(typeof val[i] === 'undefined') { + if(val[i] === null || typeof val[i] === 'undefined') { result = result + 'NULL'; } else if(Array.isArray(val[i])) { @@ -33,8 +30,7 @@ function arrayString(val) { } else { - result = result + - (val[i] === null ? 'NULL' : JSON.stringify(val[i])); + result = result + JSON.stringify(prepareValue(val[i])); } } result = result + '}'; diff --git a/test/unit/utils-tests.js b/test/unit/utils-tests.js index <HASH>..<HASH> 100644 --- a/test/unit/utils-tests.js +++ b/test/unit/utils-tests.js @@ -95,9 +95,24 @@ test('prepareValue: string prepared properly', function() { assert.strictEqual(out, 'big bad wolf'); }); -test('prepareValue: array prepared properly', function() { +test('prepareValue: simple array prepared properly', function() { var out = utils.prepareValue([1, null, 3, undefined, [5, 6, "squ,awk"]]); - assert.strictEqual(out, '{1,NULL,3,NULL,{5,6,"squ,awk"}}'); + assert.strictEqual(out, '{"1",NULL,"3",NULL,{"5","6","squ,awk"}}'); +}); + +test('prepareValue: complex array prepared properly', function() { + var out = utils.prepareValue([{ x: 42 }, { y: 84 }]); + assert.strictEqual(out, '{"{\\"x\\":42}","{\\"y\\":84}"}'); +}); + +test('prepareValue: date array prepared properly', function() { + helper.setTimezoneOffset(-330); + + var date = new Date(2014, 1, 1, 11, 11, 1, 7); + var out = utils.prepareValue([date]); + assert.strictEqual(out, '{"2014-02-01T11:11:01.007+05:30"}'); + + helper.resetTimezoneOffset(); }); test('prepareValue: arbitrary objects prepared properly', function() {
properly prepare complex arrays `arrayString` duplicated too much of `prepareValue`'s logic, and so didn't receive bugfixes for handling dates with timestamps. Defer to `prepareValue` whenever possible. This change enforces double-quote escaping of all array elements, regardless of whether escaping is necessary. This has the side-effect of properly escaping JSON arrays.
brianc_node-postgres
train
0ea430a84ff913e6988b4a11b61d607875b5e143
diff --git a/src/plugins/SmoothScroller.js b/src/plugins/SmoothScroller.js index <HASH>..<HASH> 100644 --- a/src/plugins/SmoothScroller.js +++ b/src/plugins/SmoothScroller.js @@ -61,8 +61,7 @@ export class SmoothScroller { y: Math.min(Math.max(this.scroll.y - event.deltaY, 0), height(this.wrapper) - window.innerHeight) }; - let i = this.scrollCallbacks.length; - while(i--) this.scrollCallbacks[i](this.scrollTarget); + this.triggerCallbacks(); } normalScroll() { @@ -82,11 +81,18 @@ export class SmoothScroller { y: this.scroll.y + (this.scrollTarget.y - this.scroll.y) * this.autoEase }; + this.triggerCallbacks(); + this.disableScroll = Math.abs(this.scrollTarget.y - this.scroll.y) > 1 || Math.abs(this.scrollTarget.x - this.scroll.x) > 1; if (this.disableScroll) requestAnimationFrame(this.autoScroll.bind(this)); else this.normalScroll(); } + triggerCallbacks() { + let i = this.scrollCallbacks.length; + while(i--) this.scrollCallbacks[i](this.scrollTarget); + } + update() { transform(this.wrapper, { x: -this.scroll.x, @@ -116,4 +122,12 @@ export class SmoothScroller { this.autoScroll(); } + + fixElement(element) { + this.fixed.push(element); + } + + unfixElement(element) { + this.fixed.slice(this.fixed.indexOf(element)); + } }; diff --git a/src/plugins/Wasabi.js b/src/plugins/Wasabi.js index <HASH>..<HASH> 100644 --- a/src/plugins/Wasabi.js +++ b/src/plugins/Wasabi.js @@ -68,7 +68,7 @@ export class Wasabi { }); append(document.body, this.debugWrapper); - if (this.scroller) this.scroller.fixed.push(this.debugWrapper); + if (this.scroller) this.scroller.fixElement(this.debugWrapper); } this.update(); @@ -210,6 +210,8 @@ export class Wasabi { } testSnapping(scrollTarget) { + if (this.scroller.disableScroll) return; + let previous = this.zones[this.currentZoneIndex-1], next = this.zones[this.currentZoneIndex+1]; @@ -242,7 +244,6 @@ export class Wasabi { } update() { - let i = this.zones.length, direction = this.previousScrollTop > this.scrollTop ? 'forward' : 'backward'; @@ -307,37 +308,29 @@ export class Wasabi { while(i--) { let zone = this.zones[i]; - if (zone.tween) { - zone.tween.kill(); - this.clearPropsForTimeline(zone.tween); - } - if (zone.progressTween) { - zone.progressTween.kill(); - this.clearPropsForTimeline(zone.progressTween); - } + if (zone.tween) this.killTimeline(zone.tween); + if (zone.progressTween) this.killTimeline(zone.progressTween); } - if (this.scroller && this.debugWrapper) - this.scroller.fixed.slice(this.scroller.fixed.indexOf(this.debugWrapper)); + if (this.scroller && this.debugWrapper) this.scroller.unfixElement(this.debugWrapper); unresize(this.resizeCallback); cancelAnimationFrame(this.updateRequest); } - clearPropsForTimeline(timeline) { - let target = timeline.target; + killTimeline(timeline) { + let tweens = timeline.getChildren(); + timeline.kill(); - if (target) { - timeline.timeline.set(target, { - clearProps: 'all' - }); - } - else { - let children = timeline.getChildren(), - i = children.length; - - while(i--) this.clearPropsForTimeline(children[i]) + let i = tweens.length, tween; + while(i--) { + tween = tweens[i]; + if (tween.target) { + TweenMax.set(tween.target, { + clearProps: Object.keys(tween.vars).join(',') + }); + } } } }
smooth scroller - fix and unfix element
chirashijs_chirashi
train
5db028612df78764c48e7171fbf2def3b7102eed
diff --git a/pkg/kubectl/cmd/describe_test.go b/pkg/kubectl/cmd/describe_test.go index <HASH>..<HASH> 100644 --- a/pkg/kubectl/cmd/describe_test.go +++ b/pkg/kubectl/cmd/describe_test.go @@ -24,7 +24,6 @@ import ( "k8s.io/apimachinery/pkg/api/meta" "k8s.io/client-go/rest/fake" - "k8s.io/kubernetes/pkg/api/legacyscheme" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/genericclioptions" @@ -108,7 +107,7 @@ func TestDescribeObject(t *testing.T) { _, _, rc := testData() tf := cmdtesting.NewTestFactory().WithNamespace("test") defer tf.Cleanup() - codec := legacyscheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) + codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) tf.UnstructuredClient = &fake.RESTClient{ NegotiatedSerializer: unstructuredSerializer, @@ -149,7 +148,7 @@ func TestDescribeListObjects(t *testing.T) { pods, _, _ := testData() tf := cmdtesting.NewTestFactory().WithNamespace("test") defer tf.Cleanup() - codec := legacyscheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) + codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) tf.UnstructuredClient = &fake.RESTClient{ NegotiatedSerializer: unstructuredSerializer, @@ -176,7 +175,7 @@ func TestDescribeObjectShowEvents(t *testing.T) { pods, _, _ := testData() tf := cmdtesting.NewTestFactory().WithNamespace("test") defer tf.Cleanup() - codec := legacyscheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) + codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) tf.UnstructuredClient = &fake.RESTClient{ NegotiatedSerializer: unstructuredSerializer, @@ -202,7 +201,7 @@ func TestDescribeObjectSkipEvents(t *testing.T) { pods, _, _ := testData() tf := cmdtesting.NewTestFactory().WithNamespace("test") defer tf.Cleanup() - codec := legacyscheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) + codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...) tf.UnstructuredClient = &fake.RESTClient{ NegotiatedSerializer: unstructuredSerializer, diff --git a/pkg/kubectl/cmd/rollingupdate.go b/pkg/kubectl/cmd/rollingupdate.go index <HASH>..<HASH> 100644 --- a/pkg/kubectl/cmd/rollingupdate.go +++ b/pkg/kubectl/cmd/rollingupdate.go @@ -32,7 +32,6 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/kubernetes" scaleclient "k8s.io/client-go/scale" - "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" @@ -311,7 +310,7 @@ func (o *RollingUpdateOptions) Run() error { // than the old rc. This selector is the hash of the rc, with a suffix to provide uniqueness for // same-image updates. if len(o.Image) != 0 { - codec := legacyscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion) + codec := scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion) newName := o.FindNewName(oldRc) if newRc, err = kubectl.LoadExistingNextReplicationController(coreClient, o.Namespace, newName); err != nil { return err
snip more legacy scheme uses we don't need ref:<URL>
kubernetes_kubernetes
train
2dad3a71dae84443fa12f8e238250595190637b3
diff --git a/lib/danger/request_sources/github/github.rb b/lib/danger/request_sources/github/github.rb index <HASH>..<HASH> 100644 --- a/lib/danger/request_sources/github/github.rb +++ b/lib/danger/request_sources/github/github.rb @@ -382,7 +382,7 @@ module Danger diff_lines.drop(file_start).each do |line| # If the line has `No newline` annotation, position need increment - if line.eql?("\ No newline at end of file\n") + if line.eql?("\\ No newline at end of file\n") position += 1 next end diff --git a/spec/lib/danger/request_sources/github_spec.rb b/spec/lib/danger/request_sources/github_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/danger/request_sources/github_spec.rb +++ b/spec/lib/danger/request_sources/github_spec.rb @@ -614,7 +614,7 @@ index <HASH>..<HASH> 100644 +++ b/#{file_path} @@ -1 +1,3 @@ -foo -\ No newline at end of file +\\ No newline at end of file +foo +bar +baz
Fix wrong test `No newline at end of file` annotation has backslash as first character. The here document diff in test, annotation line needs extra backslash because of escape.
danger_danger
train
3bbf2a3266ff20ca1d81a14aee38c70f690086af
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ } ], "require": { - "php": "^7.0", + "php": "^5.6 || ^7.0", "ext-gmp": "*", "ramsey/uuid": "^3.7", "guzzlehttp/guzzle": "^6.3", diff --git a/spec/UserDataItemSpec.php b/spec/UserDataItemSpec.php index <HASH>..<HASH> 100644 --- a/spec/UserDataItemSpec.php +++ b/spec/UserDataItemSpec.php @@ -20,13 +20,13 @@ class UserDataItemSpec extends ObjectBehavior function it_is_json_serializable() { - $this->shouldImplement(JsonSerializable::class); - assert(json_encode($this->getWrappedObject()) === json_encode([ - 'label' => 'label', - 'value' => 'value', - 'isValid' => true, - 'isOwner' => false, - ]), 'JSON representation'); + $this->shouldImplement(JsonSerializable::class); + assert(json_encode($this->getWrappedObject()) === json_encode([ + 'label' => 'label', + 'value' => 'value', + 'isValid' => true, + 'isOwner' => false, + ]), 'JSON representation'); } public function it_is_readable() diff --git a/spec/UserDataSpec.php b/spec/UserDataSpec.php index <HASH>..<HASH> 100644 --- a/spec/UserDataSpec.php +++ b/spec/UserDataSpec.php @@ -25,11 +25,11 @@ class UserDataSpec extends ObjectBehavior function it_is_json_serializable() { - $this->shouldImplement(JsonSerializable::class); - assert(json_encode($this->getWrappedObject()) === json_encode([ - ['label' => 'label1', 'value' => 'value1', 'isValid' => true, 'isOwner' => true], - ['label' => 'label2', 'value' => 'value2', 'isValid' => true, 'isOwner' => false], - ]), 'JSON representation'); + $this->shouldImplement(JsonSerializable::class); + assert(json_encode($this->getWrappedObject()) === json_encode([ + ['label' => 'label1', 'value' => 'value1', 'isValid' => true, 'isOwner' => true], + ['label' => 'label2', 'value' => 'value2', 'isValid' => true, 'isOwner' => false], + ]), 'JSON representation'); } function it_returns_data_items()
Lower composer require to php<I>
blockvis_civic-sip-php
train
f9bcda93257ec64fceab62bd75075fb762f2c669
diff --git a/squad/frontend/tests.py b/squad/frontend/tests.py index <HASH>..<HASH> 100644 --- a/squad/frontend/tests.py +++ b/squad/frontend/tests.py @@ -83,19 +83,20 @@ class TestResultTable(list): suite_id, name, SUM(CASE when result is null then 1 else 0 end) as skips, - SUM(CASE when result is null then 0 when result then 0 else 1 end) as fails, + SUM(CASE when result is not null and not result and not has_known_issues then 1 else 0 end) as fails, + SUM(CASE when result is not null and not result and has_known_issues then 1 else 0 end) as xfails, SUM(CASE when result is null then 0 when result then 1 else 0 end) as passes FROM core_test JOIN core_testrun ON core_testrun.id = core_test.test_run_id WHERE core_testrun.build_id = %s GROUP BY suite_id, name - ORDER BY fails DESC, skips DESC, passes DESC, suite_id, name + ORDER BY fails DESC, xfails DESC, skips DESC, passes DESC, suite_id, name LIMIT %s OFFSET %s """ with connection.cursor() as cursor: cursor.execute(query, [build_id, per_page, offset]) - for suite_id, name, _, _, _ in cursor.fetchall(): + for suite_id, name, _, _, _, _ in cursor.fetchall(): conditions.setdefault(suite_id, []) conditions[suite_id].append(name)
frontend: "All tests": fix sorting in the presence of xfail Tests are ordered by decreasing number of fails, xfails, skips, and passes.
Linaro_squad
train
52955ee8dfd106fa9df55ded0ea0cdb75c9d9945
diff --git a/client/lib/signup/step-actions/index.js b/client/lib/signup/step-actions/index.js index <HASH>..<HASH> 100644 --- a/client/lib/signup/step-actions/index.js +++ b/client/lib/signup/step-actions/index.js @@ -145,6 +145,10 @@ function getNewSiteParams( { get( signupDependencies, 'themeSlugWithRepo', false ) || siteTypeTheme; + // We will use the default annotation instead of theme annotation as fallback, + // when segment and vertical values are not sent. Check pbAok1-p2#comment-834. + const shouldUseDefaultAnnotationAsFallback = true; + const newSiteParams = { blog_title: siteTitle, public: Visibility.PublicNotIndexed, @@ -152,6 +156,7 @@ function getNewSiteParams( { designType: designType || undefined, theme, use_theme_annotation: get( signupDependencies, 'useThemeHeadstart', false ), + default_annotation_as_primary_fallback: shouldUseDefaultAnnotationAsFallback, siteGoals: siteGoals || undefined, site_style: siteStyle || undefined, site_segment: siteSegment || undefined,
New sites use default headstart annotation, not theme annotation (#<I>)
Automattic_wp-calypso
train
1f1ecd71019c1172da8ba639401053d585d9464f
diff --git a/src/basic/IconNB.js b/src/basic/IconNB.js index <HASH>..<HASH> 100644 --- a/src/basic/IconNB.js +++ b/src/basic/IconNB.js @@ -103,6 +103,7 @@ IconNB.propTypes = { 'Feather', 'FontAwesome', 'FontAwesome5', + 'Fontisto', 'Foundation', 'Ionicons', 'MaterialCommunityIcons',
fix: missing value Fontisto added to IconNB's prop types
GeekyAnts_NativeBase
train
d013f95751b2dd2d9776c8650a44001a7d5d0cff
diff --git a/src/Host/Storage.php b/src/Host/Storage.php index <HASH>..<HASH> 100644 --- a/src/Host/Storage.php +++ b/src/Host/Storage.php @@ -14,6 +14,72 @@ use function Deployer\Support\array_flatten; class Storage { + /** + * In a multi user environment where multiple projects are located on the same instance(s) + * if two or more users are deploying a project on the same environment, the generated hosts files + * are overwritten or worse, the deploy will fail due to file permissions + * + * Make the persistent storage folder configurable or use the system tmp + * as default if not possible + * + * @return string + * @throws Exception + */ + private static function _getPersistentStorageLocation() { + $config = \Deployer\Deployer::get()->config; + + // default persistent storage in case we can't use the configured value + // or we can't create the default location + // use the system temporary folder and the current pid to make the path unique + $tmp = sys_get_temp_dir() . '/' . uuid(posix_getpid()); + + // get the location for the deployer configuration + $deployerConfig = $config->has('deployer_config') ? $config->get('deployer_config') : null; + + if ( !is_null($deployerConfig) ) { + // check if the folder exists and it's writable + if ( !(is_dir($deployerConfig) && is_writable($deployerConfig)) ) { + throw new Exception("Deployer folder `$deployerConfig` doesn't exists or doesn't writable."); + } + } else { + // not configured, generate deployer folder name + + // use the home dir of the current user + // and the repository name + $userInfo = posix_getpwuid(posix_getuid()); + + // if for some reason we couldn't find a valid home folder + // or if it's not writable, use the default location + if ( !isset($userInfo['dir']) || !(is_dir($userInfo['dir']) && is_writable($userInfo['dir'])) ) { + return $tmp; + } + + // we have a folder name + $deployerConfig = $userInfo['dir'] . '/.deployer'; + + //if it doesn't exists, create it + if ( !file_exists($deployerConfig) ) { + mkdir($deployerConfig, 0777, true); + } + + //it exists, check if it's a folder and if it's writable + if ( !(is_dir($deployerConfig) && is_writable($deployerConfig)) ) { + return $tmp; + } + } + + // we will store the persistent data per repository + $configRepository = $config->has('repository') ? $config->get('repository') : null; + if (empty($configRepository)) { + return $tmp; + } + + // we now have the repository name + $repository = str_replace('/', '_', substr($configRepository, (strrpos($configRepository, ':') + 1))); + + return $deployerConfig . '/' . $repository; + } + /** * @param Host[] $hosts */ @@ -27,7 +93,7 @@ class Storage $values[$key] = $host->get($key); } - $file = sys_get_temp_dir() . '/' . $host->getHostname() . '.dep'; + $file = self::_getPersistentStorageLocation() . '/' . $host->getHostname() . '.dep'; $values['host_config_storage'] = $file; $persistentCollection = new PersistentCollection($file, $values);
In a multi user environment where multiple projects are located on the same instance(s) if two or more users are deploying a project on the same environment, the generated hosts files are overwritten or worse, the deploy will fail due to file permissions Make the persistent storage folder configurable or use the system tmp as default if not possible
deployphp_deployer
train
97c000ddd83ec0f92d040a3a574d1d997759f4ee
diff --git a/pandas/tests/test_rplot.py b/pandas/tests/test_rplot.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_rplot.py +++ b/pandas/tests/test_rplot.py @@ -29,6 +29,10 @@ class TestUtilityFunctions(unittest.TestCase): """ Tests for RPlot utility functions. """ + def setUp(self): + path = os.path.join(curpath(), 'data/iris.csv') + self.data = read_csv(path, sep=',') + def test_make_aes1(self): aes = rplot.make_aes() self.assertTrue(aes['x'] is None) @@ -74,6 +78,19 @@ class TestUtilityFunctions(unittest.TestCase): if key != 'size' and key != 'shape': self.assertTrue(layer2.aes[key] is None) + def test_sequence_layers(self): + layer1 = rplot.Layer(self.data) + layer2 = rplot.GeomPoint(x='SepalLength', y='SepalWidth', size=rplot.ScaleSize('PetalLength')) + layer3 = rplot.GeomPolyFit(2) + result = rplot.sequence_layers([layer1, layer2, layer3]) + self.assertEqual(len(result), 3) + last = result[-1] + self.assertEqual(last.aes['x'], 'SepalLength') + self.assertEqual(last.aes['y'], 'SepalWidth') + self.assertTrue(isinstance(last.aes['size'], rplot.ScaleSize)) + self.assertTrue(self.data is last.data) + self.assertTrue(rplot.sequence_layers([layer1])[0] is layer1) + class TestScaleGradient(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/iris.csv')
Added test_sequence_layers method
pandas-dev_pandas
train
93c4cccc6ed0d973f16fce4d291396aa5c52f39e
diff --git a/builtin/logical/mysql/backend.go b/builtin/logical/mysql/backend.go index <HASH>..<HASH> 100644 --- a/builtin/logical/mysql/backend.go +++ b/builtin/logical/mysql/backend.go @@ -68,11 +68,13 @@ func (b *backend) DB(s logical.Storage) (*sql.DB, error) { fmt.Errorf("configure the DB connection with config/connection first") } - var conn string - if err := entry.DecodeJSON(&conn); err != nil { + var connConfig connectionConfig + if err := entry.DecodeJSON(&connConfig); err != nil { return nil, err } + conn := connConfig.ConnectionString + b.db, err = sql.Open("mysql", conn) if err != nil { return nil, err @@ -80,7 +82,7 @@ func (b *backend) DB(s logical.Storage) (*sql.DB, error) { // Set some connection pool settings. We don't need much of this, // since the request rate shouldn't be high. - b.db.SetMaxOpenConns(2) + b.db.SetMaxOpenConns(connConfig.MaxOpenConnections) return b.db, nil } diff --git a/builtin/logical/mysql/path_config_connection.go b/builtin/logical/mysql/path_config_connection.go index <HASH>..<HASH> 100644 --- a/builtin/logical/mysql/path_config_connection.go +++ b/builtin/logical/mysql/path_config_connection.go @@ -17,6 +17,10 @@ func pathConfigConnection(b *backend) *framework.Path { Type: framework.TypeString, Description: "DB connection string", }, + "max_open_connections": &framework.FieldSchema{ + Type: framework.TypeInt, + Description: "Maximum number of open connections to database", + }, }, Callbacks: map[logical.Operation]framework.OperationFunc{ @@ -32,8 +36,14 @@ func (b *backend) pathConnectionWrite( req *logical.Request, data *framework.FieldData) (*logical.Response, error) { connString := data.Get("value").(string) + maxOpenConns := data.Get("max_open_connections").(int) + if maxOpenConns == 0 { + maxOpenConns = 2 + } + // Verify the string db, err := sql.Open("mysql", connString) + if err != nil { return logical.ErrorResponse(fmt.Sprintf( "Error validating connection info: %s", err)), nil @@ -45,7 +55,10 @@ func (b *backend) pathConnectionWrite( } // Store it - entry, err := logical.StorageEntryJSON("config/connection", connString) + entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ + ConnectionString: connString, + MaxOpenConnections: maxOpenConns, + }) if err != nil { return nil, err } @@ -58,6 +71,11 @@ func (b *backend) pathConnectionWrite( return nil, nil } +type connectionConfig struct { + ConnectionString string `json:"value"` + MaxOpenConnections int `json:"max_open_connections"` +} + const pathConfigConnectionHelpSyn = ` Configure the connection string to talk to MySQL. ` diff --git a/website/source/docs/secrets/mysql/index.html.md b/website/source/docs/secrets/mysql/index.html.md index <HASH>..<HASH> 100644 --- a/website/source/docs/secrets/mysql/index.html.md +++ b/website/source/docs/secrets/mysql/index.html.md @@ -129,6 +129,16 @@ allowed to read. </li> </ul> </dd> + <dd> + <ul> + <li> + <span class="param">max_open_connections</span> + <span class="param-flags">optional</span> + Maximum number of open connections to the database. + Defaults to 2. + </li> + </ul> + </dd> <dt>Returns</dt> <dd>
mysql: made max_open_connections configurable
hashicorp_vault
train
76d11c92d455af5259ce193553a3d6d9329665d0
diff --git a/client_test.go b/client_test.go index <HASH>..<HASH> 100644 --- a/client_test.go +++ b/client_test.go @@ -1,7 +1,6 @@ package arp import ( - "bytes" "net" "reflect" "testing" @@ -228,7 +227,7 @@ func Test_firstIPv4Addr(t *testing.T) { continue } - if want, got := tt.ip.To4(), ip.To4(); !bytes.Equal(want, got) { + if want, got := tt.ip.To4(), ip.To4(); !want.Equal(got) { t.Fatalf("[%02d] test %q, unexpected IPv4 address: %v != %v", i, tt.desc, want, got) }
arp: compare net.IP with Equal method
mdlayher_arp
train
4739cc8c1d8073abaacb2eb496f6a8e075faa849
diff --git a/influxql/ast.go b/influxql/ast.go index <HASH>..<HASH> 100644 --- a/influxql/ast.go +++ b/influxql/ast.go @@ -183,12 +183,6 @@ func (a SortFields) String() string { type CreateDatabaseStatement struct { // Name of the database to be created. Name string - - // List of retention policies. - Policies []string - - // Default retention policy. - DefaultPolicy string } // String returns a string representation of the create database statement. @@ -196,14 +190,6 @@ func (s *CreateDatabaseStatement) String() string { var buf bytes.Buffer _, _ = buf.WriteString("CREATE DATABASE ") _, _ = buf.WriteString(s.Name) - for _, policy := range s.Policies { - _, _ = buf.WriteString(" WITH ") - if policy == s.DefaultPolicy { - _, _ = buf.WriteString("DEFAULT ") - } - _, _ = buf.WriteString("RETENTION POLICY ") - _, _ = buf.WriteString(policy) - } return buf.String() } diff --git a/influxql/parser.go b/influxql/parser.go index <HASH>..<HASH> 100644 --- a/influxql/parser.go +++ b/influxql/parser.go @@ -493,52 +493,6 @@ func (p *Parser) parseCreateDatabaseStatement() (*CreateDatabaseStatement, error } stmt.Name = lit - // Require at least one retention policy. - tok, pos, lit = p.scanIgnoreWhitespace() - if tok != WITH { - return nil, newParseError(tokstr(tok, lit), []string{"WITH"}, pos) - } - - policy, dfault, err := p.parseRetentionPolicy() - if err != nil { - return nil, err - } - - stmt.Policies = append(stmt.Policies, policy) - - if dfault { - stmt.DefaultPolicy = policy - } - - // Parse any additional retention policies. - for { - tok, pos, lit = p.scanIgnoreWhitespace() - if tok != WITH { - p.unscan() - break - } - - // Make sure there aren't multiple default policies. - tok, pos, lit = p.scanIgnoreWhitespace() - if tok == DEFAULT && stmt.DefaultPolicy != "" { - err := newParseError(tokstr(tok, lit), []string{"RETENTION"}, pos) - err.Message = "multiple default retention policies not allowed" - return nil, err - } - p.unscan() - - policy, dfault, err := p.parseRetentionPolicy() - if err != nil { - return nil, err - } - - stmt.Policies = append(stmt.Policies, policy) - - if dfault { - stmt.DefaultPolicy = policy - } - } - return stmt, nil } diff --git a/influxql/parser_test.go b/influxql/parser_test.go index <HASH>..<HASH> 100644 --- a/influxql/parser_test.go +++ b/influxql/parser_test.go @@ -292,20 +292,9 @@ func TestParser_ParseStatement(t *testing.T) { // CREATE DATABASE statement { - s: `CREATE DATABASE testdb WITH RETENTION POLICY policy1`, + s: `CREATE DATABASE testdb`, stmt: &influxql.CreateDatabaseStatement{ Name: "testdb", - Policies: []string{"policy1"}, - }, - }, - - // CREATE DATABASE statement with multiple retention policies - { - s: `CREATE DATABASE testdb WITH DEFAULT RETENTION POLICY policy1 WITH RETENTION POLICY policy2`, - stmt: &influxql.CreateDatabaseStatement{ - Name: "testdb", - Policies: []string{"policy1", "policy2"}, - DefaultPolicy: "policy1", }, },
remove RETENTION POLICY from CREATE DATABASE
influxdata_influxdb
train
6ef63c5920192806513f146874a1db2a1805f291
diff --git a/auth/cas/settings.php b/auth/cas/settings.php index <HASH>..<HASH> 100644 --- a/auth/cas/settings.php +++ b/auth/cas/settings.php @@ -78,7 +78,7 @@ if ($ADMIN->fulltree) { } $settings->add(new admin_setting_configselect('auth_cas/language', new lang_string('auth_cas_language_key', 'auth_cas'), - new lang_string('auth_cas_language', 'auth_cas'), '', $CASLANGUAGES)); + new lang_string('auth_cas_language', 'auth_cas'), PHPCAS_LANG_ENGLISH, $CASLANGUAGES)); // Proxy. $yesno = array(
MDL-<I> auth_cas: Default to English
moodle_moodle
train
5fd574659f1da2e16beb707f477bfb5103b32ee8
diff --git a/src/extensions/renderer/base/coord-ele-math.js b/src/extensions/renderer/base/coord-ele-math.js index <HASH>..<HASH> 100644 --- a/src/extensions/renderer/base/coord-ele-math.js +++ b/src/extensions/renderer/base/coord-ele-math.js @@ -128,26 +128,31 @@ BRp.recalculateRenderedStyle = function( eles, useCache ){ if( (useCache && rstyle.clean) || ele.removed() ){ continue; } if( _p.group === 'nodes' ){ - var pos = _p.position; - nodes.push( ele ); - - rstyle.nodeX = pos.x; - rstyle.nodeY = pos.y; - rstyle.nodeW = ele.pstyle( 'width' ).pfValue; - rstyle.nodeH = ele.pstyle( 'height' ).pfValue; } else { // edges - edges.push( ele ); - - } // if edges + } rstyle.clean = true; // rstyle.dirtyEvents = null; } + // update node data from projections + for( var i = 0; i < nodes.length; i++ ){ + var ele = nodes[i]; + var _p = ele._private; + var rstyle = _p.rstyle; + var pos = _p.position; + + this.recalculateNodeLabelProjection( ele ); + + rstyle.nodeX = pos.x; + rstyle.nodeY = pos.y; + rstyle.nodeW = ele.pstyle( 'width' ).pfValue; + rstyle.nodeH = ele.pstyle( 'height' ).pfValue; + } + this.recalculateEdgeProjections( edges ); - this.recalculateLabelProjections( nodes, edges ); // update edge data from projections for( var i = 0; i < edges.length; i++ ){ @@ -156,6 +161,8 @@ BRp.recalculateRenderedStyle = function( eles, useCache ){ var rstyle = _p.rstyle; var rs = _p.rscratch; + this.recalculateEdgeLabelProjections( ele ); + // update rstyle positions rstyle.srcX = rs.arrowStartX; rstyle.srcY = rs.arrowStartY; @@ -1164,16 +1171,6 @@ BRp.calculateLabelDimensions = function( ele, text, extraKey ){ return cache[ cacheKey ]; }; -BRp.recalculateLabelProjections = function( nodes, edges ){ - for( var i = 0; i < nodes.length; i++ ){ - this.recalculateNodeLabelProjection( nodes[ i ] ); - } - - for( var i = 0; i < edges.length; i++ ){ - this.recalculateEdgeLabelProjections( edges[ i ] ); - } -}; - BRp.recalculateEdgeProjections = function( edges ){ this.findEdgeControlPoints( edges ); };
Arrow positioned wrong when using label width and height #<I> Node label projections must forced to be calculated before edge projections, because the enqueued dirty elements might come in the wrong order.
cytoscape_cytoscape.js
train
bc12ba7e1f1f1cc1fc07887623ee2a1df5fdba1d
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -6,12 +6,12 @@ setup( package_data = { 'summa': ['README', 'LICENSE'] }, - version = '1.0.0', + version = '1.1.0', description = 'A text summarization and keyword extraction package based on TextRank', long_description = open('README', encoding="utf-8").read(), author = 'Federico Barrios, Federico Lopez', url = 'https://github.com/summanlp/textrank', - download_url = 'https://github.com/summanlp/textrank/tarball/v1.0.0', + download_url = 'https://github.com/summanlp/textrank/releases', keywords = ['summa', 'nlp', 'summarization', "NLP", "natural language processing", "automatic summarization",
<I> release (#<I>)
summanlp_textrank
train
8415f3d118bea99ab4bbdb417dfff33fa83af2f4
diff --git a/app/addons/databases/stores.js b/app/addons/databases/stores.js index <HASH>..<HASH> 100644 --- a/app/addons/databases/stores.js +++ b/app/addons/databases/stores.js @@ -89,7 +89,6 @@ define([ dispatch: function (action) { switch (action.type) { - case ActionTypes.DATABASES_INIT: this.init(action.options.collection, action.options.backboneCollection); this.setPage(action.options.page); @@ -112,10 +111,6 @@ define([ this.setLoading(false); break; - case ActionTypes.DATABASES_SHOWDELETE_MODAL: - this.setDeleteModal(action.options); - break; - default: return; }
Remove old code This just removes a clause in a store that references a deleted function. Caused errors with dash mocha tests.
apache_couchdb-fauxton
train
7aab2691c76ddc8f3a0b886e2a9ffacad948c89a
diff --git a/Gemfile.lock b/Gemfile.lock index <HASH>..<HASH> 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -3,6 +3,7 @@ PATH specs: magic_grid (0.0.1) rails (~> 3.1.1) + will_paginate (~> 3.0.0) GEM remote: http://rubygems.org/ @@ -40,9 +41,6 @@ GEM erubis (2.7.0) hike (1.2.1) i18n (0.6.0) - jquery-rails (1.0.16) - railties (~> 3.0) - thor (~> 0.14) json (1.6.1) mail (2.3.0) i18n (>= 0.4.0) @@ -89,11 +87,11 @@ GEM polyglot polyglot (>= 0.3.1) tzinfo (0.3.30) + will_paginate (3.0.2) PLATFORMS ruby DEPENDENCIES - jquery-rails magic_grid! sqlite3 diff --git a/lib/action_view/helpers/magic_grid_helper.rb b/lib/action_view/helpers/magic_grid_helper.rb index <HASH>..<HASH> 100644 --- a/lib/action_view/helpers/magic_grid_helper.rb +++ b/lib/action_view/helpers/magic_grid_helper.rb @@ -43,25 +43,26 @@ module ActionView Rails.logger.info("MagicGrid created!") end - def self.normalize(collection, columns = [], options = {}) - if collection.is_a? MagicGrid - collection - elsif columns.is_a? MagicGrid - columns - elsif options.is_a? MagicGrid - options - else - self.new(columns, collection, params, options) - end + end + + def normalize_magic(collection, columns = [], options = {}) + if collection.is_a? MagicGrid + collection + elsif columns.is_a? MagicGrid + columns + elsif options.is_a? MagicGrid + options + else + MagicGrid.new(columns, collection, params, options) end end def magic_collection(collection, cols, opts = {}) - MagicGrid.normalize(collection, cols, opts).collection + normalize_magic(collection, cols, opts).collection end def magic_grid(collection = nil, cols = nil, opts = {}, &block) - grid = MagicGrid.normalize(collection, cols, opts) + grid = normalize_magic(collection, cols, opts) content_tag 'table', :class => 'zebra wide thin-border ajaxed_pager', :id => "magic_#{grid.magic_id}" do table = content_tag 'thead' do thead = content_tag 'tr', :class => 'pagination' do @@ -78,7 +79,7 @@ module ActionView end def magic_headers(cols, collection = nil, opts = {}) - grid = MagicGrid.normalize(collection, cols, opts) + grid = normalize_magic(collection, cols, opts) headers = grid.columns.each_index.map do |i| if grid.columns[i].is_a? String "<th>#{grid.columns[i]}</th>" @@ -92,7 +93,7 @@ module ActionView end def magic_rows(cols, collection = nil) - grid = MagicGrid.normalize(collection, cols) + grid = normalize_magic(collection, cols) grid.collection.map do |row| if block_given? yield row @@ -104,7 +105,7 @@ module ActionView def magic_row(record, cols, collection = nil) cells = [] - grid = MagicGrid.normalize(collection, cols) + grid = normalize_magic(collection, cols) grid.columns.each do |c| method = c[:to_s] || c[:col] cells << (record.respond_to?(method) ? record.send(method).to_s : '') diff --git a/lib/magic_grid.rb b/lib/magic_grid.rb index <HASH>..<HASH> 100644 --- a/lib/magic_grid.rb +++ b/lib/magic_grid.rb @@ -1,2 +1,6 @@ +require 'action_view/helpers/magic_grid_helper' + module MagicGrid end + +ActionView::Helpers.send :include, ActionView::Helpers::MagicGridHelper
Autoload ourselves into ActionView::Helpers Kinda useless without it..
rmg_magic_grid
train
9f9b197fa077dabf5884242507f52528b99f1918
diff --git a/horizon/static/horizon/js/horizon.forms.js b/horizon/static/horizon/js/horizon.forms.js index <HASH>..<HASH> 100644 --- a/horizon/static/horizon/js/horizon.forms.js +++ b/horizon/static/horizon/js/horizon.forms.js @@ -223,7 +223,7 @@ horizon.addInitFunction(function () { /* Switchable Fields (See Horizon's Forms docs for more information) */ - // Bind handler for swapping labels on "switchable" fields. + // Bind handler for swapping labels on "switchable" select fields. $(document).on("change", 'select.switchable', function (evt) { var $fieldset = $(evt.target).closest('fieldset'), $switchables = $fieldset.find('.switchable'); @@ -258,6 +258,45 @@ horizon.addInitFunction(function () { $(modal).find('select.switchable').trigger('change'); }); + // Bind handler for swapping labels on "switchable" checkbox input fields. + $(document).on("change", 'input.switchable', function (evt) { + var $fieldset = $(evt.target).closest('fieldset'), + $switchables = $fieldset.find('input.switchable'); + + $switchables.each(function (index, switchable) { + var $switchable = $(switchable), + slug = $switchable.data('slug'), + checked = $switchable.prop('checked'); + + function handle_switched_field(index, input){ + var $input = $(input); + + if ( checked ) { + $input.closest('.form-group').show(); + // Add the required class to form group to show a (*) next to label + if ($input.data('is-required')) { + $input.closest('.form-group').addClass("required"); + } + } else { + $input.closest('.form-group').hide(); + if ($input.data('is-required')) { + $input.closest('.form-group').removeClass("required"); + } + } + } + + $fieldset.find('.switched[data-switch-on*="' + slug + '"]').each(handle_switched_field); + $fieldset.siblings().find('.switched[data-switch-on*="' + slug + '"]').each(handle_switched_field); + }); + }); + + // Fire off the change event to trigger the proper initial values. + $('input.switchable').trigger('change'); + // Queue up the for new modals, too. + horizon.modals.addModalInitFunction(function (modal) { + $(modal).find('input.switchable').trigger('change'); + }); + // Handle field toggles for the Create Volume source type field function update_volume_source_displayed_fields (field) { var $this = $(field), diff --git a/openstack_dashboard/dashboards/project/networks/workflows.py b/openstack_dashboard/dashboards/project/networks/workflows.py index <HASH>..<HASH> 100644 --- a/openstack_dashboard/dashboards/project/networks/workflows.py +++ b/openstack_dashboard/dashboards/project/networks/workflows.py @@ -84,25 +84,44 @@ class CreateNetworkInfo(workflows.Step): class CreateSubnetInfoAction(workflows.Action): with_subnet = forms.BooleanField(label=_("Create Subnet"), - initial=True, required=False) + widget=forms.CheckboxInput(attrs={ + 'class': 'switchable', + 'data-slug': 'with_subnet', + }), + initial=True, + required=False) subnet_name = forms.CharField(max_length=255, + widget=forms.TextInput(attrs={ + 'class': 'switched', + 'data-switch-on': 'with_subnet', + }), label=_("Subnet Name"), required=False) cidr = forms.IPField(label=_("Network Address"), - required=False, - initial="", - help_text=_("Network address in CIDR format " - "(e.g. 192.168.0.0/24, 2001:DB8::/48)"), - version=forms.IPv4 | forms.IPv6, - mask=True) + required=False, + initial="", + widget=forms.TextInput(attrs={ + 'class': 'switched', + 'data-switch-on': 'with_subnet', + 'data-is-required': 'true' + }), + help_text=_("Network address in CIDR format " + "(e.g. 192.168.0.0/24, 2001:DB8::/48)"), + version=forms.IPv4 | forms.IPv6, + mask=True) ip_version = forms.ChoiceField(choices=[(4, 'IPv4'), (6, 'IPv6')], widget=forms.Select(attrs={ - 'class': 'switchable', + 'class': 'switchable switched', 'data-slug': 'ipversion', + 'data-switch-on': 'with_subnet', }), label=_("IP Version")) gateway_ip = forms.IPField( label=_("Gateway IP"), + widget=forms.TextInput(attrs={ + 'class': 'switched', + 'data-switch-on': 'with_subnet', + }), required=False, initial="", help_text=_("IP address of Gateway (e.g. 192.168.0.254) " @@ -116,6 +135,10 @@ class CreateSubnetInfoAction(workflows.Action): version=forms.IPv4 | forms.IPv6, mask=False) no_gateway = forms.BooleanField(label=_("Disable Gateway"), + widget=forms.CheckboxInput(attrs={ + 'class': 'switched', + 'data-switch-on': 'with_subnet', + }), initial=False, required=False) class Meta:
Style network address for subnet as required field It does this by adding the required class to the network address field when the checkbox is enabled. I have also made the checkbox behave like a switchable select so when the create subnet checkbox is checked all fields are visible. There are hidden when create subnet is unselected. Change-Id: Id<I>d5ce2a1bb<I>e4bcaa<I>df<I>ca2b1ccee3c7e Closes-bug: <I>
openstack_horizon
train
b62a32f990646a2231677dd8ce3722954f817856
diff --git a/public/src/Conn/Delete.php b/public/src/Conn/Delete.php index <HASH>..<HASH> 100644 --- a/public/src/Conn/Delete.php +++ b/public/src/Conn/Delete.php @@ -114,6 +114,19 @@ class Delete extends Conn $this->delete->execute($this->places); $this->result = true; $result = (is_array($this->resultsUpdates) ? (!empty($this->resultsUpdates[0]) ? $this->resultsUpdates[0] : $this->resultsUpdates) : []); + + /** + * Delete caches IDs + */ + $idList = ""; + foreach ($this->resultsUpdates as $resultsUpdate) + $idList .= (!empty($idList) ? ", " : "") . $resultsUpdate['id']; + + if(!empty($idList)) { + $sql = new SqlCommand(!0); + $sql->exeCommand("DELETE FROM " . str_replace(PRE, PRE . "wcache_", $this->tabela) . " WHERE id IN (" . $idList . ")"); + } + $this->react = new React("delete", str_replace(PRE, '', $this->tabela), $result, $result); } catch (\PDOException $e) { $this->result = null; diff --git a/public/src/Conn/Update.php b/public/src/Conn/Update.php index <HASH>..<HASH> 100644 --- a/public/src/Conn/Update.php +++ b/public/src/Conn/Update.php @@ -153,6 +153,18 @@ class Update extends Conn $this->result = true; /** + * Delete caches IDs + */ + $idList = ""; + foreach ($this->resultsUpdates as $resultsUpdate) + $idList .= (!empty($idList) ? ", " : "") . $resultsUpdate['id']; + + if(!empty($idList)) { + $sql = new SqlCommand(!0); + $sql->exeCommand("DELETE FROM " . str_replace(PRE, PRE . "wcache_", $this->tabela) . " WHERE id IN (" . $idList . ")"); + } + + /** * Garante que todos os campos estejam presentes nos dados */ foreach ($this->resultsUpdates[0] as $col => $value) {
delete and update clear wcache DB
edineibauer_uebConn
train
e01b5fbe821f1bd300cfbff4bda6f4525ce0e095
diff --git a/Exedra/Container/Container.php b/Exedra/Container/Container.php index <HASH>..<HASH> 100644 --- a/Exedra/Container/Container.php +++ b/Exedra/Container/Container.php @@ -33,12 +33,12 @@ class Container implements \ArrayAccess /** * registry exist check - * @param string $type + * @param string $name * @return bool */ - public function offsetExists($type) + public function offsetExists($name) { - return isset($this->services[$type]); + return isset($this->services[$name]) || $this->services['service']->has($name); } /** @@ -194,7 +194,7 @@ class Container implements \ArrayAccess */ public function __isset($name) { - return $this->services['service']->has($name); + return $this->offsetExists($name); } /** diff --git a/Exedra/Runtime/Context.php b/Exedra/Runtime/Context.php index <HASH>..<HASH> 100644 --- a/Exedra/Runtime/Context.php +++ b/Exedra/Runtime/Context.php @@ -126,6 +126,17 @@ class Context extends Container } /** + * Override main and check the app instance + * + * @param string $name + * @return bool + */ + public function offsetExists($name) + { + return parent::offsetExists($name) || $this->app->offsetExists('@' . $name); + } + + /** * Get application instance * @return \Exedra\Application */
isset check on Context now should check @ on app too
Rosengate_exedra
train
ed6ae9ded33f32da768f65318599161675fa3391
diff --git a/fastlane_core/lib/fastlane_core/ui/implementations/shell.rb b/fastlane_core/lib/fastlane_core/ui/implementations/shell.rb index <HASH>..<HASH> 100644 --- a/fastlane_core/lib/fastlane_core/ui/implementations/shell.rb +++ b/fastlane_core/lib/fastlane_core/ui/implementations/shell.rb @@ -60,7 +60,7 @@ module FastlaneCore end def command(message) - log.info("$ #{message}".cyan.underline) + log.info("$ #{message}".cyan) end def command_output(message)
Don't underline printed commands (#<I>) Fixes <URL>
fastlane_fastlane
train
167d39049e2d49fc88fe8986f46f6ed5cfe0de11
diff --git a/Classes/Domain/Model/Changes/AbstractCopy.php b/Classes/Domain/Model/Changes/AbstractCopy.php index <HASH>..<HASH> 100644 --- a/Classes/Domain/Model/Changes/AbstractCopy.php +++ b/Classes/Domain/Model/Changes/AbstractCopy.php @@ -27,11 +27,12 @@ abstract class AbstractCopy extends AbstractStructuralChange * Generate a unique node name for the copied node * * @param NodeInterface $parentNode + * @param bool $forceRegeneration * @return string */ - protected function generateUniqueNodeName(NodeInterface $parentNode) + protected function generateUniqueNodeName(NodeInterface $parentNode, $forceRegeneration = false) { return $this->contentRepositoryNodeService - ->generateUniqueNodeName($parentNode->getPath(), $this->getSubject()->getName()); + ->generateUniqueNodeName($parentNode->getPath(), $forceRegeneration ? null : $this->getSubject()->getName()); } } diff --git a/Classes/Domain/Model/Changes/CopyAfter.php b/Classes/Domain/Model/Changes/CopyAfter.php index <HASH>..<HASH> 100644 --- a/Classes/Domain/Model/Changes/CopyAfter.php +++ b/Classes/Domain/Model/Changes/CopyAfter.php @@ -39,7 +39,7 @@ class CopyAfter extends AbstractCopy public function apply() { if ($this->canApply()) { - $nodeName = $this->generateUniqueNodeName($this->getSiblingNode()->getParent()); + $nodeName = $this->generateUniqueNodeName($this->getSiblingNode()->getParent(), true); $node = $this->getSubject()->copyAfter($this->getSiblingNode(), $nodeName); $this->finish($node); } diff --git a/Classes/Domain/Model/Changes/CopyBefore.php b/Classes/Domain/Model/Changes/CopyBefore.php index <HASH>..<HASH> 100644 --- a/Classes/Domain/Model/Changes/CopyBefore.php +++ b/Classes/Domain/Model/Changes/CopyBefore.php @@ -38,7 +38,7 @@ class CopyBefore extends AbstractCopy public function apply() { if ($this->canApply()) { - $nodeName = $this->generateUniqueNodeName($this->getSiblingNode()->getParent()); + $nodeName = $this->generateUniqueNodeName($this->getSiblingNode()->getParent(), true); $node = $this->getSubject()->copyBefore($this->getSiblingNode(), $nodeName); $this->finish($node); } diff --git a/Classes/Domain/Model/Changes/CopyInto.php b/Classes/Domain/Model/Changes/CopyInto.php index <HASH>..<HASH> 100644 --- a/Classes/Domain/Model/Changes/CopyInto.php +++ b/Classes/Domain/Model/Changes/CopyInto.php @@ -74,7 +74,7 @@ class CopyInto extends AbstractCopy public function apply() { if ($this->canApply()) { - $nodeName = $this->generateUniqueNodeName($this->getParentNode()); + $nodeName = $this->generateUniqueNodeName($this->getParentNode(), true); $node = $this->getSubject()->copyInto($this->getParentNode(), $nodeName); $this->finish($node); }
BUGFIX: Force re generation of copied node names Fixes: #<I>
neos_neos-ui
train
48973d89e8d6e1099acf92e3b597747e32cec378
diff --git a/server/index.js b/server/index.js index <HASH>..<HASH> 100644 --- a/server/index.js +++ b/server/index.js @@ -34,7 +34,9 @@ swaggerTools.initializeMiddleware(api, function(middleware) { useStubs: false })); app.use(middleware.swaggerUi({ - swaggerUi: '/api/docs' + apiDocs: '/api/docs/api.json', + swaggerUi: '/api/docs', + swaggerUiDir: './docs' })); app.get('/', function(req, res) {
point server at custom swagger ui for docs
adafruit_adafruit-io-node
train
dfc7a11705302e6b063174182757d7593a5d8e65
diff --git a/atomicpuppy/atomicpuppy.py b/atomicpuppy/atomicpuppy.py index <HASH>..<HASH> 100644 --- a/atomicpuppy/atomicpuppy.py +++ b/atomicpuppy/atomicpuppy.py @@ -165,21 +165,26 @@ class StreamReader: @asyncio.coroutine def _walk_from_last(self, prev_uri): - self.logger.debug("walking backwards from %s", prev_uri) - r = yield from self._fetcher.fetch(prev_uri) - js = yield from r.json() - if(js["entries"]): - self.logger.debug("raising events from page %s", prev_uri) - yield from self._raise_page_events(js) - prev = self._get_link(js, "previous") - if(prev): - self.logger.debug("Continuing to previous page %s", prev) - yield from self._walk_from_last(prev) - else: - self.logger.debug( - "back-walk completed, new polling uri is %s", - prev_uri) - self._subscriptions.update_uri(self._stream, prev_uri) + uri = prev_uri + while True: + self.logger.debug("walking backwards from %s", uri) + r = yield from self._fetcher.fetch(uri) + js = yield from r.json() + if(js["entries"]): + self.logger.debug("raising events from page %s", uri) + yield from self._raise_page_events(js) + prev_uri = self._get_link(js, "previous") + if not prev_uri: + # loop until there's a prev link, otherwise it means + # we are at the end or we are fetching an empty page + self.logger.debug( + "back-walk completed, new polling uri is %s", + uri) + self._subscriptions.update_uri(self._stream, uri) + break + + self.logger.debug("Continuing to previous page %s", prev_uri) + uri = prev_uri @asyncio.coroutine def _raise_page_events(self, js):
Remove recursion when walking pages If there are more than <I> pages we hit the Python default recursion depth limit and the StreamFetcher dies with an exception
madedotcom_atomicpuppy
train
e6fdf4b8cb5d951443a560463927840a2c555a7d
diff --git a/graylog2-server/src/main/java/org/graylog2/inputs/InputEventListener.java b/graylog2-server/src/main/java/org/graylog2/inputs/InputEventListener.java index <HASH>..<HASH> 100644 --- a/graylog2-server/src/main/java/org/graylog2/inputs/InputEventListener.java +++ b/graylog2-server/src/main/java/org/graylog2/inputs/InputEventListener.java @@ -58,7 +58,7 @@ public class InputEventListener { } @Subscribe public void inputCreated(InputCreated inputCreatedEvent) { - LOG.info("Input created: " + inputCreatedEvent.id()); + LOG.debug("Input created/changed: " + inputCreatedEvent.id()); final Input input; try { input = inputService.find(inputCreatedEvent.id()); @@ -88,7 +88,7 @@ public class InputEventListener { } @Subscribe public void inputDeleted(InputDeleted inputDeletedEvent) { - LOG.info("Input deleted: " + inputDeletedEvent.id()); + LOG.debug("Input deleted: " + inputDeletedEvent.id()); final IOState<MessageInput> inputState = inputRegistry.getInputState(inputDeletedEvent.id()); if (inputState != null) { inputRegistry.remove(inputState);
Chane log levels and wording of debug logging.
Graylog2_graylog2-server
train
728364accfb93cd52003fb38a6412c8e4965116b
diff --git a/server.go b/server.go index <HASH>..<HASH> 100644 --- a/server.go +++ b/server.go @@ -1590,7 +1590,7 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str trInfo.tr.SetError() } errDesc := fmt.Sprintf("malformed method name: %q", stream.Method()) - if err := t.WriteStatus(stream, status.New(codes.ResourceExhausted, errDesc)); err != nil { + if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { if trInfo != nil { trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) trInfo.tr.SetError() diff --git a/test/end2end_test.go b/test/end2end_test.go index <HASH>..<HASH> 100644 --- a/test/end2end_test.go +++ b/test/end2end_test.go @@ -6347,6 +6347,23 @@ func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) { } } +// TestMalformedStreamMethod starts a test server and sends an RPC with a +// malformed method name. The server should respond with an UNIMPLEMENTED status +// code in this case. +func (s) TestMalformedStreamMethod(t *testing.T) { + const testMethod = "a-method-name-without-any-slashes" + te := newTest(t, tcpClearRREnv) + te.startServer(nil) + defer te.tearDown() + + ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout) + defer cancel() + err := te.clientConn().Invoke(ctx, testMethod, nil, nil) + if gotCode := status.Code(err); gotCode != codes.Unimplemented { + t.Fatalf("Invoke with method %q, got code %s, want %s", testMethod, gotCode, codes.Unimplemented) + } +} + func (s) TestMethodFromServerStream(t *testing.T) { const testMethod = "/package.service/method" e := tcpClearRREnv
server: return UNIMPLEMENTED on receipt of malformed method name (#<I>)
grpc_grpc-go
train
db445b5352db7dd320fa093d911ad5c96e89771c
diff --git a/lib/httplog/http_log.rb b/lib/httplog/http_log.rb index <HASH>..<HASH> 100644 --- a/lib/httplog/http_log.rb +++ b/lib/httplog/http_log.rb @@ -18,7 +18,9 @@ module HttpLog :compact_log => false, :url_whitelist_pattern => /.*/, :url_blacklist_pattern => nil, - :color => false + :color => false, + :prefix_response_lines => false, + :prefix_line_numbers => false } LOG_PREFIX = "[httplog] ".freeze @@ -99,7 +101,19 @@ module HttpLog data = utf_encoded(body.to_s, content_type) - log("Response:\n#{data}") + if options[:prefix_response_lines] + log("Response:") + data.each_line.with_index do |line, row| + if options[:prefix_line_numbers] + log("#{row + 1}: #{line.strip}") + else + log(line.strip) + end + end + else + log("Response:\n#{data}") + end + end def log_data(data) @@ -134,5 +148,6 @@ module HttpLog content_type =~ /^text/ || content_type =~ /^application/ && content_type != 'application/octet-stream' end + end end diff --git a/spec/http_log_spec.rb b/spec/http_log_spec.rb index <HASH>..<HASH> 100644 --- a/spec/http_log_spec.rb +++ b/spec/http_log_spec.rb @@ -208,6 +208,23 @@ describe HttpLog do expect(log).to_not include(HttpLog::LOG_PREFIX + "Reponse:") end + it "should prefix all response lines" do + HttpLog.options[:prefix_response_lines] = true + + adapter.send_post_request + expect(log).to include(HttpLog::LOG_PREFIX + "Response:") + expect(log).to include(HttpLog::LOG_PREFIX + "<html>") + end + + it "should prefix all response lines with line numbers" do + HttpLog.options[:prefix_response_lines] = true + HttpLog.options[:prefix_line_numbers] = true + + adapter.send_post_request + expect(log).to include(HttpLog::LOG_PREFIX + "Response:") + expect(log).to include(HttpLog::LOG_PREFIX + "1: <html>") + end + it "should not log the benchmark if disabled" do HttpLog.options[:log_benchmark] = false adapter.send_post_request
Add prefix in all lines of the response body including (optionally) the line number
trusche_httplog
train
ba8904c71357ddda0e18d95f3184307cd52be710
diff --git a/lib/mixlib/log.rb b/lib/mixlib/log.rb index <HASH>..<HASH> 100644 --- a/lib/mixlib/log.rb +++ b/lib/mixlib/log.rb @@ -190,6 +190,7 @@ module Mixlib # via public API. In order to reduce amount of impact and # handle only File type log devices I had to use this method # to get access to it. + next unless logger.instance_variable_defined?(:"@logdev") next unless (logdev = logger.instance_variable_get(:"@logdev")) loggers_to_close << logger if logdev.filename end
Check for the existence of the ivar before accessing it. Makes the code run nearly warning free, reducing the output of `rspec -w spec` by <I> lines. That has to mean something, right?
chef_mixlib-log
train
1cefc4ddc6c3fa7d92a12f5ca58c498e187d5bdd
diff --git a/core-bundle/src/Controller/BackendController.php b/core-bundle/src/Controller/BackendController.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/Controller/BackendController.php +++ b/core-bundle/src/Controller/BackendController.php @@ -60,7 +60,7 @@ class BackendController extends Controller $this->container->get('contao.framework')->initialize(); if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) { - return new RedirectResponse($this->container->get('security.logout_url_generator')->getLogoutUrl()); + return new RedirectResponse($this->container->get('router')->generate('contao_backend')); } $controller = new BackendIndex();
[Core] Redirect to the back end if a user is fully authenticated upon login.
contao_contao
train
2a99605f28f095e10406bd281e3d820e616ee100
diff --git a/rebulk/__version__.py b/rebulk/__version__.py index <HASH>..<HASH> 100644 --- a/rebulk/__version__.py +++ b/rebulk/__version__.py @@ -4,4 +4,4 @@ Version module """ # pragma: no cover -__version__ = '1.0.1.dev0' +__version__ = '1.0.1'
Preparing release <I>
Toilal_rebulk
train
dcc540ec33e683c8bb2aecccd62ccfdd73df0391
diff --git a/spec/test_myrrha.rb b/spec/test_myrrha.rb index <HASH>..<HASH> 100644 --- a/spec/test_myrrha.rb +++ b/spec/test_myrrha.rb @@ -21,7 +21,7 @@ describe Myrrha do }.should raise_error(Myrrha::Error, "Unable to coerce `true` to Integer") lambda{ graph.coerce("12.2", Integer) - }.should raise_error(Myrrha::Error, "Unable to coerce `12.2` to Integer (invalid value for Integer: \"12.2\")") + }.should raise_error(Myrrha::Error, /^Unable to coerce `12.2` to Integer \(invalid value /) end it "should support all-catching rules" do
Fixed a failing test under <I>
blambeau_myrrha
train
d3fdc3680da94482d94bf4bac4403073661a80c1
diff --git a/Lib/Filter/ImportInline.php b/Lib/Filter/ImportInline.php index <HASH>..<HASH> 100644 --- a/Lib/Filter/ImportInline.php +++ b/Lib/Filter/ImportInline.php @@ -18,7 +18,7 @@ class ImportInline extends AssetFilter { public function settings($settings) { parent::settings($settings); - $this->_Scanner = new AssetScanner($settings['paths']); + $this->_Scanner = new AssetScanner($settings['paths'], Hash::get($settings, 'theme')); } /**
Make import inline use theme setting. Allows importing files with theme syntax (plugin syntax already works): @import url('theme:css/accordion.css');
markstory_asset_compress
train
a2bae70d50add7b425a2b664dc4539624db86b0c
diff --git a/pubsub/pubsub.go b/pubsub/pubsub.go index <HASH>..<HASH> 100644 --- a/pubsub/pubsub.go +++ b/pubsub/pubsub.go @@ -14,9 +14,8 @@ type PubSub struct { Stats } -func (pubsub *PubSub) Publish(i interface{}) error { +func (pubsub *PubSub) Publish(i interface{}) (e error) { pubsub.Stats.MessageReceived() - var e error value := reflect.ValueOf(i) for _, s := range pubsub.subscriptions { if !s.closed && s.Matches(value) { @@ -24,7 +23,8 @@ func (pubsub *PubSub) Publish(i interface{}) error { case s.buffer <- value: pubsub.Stats.MessageDispatched() default: - e = fmt.Errorf("unable to publish to %v", s) + pubsub.Stats.MessageIgnored() + e = fmt.Errorf("unable to publish (subscriber buffer full) to %+v", s) } } } diff --git a/pubsub/stats.go b/pubsub/stats.go index <HASH>..<HASH> 100644 --- a/pubsub/stats.go +++ b/pubsub/stats.go @@ -6,6 +6,8 @@ type Stats struct { dispatchedChan chan interface{} dispatched int64 collecting bool + ignored int64 + ignoredChan chan interface{} } func (stats *Stats) Dispatched() int64 { @@ -16,6 +18,10 @@ func (stats *Stats) Received() int64 { return stats.received } +func (stats *Stats) Ignored() int64 { + return stats.ignored +} + func (stats *Stats) MessageDispatched() { stats.StartCollecting() stats.dispatchedChan <- nil @@ -27,6 +33,7 @@ func (stats *Stats) StartCollecting() { } stats.dispatchedChan = make(chan interface{}, 1000) stats.receivedChan = make(chan interface{}, 1000) + stats.ignoredChan = make(chan interface{}, 1000) go func() { for { select { @@ -34,6 +41,8 @@ func (stats *Stats) StartCollecting() { stats.received++ case <-stats.dispatchedChan: stats.dispatched++ + case <-stats.ignoredChan: + stats.ignored++ } } }() @@ -45,3 +54,7 @@ func (stats *Stats) MessageReceived() { stats.receivedChan <- nil } +func (stats *Stats) MessageIgnored() { + stats.StartCollecting() + stats.ignoredChan <- nil +}
added stats for ignored messages Messages are ignored when the subscribers buffer is full. Those messages are now counted so that the receiving party can verify whether there might be a problem.
dynport_dgtk
train
064672b2f797a3d36848c3b137ec89a9e8fdf1cf
diff --git a/matplotlib2tikz/save.py b/matplotlib2tikz/save.py index <HASH>..<HASH> 100644 --- a/matplotlib2tikz/save.py +++ b/matplotlib2tikz/save.py @@ -208,7 +208,8 @@ def _print_pgfplot_libs_message(data): print('=========================================================') print('Please add the following lines to your LaTeX preamble:\n') print('\\usepackage[utf8]{inputenc}') - print('\\usepackage{fontspec}') + print('\\usepackage{fontspec}', + '% This Line only for XeLaTeX and LuaLaTeX') print('\\usepackage{pgfplots}') if tikzlibs: print('\\usetikzlibrary{' + tikzlibs + '}')
fontspec is XeLaTeX and LuaLaTeX specific The hint to add \usepackage{fontspec} to the LaTeX code is only recommented for XeLaTeX and LuaLaTeX
nschloe_matplotlib2tikz
train
52a082a4413e3e2cefb32e5dd5045f59962814c0
diff --git a/lib/terraforming/resource/route_table_association.rb b/lib/terraforming/resource/route_table_association.rb index <HASH>..<HASH> 100644 --- a/lib/terraforming/resource/route_table_association.rb +++ b/lib/terraforming/resource/route_table_association.rb @@ -23,11 +23,15 @@ module Terraforming resources = {} route_tables.each do |route_table| associations_of(route_table).each do |assoc| + # Skip implicit associations + next unless assoc.subnet_id + attributes = { "id" => assoc.route_table_association_id, "route_table_id" => assoc.route_table_id, "subnet_id" => assoc.subnet_id, } + resources["aws_route_table_association.#{module_name_of(route_table, assoc)}"] = { "type" => "aws_route_table_association", "primary" => { diff --git a/spec/lib/terraforming/resource/route_table_association_spec.rb b/spec/lib/terraforming/resource/route_table_association_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/terraforming/resource/route_table_association_spec.rb +++ b/spec/lib/terraforming/resource/route_table_association_spec.rb @@ -66,6 +66,12 @@ module Terraforming route_table_id: 'rtb-a12bcd34', subnet_id: 'subnet-8901b123', main: false + }, + { + route_table_association_id: 'rtbassoc-e71201aaa', + route_table_id: 'rtb-a12bcd34', + subnet_id: nil, + main: true } ], tags: [
Skip implicit route table associations when generating tfstate
dtan4_terraforming
train
f8e82fabed9c82ff5f8400af665045d0cef8f43e
diff --git a/lib/internal/backend/repository/repository2.go b/lib/internal/backend/repository/repository2.go index <HASH>..<HASH> 100644 --- a/lib/internal/backend/repository/repository2.go +++ b/lib/internal/backend/repository/repository2.go @@ -345,7 +345,7 @@ func (rb *RepositoryBackend) getManifestV21(dockerURL *types.ParsedDockerURL, re layers := make([]string, len(manifest.FSLayers)) for i, layer := range manifest.FSLayers { - rb.reverseLayers[layer.BlobSum] = i + rb.reverseLayers[layer.BlobSum] = len(manifest.FSLayers) - 1 - i layers[i] = layer.BlobSum }
repository2: populate reverseLayers correctly In da<I>c<I>f we introduced an optimization to avoid going through all the layers every time we need the index of a specific one. However, when we set the layer index, we weren't setting the reversed index, like we were doing before the optimization. Fix it by setting the correct index.
appc_docker2aci
train
14bd9814240bbfbf8eab6afff407da39f9bc9700
diff --git a/hazelcast/src/main/java/com/hazelcast/logging/Logger.java b/hazelcast/src/main/java/com/hazelcast/logging/Logger.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/logging/Logger.java +++ b/hazelcast/src/main/java/com/hazelcast/logging/Logger.java @@ -44,9 +44,9 @@ public final class Logger { */ public static ILogger getLogger(String name) { LoggerFactory loggerFactoryToUse = loggerFactory; - //fast-track when factory is initialized - if (loggerFactory != null) { - return loggerFactory.getLogger(name); + // fast-track when factory is initialized + if (loggerFactoryToUse != null) { + return loggerFactoryToUse.getLogger(name); } synchronized (FACTORY_LOCK) { @@ -54,19 +54,20 @@ public final class Logger { // init static logger with user-specified custom logger class String loggerClass = System.getProperty("hazelcast.logging.class"); if (!StringUtil.isNullOrEmpty(loggerClass)) { - loggerFactory = loadLoggerFactory(loggerClass); - loggerFactoryToUse = loggerFactory; - } - } - if (loggerFactory == null) { - String loggerType = System.getProperty("hazelcast.logging.type"); - loggerFactoryToUse = newLoggerFactory(loggerType); - if (!StringUtil.isNullOrEmpty(loggerType)) { + //ok, there is a custom logging factory class -> let's use it now and store it for next time + loggerFactoryToUse = loadLoggerFactory(loggerClass); loggerFactory = loggerFactoryToUse; + } else { + String loggerType = System.getProperty("hazelcast.logging.type"); + loggerFactoryToUse = newLoggerFactory(loggerType); + //store the factory only when the type was set explicitly. we do not want to store default type. + if (!StringUtil.isNullOrEmpty(loggerType)) { + loggerFactory = loggerFactoryToUse; + } } } } - //loggerFactory was initialized -> loggerFactoryToUse was left to null + //loggerFactory was initialized by other thread before we acquired the lock->loggerFactoryToUse was left to null if (loggerFactoryToUse == null) { loggerFactoryToUse = loggerFactory; }
Logger.getLogger() - minor refactoring
hazelcast_hazelcast
train
9ae7562f92f13aceda2b5c0389dd37955ca9e066
diff --git a/astroid/bases.py b/astroid/bases.py index <HASH>..<HASH> 100644 --- a/astroid/bases.py +++ b/astroid/bases.py @@ -541,15 +541,20 @@ class NodeNG(object): string = '%(cname)s(%(fields)s)' alignment = len(cname) + 1 result = [] - for a in self._other_fields + self._astroid_fields: - lines = pprint.pformat(getattr(self, a), indent=2, - width=80-len(a)-alignment).splitlines(True) + for field in self._other_fields + self._astroid_fields: + value = getattr(self, field) + width = 80 - len(field) - alignment + lines = pprint.pformat(value, indent=2, + width=width).splitlines(True) + inner = [lines[0]] - for l in lines[1:]: - inner.append(' '*alignment + l) - result.append('%s=%s' % (a, ''.join(inner))) - return string % {'cname': cname, 'rname': rname, - 'fields': (',\n' + ' '*alignment).join(result)} + for line in lines[1:]: + inner.append(' ' * alignment + line) + result.append('%s=%s' % (field, ''.join(inner))) + + return string % {'cname': cname, + 'rname': rname, + 'fields': (',\n' + ' ' * alignment).join(result)} def __repr__(self): rname = self._repr_name() @@ -557,8 +562,10 @@ class NodeNG(object): string = '<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>' else: string = '<%(cname)s l.%(lineno)s at 0x%(id)x>' - return string % {'cname': type(self).__name__, 'rname': rname, - 'lineno': self.fromlineno, 'id': id(self)} + return string % {'cname': type(self).__name__, + 'rname': rname, + 'lineno': self.fromlineno, + 'id': id(self)} def accept(self, visitor): func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) @@ -800,28 +807,23 @@ class NodeNG(object): default is 80. Attempts to format the output string to stay within max_width characters, but can exceed it under some circumstances. - """ @_singledispatch def _repr_tree(node, result, done, cur_indent='', depth=1): - '''Outputs a representation of a non-tuple/list, non-node that's + """Outputs a representation of a non-tuple/list, non-node that's contained within an AST, including strings. - - ''' + """ lines = pprint.pformat(node, width=max(max_width - len(cur_indent), 1)).splitlines(True) result.append(lines[0]) - result.extend([cur_indent + l for l in lines[1:]]) - return False if len(lines) == 1 else True + result.extend([cur_indent + line for line in lines[1:]]) + return len(lines) != 1 @_repr_tree.register(tuple) @_repr_tree.register(list) def _repr_seq(node, result, done, cur_indent='', depth=1): - '''Outputs a representation of a sequence that's contained within an - AST. - - ''' + """Outputs a representation of a sequence that's contained within an AST.""" cur_indent += indent result.append('[') if len(node) == 0: @@ -851,7 +853,7 @@ class NodeNG(object): @_repr_tree.register(NodeNG) def _repr_node(node, result, done, cur_indent='', depth=1): - '''Outputs a strings representation of an astroid node.''' + """Outputs a strings representation of an astroid node.""" if node in done: result.append(indent + '<Recursion on %s with id=%s' % (type(node).__name__, id(node))) diff --git a/astroid/context.py b/astroid/context.py index <HASH>..<HASH> 100644 --- a/astroid/context.py +++ b/astroid/context.py @@ -62,14 +62,16 @@ class InferenceContext(object): self.path = path def __str__(self): - return '%s(%s)' % (type(self).__name__, ',\n '.join( - ('%s=%s' % (a, pprint.pformat(getattr(self, a), width=80-len(a))) - for a in self.__slots__))) + state = ('%s=%s' % (field, pprint.pformat(getattr(self, field), + width=80 - len(field))) + for field in self.__slots__) + return '%s(%s)' % (type(self).__name__, ',\n '.join(state)) def __repr__(self): - return '%s(%s)' % (type(self).__name__, ', '.join( - ('%s=%s' % (a, repr(getattr(self, a))) - for a in self.__slots__))) + state = ('%s=%s' % (field, repr(getattr(self, field))) + for field in self.__slots__) + return '%s(%s)' % (type(self).__name__, ', '.join(state)) + class CallContext(object):
Change a couple of readability issues, proper variable names and so on.
PyCQA_astroid
train
f060662c4245cdf7a7a5e17e27be802f5cf93747
diff --git a/core/core_test.go b/core/core_test.go index <HASH>..<HASH> 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -20,12 +20,9 @@ func launchSwarm(nodeCount int, t *testing.T) []*server { var wg sync.WaitGroup wg.Add(nodeCount) + var peers []string for i := 0; i < nodeCount; i++ { port := port + i - var peers []string - if i > 0 { - peers = append(peers, fmt.Sprintf("localhost:%d", nodes[i-1].network.Port)) - } s, err := newServer(port, peers, diskAllocated) if err != nil { t.Error(err) @@ -36,6 +33,7 @@ func launchSwarm(nodeCount int, t *testing.T) []*server { t.Log(err) } }() + peers = append(peers, fmt.Sprintf("localhost:%d", s.network.Port)) nodes = append(nodes, s) time.Sleep(20 * time.Millisecond) }
Hopefully fixed core network connection tests when running on non externally routable box
degdb_degdb
train
17fbfacdce8e6dc0391d45edadabb26cb237d82a
diff --git a/fontbakery-check-ttf.py b/fontbakery-check-ttf.py index <HASH>..<HASH> 100755 --- a/fontbakery-check-ttf.py +++ b/fontbakery-check-ttf.py @@ -598,24 +598,25 @@ def main(): logging.warning(msg) #---------------------------------------------------- - logging.debug("substitute copyright, registered and trademark symbols in name table entries") - new_names = [] - nametable_updated = False - replacement_map = [(u"\u00a9", '(c)'), (u"\u00ae", '(r)'), (u"\u2122", '(tm)')] - for name in font['name'].names: - new_name = name - original = name.string - string = name.string - for mark, ascii_repl in replacement_map: - string = string.replace(mark, ascii_repl) - new_name.string = string.encode(name.getEncoding()) - if string != original: - logging.error("HOTFIXED: Name entry fixed to '{}'.".format(string)) - nametable_updated = True - new_names.append(new_name) - if nametable_updated: - logging.error("HOTFIXED: Name table entries were modified to replace unicode symbols such as (c), (r) and TM.") - font['name'].names = new_names +#TODO: Fix this! See issue: https://github.com/googlefonts/fontbakery/issues/789 +# logging.debug("substitute copyright, registered and trademark symbols in name table entries") +# new_names = [] +# nametable_updated = False +# replacement_map = [(u"\u00a9", '(c)'), (u"\u00ae", '(r)'), (u"\u2122", '(tm)')] +# for name in font['name'].names: +# new_name = name +# original = name.string +# string = name.string +# for mark, ascii_repl in replacement_map: +# string = string.replace(mark, ascii_repl) +# new_name.string = string.encode(name.getEncoding()) +# if string != original: +# logging.error("HOTFIXED: Name entry fixed to '{}'.".format(string)) +# nametable_updated = True +# new_names.append(new_name) +# if nametable_updated: +# logging.error("HOTFIXED: Name table entries were modified to replace unicode symbols such as (c), (r) and TM.") +# font['name'].names = new_names #---------------------------------------------------- file_path, filename = os.path.split(font_file)
Temporarily disabling a broken test, so that the tool can be used. I'll then address the issue, as described at <URL>
googlefonts_fontbakery
train
f08d92cdba7b739e4cb7ad0e9bf14de877ed76df
diff --git a/http/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/WebSocketSourceHandler.java b/http/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/WebSocketSourceHandler.java index <HASH>..<HASH> 100644 --- a/http/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/WebSocketSourceHandler.java +++ b/http/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/WebSocketSourceHandler.java @@ -133,7 +133,7 @@ public class WebSocketSourceHandler extends SourceHandler { .getMessageProcessor(); if (carbonMessageProcessor != null) { try { - carbonMessageProcessor.receive(cMsg, new ResponseCallback(this.ctx)); + carbonMessageProcessor.receive(cMsg, null); } catch (Exception e) { logger.error("Error while submitting CarbonMessage to CarbonMessageProcessor.", e); ctx.channel().close();
Merged new changes and resolved conflicts.
wso2_transport-http
train
5d626163bbfb1254effbd15a52458c64eaf73c94
diff --git a/src/discoursegraphs/merging.py b/src/discoursegraphs/merging.py index <HASH>..<HASH> 100755 --- a/src/discoursegraphs/merging.py +++ b/src/discoursegraphs/merging.py @@ -10,13 +10,10 @@ So far, it is able to merge rhetorical structure theory (RS3), syntax import os import sys -import re import argparse from networkx import write_dot -from discoursegraphs import DiscourseDocumentGraph from discoursegraphs.relabel import relabel_nodes -from discoursegraphs.util import ensure_unicode from discoursegraphs.readwrite.anaphoricity import AnaphoraDocumentGraph from discoursegraphs.readwrite.rst import RSTGraph, rst_tokenlist from discoursegraphs.readwrite.tiger import TigerDocumentGraph, tiger_tokenlist diff --git a/src/discoursegraphs/readwrite/rst.py b/src/discoursegraphs/readwrite/rst.py index <HASH>..<HASH> 100755 --- a/src/discoursegraphs/readwrite/rst.py +++ b/src/discoursegraphs/readwrite/rst.py @@ -10,9 +10,7 @@ rhetorical structure) into a networkx-based directed graph from __future__ import print_function import os -import sys from lxml import etree -from networkx import write_gpickle from discoursegraphs import DiscourseDocumentGraph from discoursegraphs.readwrite.generic import generic_converter_cli diff --git a/src/discoursegraphs/readwrite/tiger.py b/src/discoursegraphs/readwrite/tiger.py index <HASH>..<HASH> 100755 --- a/src/discoursegraphs/readwrite/tiger.py +++ b/src/discoursegraphs/readwrite/tiger.py @@ -7,7 +7,6 @@ The ``tiger`` module converts a ``TigerXML`` file into a networkx-based document graph. """ -import sys import os from lxml import etree
flake8: removed unused imports
arne-cl_discoursegraphs
train
1c38ddd2604125e9aaa29746f724a56cbc90c21a
diff --git a/hebel/layers/hidden_layer.py b/hebel/layers/hidden_layer.py index <HASH>..<HASH> 100644 --- a/hebel/layers/hidden_layer.py +++ b/hebel/layers/hidden_layer.py @@ -217,12 +217,12 @@ class HiddenLayer(object): @property def l1_penalty(self): - return float(self.l1_penalty_weight) * gpuarray.sum(abs(self.W)) + return float(self.l1_penalty_weight * gpuarray.sum(abs(self.W))) @property def l2_penalty(self): - return float(self.l2_penalty_weight) * .5 * \ - gpuarray.sum(self.W ** 2.) + return float(self.l2_penalty_weight * .5 * \ + gpuarray.sum(self.W ** 2.)) def feed_forward(self, input_data, prediction=False): """Propagate forward through the layer diff --git a/hebel/layers/linear_regression_layer.py b/hebel/layers/linear_regression_layer.py index <HASH>..<HASH> 100644 --- a/hebel/layers/linear_regression_layer.py +++ b/hebel/layers/linear_regression_layer.py @@ -189,5 +189,5 @@ class LinearRegressionLayer(SoftmaxLayer): matrix_sum_out_axis((targets - activations) ** 2, 1)) if average: loss = loss.mean() - return loss + return loss.get() train_error = squared_loss diff --git a/hebel/layers/logistic_layer.py b/hebel/layers/logistic_layer.py index <HASH>..<HASH> 100644 --- a/hebel/layers/logistic_layer.py +++ b/hebel/layers/logistic_layer.py @@ -279,7 +279,7 @@ class LogisticLayer(TopLayer): if average: loss /= targets.shape[0] # assert np.isfinite(loss) - return loss + return loss.get() train_error = cross_entropy_error diff --git a/hebel/layers/softmax_layer.py b/hebel/layers/softmax_layer.py index <HASH>..<HASH> 100644 --- a/hebel/layers/softmax_layer.py +++ b/hebel/layers/softmax_layer.py @@ -282,7 +282,7 @@ class SoftmaxLayer(TopLayer): loss = cross_entropy(activations, targets) if average: loss /= targets.shape[0] - return loss + return loss.get() train_error = cross_entropy_error @@ -321,4 +321,4 @@ class SoftmaxLayer(TopLayer): cumath.log(activations + eps))) if average: kl_error /= targets.shape[0] - return float(kl_error.get()) + return kl_error.get() diff --git a/hebel/optimizers.py b/hebel/optimizers.py index <HASH>..<HASH> 100644 --- a/hebel/optimizers.py +++ b/hebel/optimizers.py @@ -173,13 +173,13 @@ class SGD(object): epoch_t = time.time() - t - self.progress_monitor.report(self.epoch, train_loss.get(), + self.progress_monitor.report(self.epoch, train_loss, validation_loss_rate, new_best, epoch_t=epoch_t) else: epoch_t = time.time() - t - self.progress_monitor.report(self.epoch, train_loss.get(), + self.progress_monitor.report(self.epoch, train_loss, epoch_t=epoch_t) except KeyboardInterrupt:
Reversal of previous commit - make train error consistently a float, and also L1/L2 penalty
hannes-brt_hebel
train
7de6a183bd84e90a772ab622dbba04e749a97f44
diff --git a/proton-c/bindings/python/proton/__init__.py b/proton-c/bindings/python/proton/__init__.py index <HASH>..<HASH> 100644 --- a/proton-c/bindings/python/proton/__init__.py +++ b/proton-c/bindings/python/proton/__init__.py @@ -1134,13 +1134,13 @@ The group-id for any replies. if link.is_sender: return None dlv = link.current if not dlv or dlv.partial: return None - encoded = link.recv(dlv.pending) + dlv.encoded = link.recv(dlv.pending) link.advance() # the sender has already forgotten about the delivery, so we might # as well too if link.remote_snd_settle_mode == Link.SND_SETTLED: dlv.settle() - self.decode(encoded) + self.decode(dlv.encoded) return dlv def __repr2__(self):
NO-JIRA: Python: keep received encoded bytes in the delivery
apache_qpid-proton
train
a57d58f38fc728bc062170842e7b22f7d9d263fb
diff --git a/queryx.go b/queryx.go index <HASH>..<HASH> 100644 --- a/queryx.go +++ b/queryx.go @@ -210,7 +210,7 @@ func (q *Queryx) Get(dest interface{}) error { if q.err != nil { return q.err } - return Iter(q.Query).Get(dest) + return q.Iter().Get(dest) } // GetRelease calls Get and releases the query, a released query cannot be @@ -230,7 +230,7 @@ func (q *Queryx) Select(dest interface{}) error { if q.err != nil { return q.err } - return Iter(q.Query).Select(dest) + return q.Iter().Select(dest) } // SelectRelease calls Select and releases the query, a released query cannot be @@ -244,5 +244,7 @@ func (q *Queryx) SelectRelease(dest interface{}) error { // big to be loaded with Select in order to do row by row iteration. // See Iterx StructScan function. func (q *Queryx) Iter() *Iterx { - return Iter(q.Query) + i := Iter(q.Query) + i.Mapper = q.Mapper + return i }
Iterx inherit mapper from Queryx
scylladb_gocqlx
train
882bd1a59a1c84d4735f6c33ab69c9930827a353
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -8,10 +8,10 @@ module.exports = function(app, urlTransform) { } return { - get: mirror.bind(null, 'get'), - post: mirror.bind(null, 'post'), - put: mirror.bind(null, 'put'), - delete: mirror.bind(null, 'delete'), - all: mirror.bind(null, 'all'), + get: mirror.bind(app, 'get'), + post: mirror.bind(app, 'post'), + put: mirror.bind(app, 'put'), + delete: mirror.bind(app, 'delete'), + all: mirror.bind(app, 'all'), } }
Bind the route handler to app.
raineorshine_route-mirror
train
cd6e5a7ce6f1ae8e67438b6c4f58f92336f9358b
diff --git a/Controller/TicketController.php b/Controller/TicketController.php index <HASH>..<HASH> 100644 --- a/Controller/TicketController.php +++ b/Controller/TicketController.php @@ -185,7 +185,7 @@ class TicketController extends Controller * Deletes a Ticket entity. * * @param Request $request - * @param $id + * @param Ticket $ticket * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function deleteAction(Request $request, Ticket $ticket)
Squashed commit of the following: commit <I>f<I>e9fe<I>de5b<I>e<I>fea<I>faa<I>be<I>a4
hackzilla_TicketBundle
train
686eb391a0b5ffc51fe7f6ad9b83cf39c9785a5c
diff --git a/gcs/gcstesting/bucket_tests.go b/gcs/gcstesting/bucket_tests.go index <HASH>..<HASH> 100644 --- a/gcs/gcstesting/bucket_tests.go +++ b/gcs/gcstesting/bucket_tests.go @@ -3625,6 +3625,43 @@ func (t *deleteTest) ParticularGeneration_Successful() { ExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{})) } +func (t *deleteTest) MetaGenerationPrecondition_Unsatisfied_ObjectExists() { + const name = "foo" + var err error + + // Create an object. + o, err := gcsutil.CreateObject( + t.ctx, + t.bucket, + name, + []byte("taco")) + + AssertEq(nil, err) + + // Attempt to delete, with a precondition for the wrong meta-generation. + precond := o.MetaGeneration + 1 + err = t.bucket.DeleteObject( + t.ctx, + &gcs.DeleteObjectRequest{ + Name: name, + MetaGenerationPrecondition: &precond, + }) + + ExpectThat(err, HasSameTypeAs(&gcs.PreconditionError{})) + + // The object should still exist. + _, err = gcsutil.ReadObject(t.ctx, t.bucket, name) + ExpectEq(nil, err) +} + +func (t *deleteTest) MetaGenerationPrecondition_Unsatisfied_ObjectDoesntExist() { + AssertTrue(false, "TODO") +} + +func (t *deleteTest) MetaGenerationPrecondition_Satisfied() { + AssertTrue(false, "TODO") +} + //////////////////////////////////////////////////////////////////////// // List ////////////////////////////////////////////////////////////////////////
DeleteTest.MetaGenerationPrecondition_Unsatisfied_ObjectExists
jacobsa_gcloud
train
81ded2a0e59d8e6b34434a169745fffc43db4f73
diff --git a/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java b/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java @@ -79,7 +79,8 @@ public class InMemoryUserDetailsManager implements UserDetailsManager, UserDetai String name = (String) names.nextElement(); editor.setAsText(users.getProperty(name)); UserAttribute attr = (UserAttribute) editor.getValue(); - Assert.notNull(attr, "The entry with username '" + name + "' could not be converted to an UserDetails"); + Assert.notNull(attr, + () -> "The entry with username '" + name + "' could not be converted to an UserDetails"); createUser(createUserDetails(name, attr)); } }
Polish Assertion By using the supplier version of Assert.notNull, the string concatenation is delayed. Issue gh-<I>
spring-projects_spring-security
train