hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
4800dd65b5b085cbccbb700ee23dbb3d567d5cc9
|
diff --git a/estnltk_core/estnltk_core/layer/base_layer.py b/estnltk_core/estnltk_core/layer/base_layer.py
index <HASH>..<HASH> 100644
--- a/estnltk_core/estnltk_core/layer/base_layer.py
+++ b/estnltk_core/estnltk_core/layer/base_layer.py
@@ -166,29 +166,23 @@ class BaseLayer:
result.add_annotation(span.base_span, **annotation)
return result
- def _set_attributes(self, attributes: Sequence[str]):
- assert not isinstance(attributes, str), attributes
- attributes = tuple(attributes)
- assert all(attr.isidentifier() for attr in attributes), attributes
- assert len(attributes) == len(set(attributes)), 'repetitive attribute name: ' + str(attributes)
- super().__setattr__('attributes', attributes)
-
- try:
- # due to unordered __slots__ in case of Python <= 3.5
- # 'default_values' might not be set by __deepcopy__ before setting 'attributes'
- # which would lead to nasty errors
- self.__getattribute__('default_values')
- except AttributeError:
- self.default_values = {}
-
- for attr in set(self.default_values) - set(attributes):
- del self.default_values[attr]
-
- self.default_values = {attr: self.default_values.get(attr) for attr in attributes}
-
def __setattr__(self, key, value):
if key == 'attributes':
- return self._set_attributes(value)
+ # set attributes
+ attributes = value
+ assert not isinstance(attributes, str), \
+ 'attributes must be a list or tuple of strings, not a single string {!r}'.format(attributes)
+ attributes = tuple(attributes)
+ # TODO: do we need the following constraint?
+ assert all(attr.isidentifier() for attr in attributes), \
+ 'unexpected attribute name: all names should be identifiers in {!r}'.format(attributes)
+ assert len(attributes) == len(set(attributes)), 'repetitive attribute name: ' + str(attributes)
+ super().__setattr__('attributes', attributes)
+ # (re)set default values
+ for attr in set(self.default_values) - set(attributes):
+ del self.default_values[attr]
+ self.default_values = {attr: self.default_values.get(attr) for attr in attributes}
+ return
super().__setattr__(key, value)
def __setitem__(self, key: int, value: Span):
|
Refactored BaseLayer: moved _set_attributes into _set_attr
|
estnltk_estnltk
|
train
|
9378bc42c8c5cc870a755fe268af778e6261aa4b
|
diff --git a/src/org/mockito/internal/creation/cglib/MockitoMethodProxy.java b/src/org/mockito/internal/creation/cglib/MockitoMethodProxy.java
index <HASH>..<HASH> 100644
--- a/src/org/mockito/internal/creation/cglib/MockitoMethodProxy.java
+++ b/src/org/mockito/internal/creation/cglib/MockitoMethodProxy.java
@@ -4,6 +4,7 @@
*/
package org.mockito.internal.creation.cglib;
+//TODO SF Replace with RealMethod and get rid of (possibly).
public interface MockitoMethodProxy {
Object invokeSuper(Object target, Object[] arguments) throws Throwable;
}
\ No newline at end of file
diff --git a/src/org/mockito/internal/invocation/realmethod/RealMethod.java b/src/org/mockito/internal/invocation/realmethod/RealMethod.java
index <HASH>..<HASH> 100644
--- a/src/org/mockito/internal/invocation/realmethod/RealMethod.java
+++ b/src/org/mockito/internal/invocation/realmethod/RealMethod.java
@@ -1,10 +1,9 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.internal.invocation.realmethod;
-
public interface RealMethod {
Object invoke(Object target, Object[] arguments) throws Throwable;
diff --git a/test/org/mockito/internal/creation/cglib/CGLIBHackerTest.java b/test/org/mockito/internal/creation/cglib/CGLIBHackerTest.java
index <HASH>..<HASH> 100644
--- a/test/org/mockito/internal/creation/cglib/CGLIBHackerTest.java
+++ b/test/org/mockito/internal/creation/cglib/CGLIBHackerTest.java
@@ -17,14 +17,13 @@ public class CGLIBHackerTest extends TestBase {
@Test
public void shouldSetMockitoNamingPolicy() throws Exception {
//given
- MethodProxy methodProxy = MethodProxy.create(null, null, null, null, null);
+ MethodProxy methodProxy = MethodProxy.create(String.class, Integer.class, "", "", "");
//when
new CGLIBHacker().setMockitoNamingPolicy(methodProxy);
//then
- Object realMethodProxy = Whitebox.invokeMethod(methodProxy, "getMethodProxy", new Object[0]);
- Object createInfo = Whitebox.getInternalState(realMethodProxy, "createInfo");
+ Object createInfo = Whitebox.getInternalState(methodProxy, "createInfo");
NamingPolicy namingPolicy = (NamingPolicy) Whitebox.getInternalState(createInfo, "namingPolicy");
assertEquals(MockitoNamingPolicy.INSTANCE, namingPolicy);
}
@@ -32,14 +31,13 @@ public class CGLIBHackerTest extends TestBase {
@Test
public void shouldSetMockitoNamingPolicyEvenIfMethodProxyIsProxied() throws Exception {
//given
- MethodProxy proxiedMethodProxy = spy(MethodProxy.create(null, null, null, null, null));
+ MethodProxy proxiedMethodProxy = spy(MethodProxy.create(String.class, Integer.class, "", "", ""));
//when
new CGLIBHacker().setMockitoNamingPolicy(proxiedMethodProxy);
//then
- Object realMethodProxy = Whitebox.invokeMethod(proxiedMethodProxy, "getMethodProxy", new Object[0]);
- Object createInfo = Whitebox.getInternalState(realMethodProxy, "createInfo");
+ Object createInfo = Whitebox.getInternalState(proxiedMethodProxy, "createInfo");
NamingPolicy namingPolicy = (NamingPolicy) Whitebox.getInternalState(createInfo, "namingPolicy");
assertEquals(MockitoNamingPolicy.INSTANCE, namingPolicy);
}
|
Fixed the test and added a TODO.
|
mockito_mockito
|
train
|
d0770684bee963cf089787876f6093311b0c58e7
|
diff --git a/publisher.js b/publisher.js
index <HASH>..<HASH> 100644
--- a/publisher.js
+++ b/publisher.js
@@ -3,11 +3,21 @@
var s3 = require('gulp-s3');
module.exports = function( opts ) {
- if( !opts || !opts.creds || !opts.creds.key || !opts.creds.secret ) {
+ var aws;
+ if (!opts || !opts.creds ) {
throw new Error('Invalid arguments');
+ } else if (typeof opts.creds == 'string') {
+ try {
+ aws = require(opts.creds);
+ } catch (err) {
+ throw new Error( 'Invalid creds location' );
+ }
+ } else if ( !opts.creds.key || !opts.creds.secret ) {
+ throw new Error('Invalid arguments');
+ } else {
+ aws = opts.creds;
}
- var aws = opts.creds;
aws.bucket = 'gaudi-cdn-test';
var options = {
diff --git a/test/publisher.js b/test/publisher.js
index <HASH>..<HASH> 100644
--- a/test/publisher.js
+++ b/test/publisher.js
@@ -29,4 +29,13 @@ describe('publisher', function() {
publisher(options)
}).to.throw( 'Invalid arguments' );
})
+
+ it('should throw with invalid location of creds', function() {
+ var options = {
+ creds: './creds.json'
+ }
+ expect(function() {
+ publisher(options)
+ }).to.throw( 'Invalid creds location' );
+ })
})
\ No newline at end of file
|
Added a way to check the creds to see if it is an object or a location and handles it accordingly.
|
Brightspace_frau-publisher
|
train
|
b53341b34b69b0d6cfed0d53174c24ecc17623f3
|
diff --git a/src/samples/java/ex/FII_Sample.java b/src/samples/java/ex/FII_Sample.java
index <HASH>..<HASH> 100644
--- a/src/samples/java/ex/FII_Sample.java
+++ b/src/samples/java/ex/FII_Sample.java
@@ -6,6 +6,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@@ -69,11 +70,21 @@ public class FII_Sample {
return baubles.stream().filter(b -> b.getName().equals("special")).map(b -> (BigDecimal) b.getCost()).findFirst().get();
}
- public static <T> Stream<T> fpIiteratorToFiniteStream(Iterator<T> iterator, boolean parallel) {
+ public static <T> Stream<T> fpIiteratorToFiniteStream283(Iterator<T> iterator, boolean parallel) {
Iterable<T> iterable = () -> iterator;
return StreamSupport.stream(iterable.spliterator(), parallel);
}
+ public void fpUseIdentity283() {
+ put(m -> {
+ m.putAll(m);
+ return m;
+ });
+ }
+
+ public void put(Function<Map<String, Object>, Map<String, Object>> updateFunction) {
+ }
+
public static class Bauble {
public String getName() {
|
add another FII fp for use identity for #<I>
|
mebigfatguy_fb-contrib
|
train
|
9342776c9c76f9fd2656fdeb202ea0052ddd44a2
|
diff --git a/p2p/protocol/identify/obsaddr.go b/p2p/protocol/identify/obsaddr.go
index <HASH>..<HASH> 100644
--- a/p2p/protocol/identify/obsaddr.go
+++ b/p2p/protocol/identify/obsaddr.go
@@ -109,7 +109,8 @@ type ObservedAddrManager struct {
// active connection -> most recent observation
activeConns map[network.Conn]ma.Multiaddr
- mu sync.RWMutex
+ mu sync.RWMutex
+ closed bool
// local(internal) address -> list of observed(external) addresses
addrs map[string][]*observedAddr
ttl time.Duration
@@ -530,9 +531,14 @@ func (oas *ObservedAddrManager) emitSpecificNATType(addrs []*observedAddr, proto
func (oas *ObservedAddrManager) Close() error {
oas.closeOnce.Do(func() {
oas.ctxCancel()
+
+ oas.mu.Lock()
+ oas.closed = true
+ oas.refreshTimer.Stop()
+ oas.mu.Unlock()
+
oas.refCount.Wait()
oas.reachabilitySub.Close()
- oas.refreshTimer.Stop()
oas.host.Network().StopNotify((*obsAddrNotifiee)(oas))
})
return nil
@@ -558,6 +564,9 @@ func observerGroup(m ma.Multiaddr) string {
func (oas *ObservedAddrManager) SetTTL(ttl time.Duration) {
oas.mu.Lock()
defer oas.mu.Unlock()
+ if oas.closed {
+ return
+ }
oas.ttl = ttl
// refresh every ttl/2 so we don't forget observations from connected peers
oas.refreshTimer.Reset(ttl / 2)
|
allow concurrent calls to Close and SetTTL in the ObservedAddrManager
|
libp2p_go-libp2p
|
train
|
32e57a1e8e200f9049144270b52c0caeb2c79fd8
|
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -445,6 +445,14 @@
'version': '31.0.1650.63'
},
+ 'Chrome 34.0.1847.137 on OS X 10.9.3': {
+ 'ua': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36',
+ 'layout': 'Blink',
+ 'name': 'Chrome',
+ 'os': 'OS X 10.9.3',
+ 'version': '34.0.1847.137'
+ },
+
'Chrome Mobile 16.0.912.77 on HTC (Android 4.0.3)': {
'ua': 'Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; HTC Sensation XE with Beats Audio Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.77 Mobile Safari/535.7',
'layout': 'WebKit',
@@ -660,6 +668,14 @@
'version': '25.0'
},
+ 'Firefox 29.0 on OS X 10.9': {
+ 'ua': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0',
+ 'layout': 'Gecko',
+ 'name': 'Firefox',
+ 'os': 'OS X 10.9',
+ 'version': '29.0'
+ },
+
'Firefox Mobile 2.0#{beta}1 on Android': {
'ua': 'Mozilla/5.0 (Android; Linux armv7l; rv:2.0b6pre) Gecko/20100907 Firefox/4.0b6pre Fennec/2.0b1pre',
'layout': 'Gecko',
@@ -1507,6 +1523,14 @@
'version': '18.0.1284.49'
},
+ 'Opera 21.0.1432.67 on OS X 10.9.3': {
+ 'ua': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.132 Safari/537.36 OPR/21.0.1432.67',
+ 'layout': 'Blink',
+ 'name': 'Opera',
+ 'os': 'OS X 10.9.3',
+ 'version': '21.0.1432.67'
+ },
+
'PhantomJS 1.0.0 (like Safari 4.x) on Cygwin': {
'ua': 'Mozilla/5.0 (X11; U; Cygwin; C -) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) PhantomJS/1.0.0',
'layout': 'WebKit',
|
Update tests
Add tests for Chrome <I>, Firefox <I> and Opera <I>
|
bestiejs_platform.js
|
train
|
884995b3644a3aa6a50a376ed2bc477150e15c5e
|
diff --git a/src/bbn/mvc.php b/src/bbn/mvc.php
index <HASH>..<HASH> 100644
--- a/src/bbn/mvc.php
+++ b/src/bbn/mvc.php
@@ -614,13 +614,15 @@ class mvc
}
/**
- * Processes the controller and checks whether it has been routed or not.
- *
+ * Adds a property to the MVC object inc if it has not been declared.
+ *
* @return bool
*/
public function add_inc($name, $obj)
{
- $this->inc->{$name} = $obj;
+ if ( !isset($this->inc->{$name}) ){
+ $this->inc->{$name} = $obj;
+ }
}
/**
|
A little change in mvc.php
|
nabab_bbn
|
train
|
3ee3411077b1df9d6747d71ab8bf4ab4506917aa
|
diff --git a/doc-src/SASS_CHANGELOG.md b/doc-src/SASS_CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/doc-src/SASS_CHANGELOG.md
+++ b/doc-src/SASS_CHANGELOG.md
@@ -12,6 +12,7 @@
* Support bare interpolation in the value portion of attribute
selectors (e.g. `[name=#{$value}]`).
* Support keyword arguments for the `invert()` function.
+* Handle backslash-separated paths better on Windows.
## 3.1.16
diff --git a/lib/sass/exec.rb b/lib/sass/exec.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/exec.rb
+++ b/lib/sass/exec.rb
@@ -452,7 +452,7 @@ MSG
def probably_dest_dir?(path)
return false unless path
return false if colon_path?(path)
- return Dir.glob(File.join(path, "*.s[ca]ss")).empty?
+ return Sass::Util.glob(File.join(path, "*.s[ca]ss")).empty?
end
end
@@ -584,7 +584,7 @@ END
end
ext = @options[:from]
- Dir.glob("#{@options[:input]}/**/*.#{ext}") do |f|
+ Sass::Util.glob("#{@options[:input]}/**/*.#{ext}") do |f|
output =
if @options[:in_place]
f
diff --git a/lib/sass/plugin/compiler.rb b/lib/sass/plugin/compiler.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/plugin/compiler.rb
+++ b/lib/sass/plugin/compiler.rb
@@ -188,7 +188,7 @@ module Sass::Plugin
staleness_checker = StalenessChecker.new(engine_options)
template_location_array.each do |template_location, css_location|
- Dir.glob(File.join(template_location, "**", "[^_]*.s[ca]ss")).sort.each do |file|
+ Sass::Util.glob(File.join(template_location, "**", "[^_]*.s[ca]ss")).sort.each do |file|
# Get the relative path to the file
name = file.sub(template_location.to_s.sub(/\/*$/, '/'), "")
css = css_filename(name, css_location)
diff --git a/lib/sass/util.rb b/lib/sass/util.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/util.rb
+++ b/lib/sass/util.rb
@@ -399,6 +399,14 @@ module Sass
RUBY_ENGINE == "ironruby"
end
+ # Like `Dir.glob`, but works with backslash-separated paths on Windows.
+ #
+ # @param path [String]
+ def glob(path)
+ path = path.gsub('\\', '/') if windows?
+ Dir.glob(path)
+ end
+
## Cross-Ruby-Version Compatibility
# Whether or not this is running under Ruby 1.8 or lower.
|
Fix Dir.glob with backslash paths on Windows.
|
sass_ruby-sass
|
train
|
cfc5d5c947ff6d056387194665fb287d9aeb4bea
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -15,7 +15,7 @@ except IOError:
setup(
name = 'Studio',
- version = '0.1',
+ version = '0.5dev',
license = 'GPLv3',
description = 'Studio is a management system for GIS.',
long_description = long_description,
|
current version is O<I>dev
|
camptocamp_Studio
|
train
|
6f585ff04076061c5616e9c7434e52a9fae6eec6
|
diff --git a/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java b/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java
index <HASH>..<HASH> 100644
--- a/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java
+++ b/src/main/java/gwt/material/design/addins/client/tree/MaterialTree.java
@@ -98,7 +98,9 @@ public class MaterialTree extends MaterialWidget implements HasCloseHandlers<Mat
}
}
MaterialTreeItem treeItem = event.getSelectedItem();
- treeItem.addStyleName(AddinsCssName.SELECTED);
+ if (treeItem != null) {
+ treeItem.addStyleName(AddinsCssName.SELECTED);
+ }
setSelectedItem(treeItem);
}));
}
|
Fixed MaterialTree: NullPointerException when deselectSelectedItem execute #<I>
|
GwtMaterialDesign_gwt-material-addins
|
train
|
9ae142abe6875a32a8fca2b8fe5c1d8800e0b97a
|
diff --git a/asciimatics/widgets.py b/asciimatics/widgets.py
index <HASH>..<HASH> 100644
--- a/asciimatics/widgets.py
+++ b/asciimatics/widgets.py
@@ -441,6 +441,9 @@ class Frame(Effect):
for layout in self._layouts:
if layout.frame_update_count > 0:
result = min(result, layout.frame_update_count)
+ for effect in self._effects:
+ if effect.frame_update_count > 0:
+ result = min(result, effect.frame_update_count)
return result
@property
|
Quick patch for Effects embedded within Frames
|
peterbrittain_asciimatics
|
train
|
9caad14c46d037e5b59d00178509eaf0c2f8dfee
|
diff --git a/tests/conftest.py b/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -17,7 +17,7 @@ ENV = Env()
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
S3_PREFIX = 'test_pyathena'
SCHEMA = 'test_pyathena_' + ''.join([random.choice(
- string.ascii_lowercase + string.digits) for i in xrange(10)])
+ string.ascii_lowercase + string.digits) for _ in xrange(10)])
@pytest.fixture(scope='session', autouse=True)
diff --git a/tests/test_pandas_cursor.py b/tests/test_pandas_cursor.py
index <HASH>..<HASH> 100644
--- a/tests/test_pandas_cursor.py
+++ b/tests/test_pandas_cursor.py
@@ -4,12 +4,13 @@ from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
+import random
+import string
import time
import unittest
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from decimal import Decimal
-from random import randint
import numpy as np
import pandas as pd
@@ -20,7 +21,7 @@ from pyathena.error import NotSupportedError
from pyathena.model import AthenaQueryExecution
from pyathena.pandas_cursor import PandasCursor
from pyathena.result_set import AthenaPandasResultSet
-from tests.conftest import SCHEMA
+from tests.conftest import ENV, S3_PREFIX, SCHEMA
from tests.util import with_pandas_cursor
@@ -283,7 +284,7 @@ class TestPandasCursor(unittest.TestCase):
@with_pandas_cursor
def test_cancel(self, cursor):
def cancel(c):
- time.sleep(randint(1, 5))
+ time.sleep(random.randint(1, 5))
c.cancel()
with ThreadPoolExecutor(max_workers=1) as executor:
@@ -311,3 +312,18 @@ class TestPandasCursor(unittest.TestCase):
'SELECT * FROM one_row', []))
cursor.close()
conn.close()
+
+ @with_pandas_cursor
+ def test_empty_result(self, cursor):
+ table = 'test_pandas_cursor_empty_result_' + ''.join([random.choice(
+ string.ascii_lowercase + string.digits) for _ in xrange(10)])
+ location = '{0}{1}/{2}/'.format(ENV.s3_staging_dir, S3_PREFIX, table)
+ df = cursor.execute("""
+ CREATE EXTERNAL TABLE IF NOT EXISTS
+ {schema}.{table} (number_of_rows INT)
+ ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
+ LINES TERMINATED BY '\n' STORED AS TEXTFILE
+ LOCATION '{location}'
+ """.format(schema=SCHEMA, table=table, location=location)).as_pandas()
+ self.assertEqual(df.shape[0], 0)
+ self.assertEqual(df.shape[1], 0)
|
Add test cases for empty results in PandasCursor
|
laughingman7743_PyAthena
|
train
|
162982cf55343747e37634909b1a882783fac6b2
|
diff --git a/src/components/cursor.js b/src/components/cursor.js
index <HASH>..<HASH> 100644
--- a/src/components/cursor.js
+++ b/src/components/cursor.js
@@ -44,6 +44,7 @@ module.exports.Component = registerComponent('cursor', {
value: function () {
this.emit('mouseup');
if (this.data.fuse) { return; }
+ if (!this.intersectedEl) { return; }
if (this.mouseDownEl === this.intersectedEl) {
this.emit('click');
this.intersectedEl.emit('click');
|
When there's no interested element we don't emit a click event
|
aframevr_aframe
|
train
|
6a05bdd40c953f0ad3dc583d166facce64aee89e
|
diff --git a/src/Command/Integration/IntegrationDeleteCommand.php b/src/Command/Integration/IntegrationDeleteCommand.php
index <HASH>..<HASH> 100644
--- a/src/Command/Integration/IntegrationDeleteCommand.php
+++ b/src/Command/Integration/IntegrationDeleteCommand.php
@@ -22,8 +22,9 @@ class IntegrationDeleteCommand extends IntegrationCommandBase
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
+ $project = $this->getSelectedProject();
- $integration = $this->selectIntegration($this->getSelectedProject(), $input->getArgument('id'), $input->isInteractive());
+ $integration = $this->selectIntegration($project, $input->getArgument('id'), $input->isInteractive());
if (!$integration) {
return 1;
}
|
Fix bug in integration:delete command: "Call to a member function getGitUrl() on null"
|
platformsh_platformsh-cli
|
train
|
a24abd55e064e752fcd675e529603c175de418eb
|
diff --git a/grade/report/singleview/index.php b/grade/report/singleview/index.php
index <HASH>..<HASH> 100644
--- a/grade/report/singleview/index.php
+++ b/grade/report/singleview/index.php
@@ -35,12 +35,12 @@ $userid = optional_param('userid', null, PARAM_INT);
$defaulttype = $userid ? 'user' : 'select';
-$itemid = optional_param('itemid', $userid, PARAM_INT);
+$itemid = optional_param('itemid', null, PARAM_INT);
$itemtype = optional_param('item', $defaulttype, PARAM_TEXT);
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', 100, PARAM_INT);
-if ($itemid < 1){
+if (empty($itemid)) {
$itemid = $userid;
$itemtype = $defaulttype;
}
|
MDL-<I> singleview: slightly clarify logic
Make it clearer what the 'unset' behaviour is because previously
we've set the default for 'empty' values twice.
|
moodle_moodle
|
train
|
5651295bffd88dbca8c89ea17eba77a287223d54
|
diff --git a/tests/test_graphers_render_analyzers.py b/tests/test_graphers_render_analyzers.py
index <HASH>..<HASH> 100644
--- a/tests/test_graphers_render_analyzers.py
+++ b/tests/test_graphers_render_analyzers.py
@@ -8,7 +8,7 @@ import numpy as np
from tempfile import NamedTemporaryFile
import os
-PLOT = False
+PLOT = True
class Test_graphers_analyzers(unittest.TestCase):
@@ -40,23 +40,25 @@ class Test_graphers_analyzers(unittest.TestCase):
# Clean-up : delete temp file
os.unlink(self.temp_file.name)
-list_graphers = timeside.core.processors(timeside.api.IGrapher)
-module = 'timeside.grapher.render_analyzers'
-grapher_analyzers = [grapher for grapher in list_graphers
- if grapher.__module__ == module]
-for grapher in grapher_analyzers:
+def _tests_factory(grapher_analyzers):
+ for grapher in grapher_analyzers:
- def _test_func_factory(grapher):
- test_func = lambda self: self._perform_test(grapher)
- test_func.__doc__ = 'Test Graphers : %s' % grapher.name()
- return test_func
+ def _test_func_factory(grapher):
+ test_func = lambda self: self._perform_test(grapher)
+ test_func.__doc__ = 'Test Graphers : %s' % grapher.name()
+ return test_func
- test_func_name = "test_%s" % grapher.name()
- test_func = _test_func_factory(grapher)
+ test_func_name = "test_%s" % grapher.name()
+ test_func = _test_func_factory(grapher)
- setattr(Test_graphers_analyzers, test_func_name, test_func)
+ setattr(Test_graphers_analyzers, test_func_name, test_func)
+list_graphers = timeside.core.processors(timeside.api.IGrapher)
+module = 'timeside.grapher.render_analyzers'
+grapher_analyzers = [grapher for grapher in list_graphers
+ if grapher.__module__ == module]
+_tests_factory(grapher_analyzers)
if __name__ == '__main__':
unittest.main(testRunner=TestRunner())
|
refactor(test_graphers_render_analyzers): Encapsulate test facory in a function
|
Parisson_TimeSide
|
train
|
33de5cd0906c00dc62d78ea46f27bf232a79cfd5
|
diff --git a/source/constructN.js b/source/constructN.js
index <HASH>..<HASH> 100644
--- a/source/constructN.js
+++ b/source/constructN.js
@@ -46,7 +46,7 @@ var constructN = _curry2(function constructN(n, Fn) {
return function() { return new Fn(); };
}
return curry(nAry(n, function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
- switch (arguments.length) {
+ switch (n) {
case 1: return new Fn($0);
case 2: return new Fn($0, $1);
case 3: return new Fn($0, $1, $2);
|
arguments.length will always be the same as n (#<I>)
|
ramda_ramda
|
train
|
76bb48825df0e4cccfb7e0272f54fe55ec575f07
|
diff --git a/modules/quality-check/src/test/java/com/github/quality/check/CheckTest.java b/modules/quality-check/src/test/java/com/github/quality/check/CheckTest.java
index <HASH>..<HASH> 100644
--- a/modules/quality-check/src/test/java/com/github/quality/check/CheckTest.java
+++ b/modules/quality-check/src/test/java/com/github/quality/check/CheckTest.java
@@ -16,6 +16,7 @@
******************************************************************************/
package com.github.quality.check;
+import org.junit.Assert;
import org.junit.Test;
import com.github.quality.check.exception.IllegalNullArgumentException;
@@ -28,6 +29,13 @@ import com.github.quality.check.exception.IllegalNullArgumentException;
*/
public class CheckTest {
+ @Test
+ public void notNull_checkReferenceIsSame() {
+ final String text = "beer tastes good";
+ Assert.assertSame(text, Check.notNull(text));
+ Assert.assertSame(text, Check.notNull(text, "textArg"));
+ }
+
@Test(expected = IllegalNullArgumentException.class)
public void notNull_withReference_isInvalid() {
Check.notNull(null);
|
Added one more test to check the return reference of method 'notNull' is
same as the input
|
before_quality-check
|
train
|
73f24f5a2bb5aba9617856ca2e46ce49411dc302
|
diff --git a/pywb/manager/manager.py b/pywb/manager/manager.py
index <HASH>..<HASH> 100644
--- a/pywb/manager/manager.py
+++ b/pywb/manager/manager.py
@@ -145,7 +145,8 @@ directory structure expected by pywb
merged.write(line)
last_line = line
- os.rename(merged_file, cdx_file)
+ shutil.move(merged_file, cdx_file)
+ #os.rename(merged_file, cdx_file)
os.remove(temp_file)
def set_metadata(self, namevalue_pairs):
diff --git a/tests/test_auto_colls.py b/tests/test_auto_colls.py
index <HASH>..<HASH> 100644
--- a/tests/test_auto_colls.py
+++ b/tests/test_auto_colls.py
@@ -37,12 +37,12 @@ def setup_module():
root_dir = os.getcwd()
def teardown_module():
- global root_dir
- shutil.rmtree(root_dir)
-
global orig_cwd
os.chdir(orig_cwd)
+ global root_dir
+ shutil.rmtree(root_dir)
+
#=============================================================================
class TestManagedColls(object):
|
manager: fixes for windows: use shutil.move instead of os.rename to allow move to
existing file
tests: reset workdir before deleting temp dir
|
webrecorder_pywb
|
train
|
200519a6ec6289034ab92293de2a843b4cfb2459
|
diff --git a/angr/sim_procedure.py b/angr/sim_procedure.py
index <HASH>..<HASH> 100644
--- a/angr/sim_procedure.py
+++ b/angr/sim_procedure.py
@@ -28,9 +28,61 @@ class SimProcedure:
:param is_syscall: Whether this procedure is a syscall
:param num_args: The number of arguments this procedure should extract
:param display_name: The name to use when displaying this procedure
+ :param library_name: The name of the library from which the function we're emulating comes
:param cc: The SimCC to use for this procedure
:param sim_kwargs: Additional keyword arguments to be passed to run()
:param is_function: Whether this procedure emulates a function
+
+ The following class variables should be set if necessary when implementing a new SimProcedure:
+
+ :cvar NO_RET: Set this to true if control flow will never return from this function
+ :cvar ADDS_EXITS: Set this to true if you do any control flow other than returning
+ :cvar IS_FUNCTION: Does this procedure simulate a function? True by default
+ :cvar ARGS_MISMATCH: Does this procedure have a different list of arguments than what is provided in the
+ function specification? This may happen when we manually extract arguments in the run()
+ method of a SimProcedure. False by default.
+ :cvar local_vars: If you use ``self.call()``, set this to a list of all the local variable
+ names in your class. They will be restored on return.
+
+ The following instance variables are available when working with simprocedures from the inside or the outside:
+
+ :ivar project: The associated angr project
+ :ivar arch: The associated architecture
+ :ivar addr: The linear address at which the procedure is executing
+ :ivar cc: The calling convention in use for engaging with the ABI
+ :ivar canonical: The canonical version of this SimProcedure. Procedures are deepcopied for many reasons,
+ including to be able to store state related to a specific run and to be able to hook
+ continuations.
+ :ivar kwargs: Any extra keyword arguments used to construct the procedure; will be passed to ``run``
+ :ivar display_name: See the eponymous parameter
+ :ivar library_name: See the eponymous parameter
+ :ivar abi:
+ :ivar symbolic_return: See the eponymous parameter
+ :ivar syscall_number: If this procedure is a syscall, the number will be populated here.
+ :ivar returns: See eponymous parameter and NO_RET cvar
+ :ivar is_syscall: See eponymous parameter
+ :ivar is_function: See eponymous parameter and cvar
+ :ivar is_stub: See eponymous parameter
+ :ivar is_continuation: Whether this procedure is the original or a continuation resulting from ``self.call()``
+ :ivar continuations: A mapping from name to each known continuation
+ :ivar run_func: The name of the function implementing the procedure. "run" by default, but different in
+ continuations.
+ :ivar num_args: The number of arguments to the procedure. If not provided in the parameter, extracted from
+ the definition of ``self.run``
+
+ The following instance variables are only used in a copy of the procedure that is actually executing on a state:
+
+ :ivar state: The SimState we should be mutating to perform the procedure
+ :ivar successors: The SimSuccessors associated with the current step
+ :ivar arguments: The function arguments, deserialized from the state
+ :ivar use_state_arguments:
+ Whether we're using arguments extracted from the state or manually provided
+ :ivar ret_to: The current return address
+ :ivar ret_expr: The computed return value
+ :ivar call_ret_expr: The return value from having used ``self.call()``
+ :ivar inhibit_autoret: Whether we should avoid automatically adding an exit for returning once the run function
+ ends
+
"""
def __init__(
self, project=None, cc=None, symbolic_return=None,
@@ -210,15 +262,11 @@ class SimProcedure:
# Implement these in a subclass of SimProcedure!
#
- NO_RET = False # set this to true if control flow will never return from this function
- ADDS_EXITS = False # set this to true if you do any control flow other than returning
- IS_FUNCTION = True # does this procedure simulate a function?
- ARGS_MISMATCH = False # does this procedure have a different list of arguments than what is provided in the
- # function specification? This may happen when we manually extract arguments in the run()
- # method of a SimProcedure.
-
- local_vars = () # if you use self.call(), set this to a list of all the local variable
- # names in your class. They will be restored on return.
+ NO_RET = False
+ ADDS_EXITS = False
+ IS_FUNCTION = True
+ ARGS_MISMATCH = False
+ local_vars = ()
def run(self, *args, **kwargs): # pylint: disable=unused-argument
"""
|
Document simprocedure ivars. see #<I>
|
angr_angr
|
train
|
a7a98c5f87934a86e7868b414e109de1f5ea1f1f
|
diff --git a/cmd/sockaddr/README.md b/cmd/sockaddr/README.md
index <HASH>..<HASH> 100644
--- a/cmd/sockaddr/README.md
+++ b/cmd/sockaddr/README.md
@@ -97,8 +97,8 @@ Options:
Here are a few impractical examples to get you started:
```text
-$ sockaddr eval '{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | joinAddrs " "}}'
-[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | joinAddrs \" \"}}"
+$ sockaddr eval '{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | join "address" " "}}'
+[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | join "address" \" \"}}"
[0] out: "100:: fe80::1/64"
$ sockaddr eval '{{. | includeByRFC 1918 | ifNames | print | len | lt 2}}'
[0] in: "{{. | includeByRFC 1918 | ifNames | print | len | lt 2}}"
@@ -106,13 +106,13 @@ $ sockaddr eval '{{. | includeByRFC 1918 | ifNames | print | len | lt 2}}'
$ sockaddr eval '{{with $ifSet := includeByIfName "lo0" . }}{{ range includeByType "IPv6" $ifSet | ifAddrs | sortByAddr | reverseAddrs}}{{ . }} {{end}}{{end}}'
[0] in: "{{with $ifSet := includeByIfName \"lo0\" . }}{{ range includeByType \"IPv6\" $ifSet | ifAddrs | sortByAddr | reverseAddrs}}{{ . }} {{end}}{{end}}"
[0] out: "fe80::1/64 100:: "
-$ sockaddr eval '{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | joinAddrs " "}}'
-[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | joinAddrs \" \"}}"
+$ sockaddr eval '{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | join "address" " "}}'
+[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | join "address" \" \"}}"
[0] out: "100:: fe80::1/64"
$ cat <<'EOF' | sockaddr eval -
-{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | joinAddrs " "}}
+{{. | includeByIfName "lo0" | includeByType "IPv6" | ifAddrs | sortByAddr | join "address" " "}}
EOF
-[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | joinAddrs \" \"}}"
+[0] in: "{{. | includeByIfName \"lo0\" | includeByType \"IPv6\" | ifAddrs | sortByAddr | join "address" \" \"}}"
[0] out: "100:: fe80::1/64"
```
diff --git a/sockaddrs.go b/sockaddrs.go
index <HASH>..<HASH> 100644
--- a/sockaddrs.go
+++ b/sockaddrs.go
@@ -3,7 +3,6 @@ package sockaddr
import (
"bytes"
"sort"
- "strings"
)
// SockAddrs is a collection of SockAddrs
@@ -214,15 +213,6 @@ func (sas SockAddrs) OnlyIPv6() (IPv6Addrs, SockAddrs) {
return ipv6Addrs, nonIPv6Addrs
}
-// JoinAddrs joins a list of SockAddrs and returns a string
-func JoinAddrs(joinStr string, inputAddrs SockAddrs) string {
- stringAddrs := make([]string, 0, len(inputAddrs))
- for _, sa := range inputAddrs {
- stringAddrs = append(stringAddrs, sa.String())
- }
- return strings.Join(stringAddrs, joinStr)
-}
-
// ReverseAddrs reverses a list of SockAddrs.
func ReverseAddrs(inputAddrs SockAddrs) SockAddrs {
reversedAddrs := append([]SockAddr(nil), inputAddrs...)
diff --git a/template/template.go b/template/template.go
index <HASH>..<HASH> 100644
--- a/template/template.go
+++ b/template/template.go
@@ -67,7 +67,6 @@ func init() {
HelperFuncs = template.FuncMap{
// Misc functions that operate on []SockAddr inputs
- "joinAddrs": sockaddr.JoinAddrs,
"reverseAddrs": sockaddr.ReverseAddrs,
"limitAddrs": sockaddr.LimitAddrs,
|
Remove joinAddrs in favor of the syntax: `join "address" " "`
|
hashicorp_go-sockaddr
|
train
|
2a8999fba35d6e77e8e7d49af2207ff20cb3974e
|
diff --git a/bag.go b/bag.go
index <HASH>..<HASH> 100644
--- a/bag.go
+++ b/bag.go
@@ -1,7 +1,5 @@
/*
-Methods for managing tag files inside of bags. These represent the standard
-tag files that are part of every Bag spec or optional tag files which can
-be used liberally throughout the bag itself.
+
For more information on Bag tagfiles see
http://tools.ietf.org/html/draft-kunze-bagit-09#section-2.3
@@ -43,12 +41,14 @@ func NewBag(location string, name string, cs *bagutil.ChecksumAlgorithm) (*Bag,
bag.cs = cs
bag.manifests = make(map[string]*Manifest)
- if err = bag.AddManifest(cs.Name()); err != nil {
+ // Init the manifests map and create the root manifest
+ mf, err := NewManifest(bag.Path(), cs)
+ if err != nil {
return nil, err
}
- bag.tagfiles = make(map[string]*TagFile)
+ bag.manifests[cs.Name()] = mf
- // Make the payload directory and such.
+ // Init the payload directory and such.
plPath := filepath.Join(bag.Path(), "data")
err = os.Mkdir(plPath, 0755)
if err != nil {
@@ -59,7 +59,8 @@ func NewBag(location string, name string, cs *bagutil.ChecksumAlgorithm) (*Bag,
return nil, err
}
- // Create the BagIt.txt Tagfile
+ // Init tagfiles map and create the BagIt.txt Tagfile
+ bag.tagfiles = make(map[string]*TagFile)
tf, err := bag.createBagItFile()
if err != nil {
return nil, err
@@ -84,7 +85,7 @@ func (b *Bag) createBagItFile() (*TagFile, error) {
return bagit, nil
}
-// METHODS FOR MANAGING BAG PAYLOAD
+// METHODS FOR MANAGING BAG PAYLOADS
// Adds a file to the bag payload and adds the generated checksum to the
// manifest.
@@ -115,36 +116,11 @@ func (b *Bag) AddDir(src string) (errs []error) {
// METHODS FOR MANAGING BAG MANIFESTS
-func (b *Bag) AddManifest(algo string) error {
- hsh, err := bagutil.LookupHashFunc(algo)
- if err != nil {
- return err
- }
- cs := bagutil.NewChecksumAlgorithm(algo, hsh)
- if err != nil {
- return err
- }
- mf, err := NewManifest(b.Path(), cs)
- if err != nil {
- return err
- }
- b.manifests[algo] = mf
- return nil
-}
-
-func (b *Bag) ManifestFile(algo string) (*Manifest, error) {
- if mf, ok := b.manifests[algo]; ok {
- return mf, nil
- }
- return nil, fmt.Errorf("Unable to find manifest-%s.txt", algo)
-}
-
func (b *Bag) Manifest() (*Manifest, error) {
- mf, err := b.ManifestFile(b.cs.Name())
- if err != nil {
- return nil, err
+ if mf, ok := b.manifests[b.cs.Name()]; ok {
+ return mf, nil
}
- return mf, nil
+ return nil, fmt.Errorf("Unable to find manifest-%s.txt", b.cs.Name())
}
// METHODS FOR MANAGING BAG TAG FILES
@@ -189,15 +165,10 @@ func (b *Bag) Path() string {
func (b *Bag) Close() (errs []error) {
// Write all the manifest files.
- for key := range b.manifests {
- if mf, err := b.ManifestFile(key); err != nil {
+ for _, mf := range b.manifests {
+ if err := mf.Create(); err != nil {
errs = append(errs, err)
- } else {
- if err = mf.Create(); err != nil {
- errs = append(errs, err)
- }
}
-
}
// TODO Write all the tag files.
diff --git a/tagfile.go b/tagfile.go
index <HASH>..<HASH> 100644
--- a/tagfile.go
+++ b/tagfile.go
@@ -1,11 +1,3 @@
-/*
-Methods for managing tag files inside of bags. These represent the standard
-tag files that are part of every Bag spec or optional tag files which can
-be used liberally throughout the bag itself.
-
-For more information on Bag tagfiles see
-http://tools.ietf.org/html/draft-kunze-bagit-09#section-2.3
-*/
package bagins
import (
|
Simplifying bag manifest methods. Only supporting one manifest.
|
APTrust_bagins
|
train
|
615da249957987b39887eb12abe887ad6c883114
|
diff --git a/lib/rb/lib/thrift/struct.rb b/lib/rb/lib/thrift/struct.rb
index <HASH>..<HASH> 100644
--- a/lib/rb/lib/thrift/struct.rb
+++ b/lib/rb/lib/thrift/struct.rb
@@ -6,7 +6,7 @@ module Thrift
def initialize(d={})
each_field do |fid, type, name, default|
value = d.delete(name.to_s) { d.delete(name.to_sym) { default.dup rescue default } }
- Thrift.check_type(value, type)
+ Thrift.check_type(value, type) if Thrift.type_checking
instance_variable_set("@#{name}", value)
end
raise Exception, "Unknown keys given to #{self.class}.new: #{d.keys.join(", ")}" unless d.empty?
@@ -72,7 +72,7 @@ module Thrift
fields.each do |field|
klass.send :attr_reader, field
klass.send :define_method, "#{field}=" do |value|
- Thrift.check_type(value, klass::FIELDS.values.find { |f| f[:name].to_s == field.to_s }[:type] )
+ Thrift.check_type(value, klass::FIELDS.values.find { |f| f[:name].to_s == field.to_s }[:type] ) if Thrift.type_checking
instance_variable_set("@#{field}", value)
end
end
diff --git a/lib/rb/lib/thrift/types.rb b/lib/rb/lib/thrift/types.rb
index <HASH>..<HASH> 100644
--- a/lib/rb/lib/thrift/types.rb
+++ b/lib/rb/lib/thrift/types.rb
@@ -26,7 +26,7 @@ module Thrift
end
def self.check_type(value, type)
- return unless Thrift.type_checking and not value.nil?
+ return if value.nil?
klasses = case type
when Types::VOID
NilClass
diff --git a/lib/rb/spec/types_spec.rb b/lib/rb/spec/types_spec.rb
index <HASH>..<HASH> 100644
--- a/lib/rb/spec/types_spec.rb
+++ b/lib/rb/spec/types_spec.rb
@@ -47,6 +47,7 @@ class ThriftTypesSpec < Spec::ExampleGroup
end
it "should be disabled when Thrift.type_checking = false" do
+ pending "disabled, parents should check Thrift.type_checking"
Thrift.type_checking = false
lambda { Thrift.check_type(3, Types::STRING) }.should_not raise_error(TypeError)
end
|
rb: Check Thrift.type_checking earlier for a performance boost [THRIFT-<I>]
|
limingxinleo_thrift
|
train
|
cd95433c6cd83224a6c9b6dad79d5f780f2e471f
|
diff --git a/bcbio/variation/annotation.py b/bcbio/variation/annotation.py
index <HASH>..<HASH> 100644
--- a/bcbio/variation/annotation.py
+++ b/bcbio/variation/annotation.py
@@ -79,9 +79,9 @@ def annotate_nongatk_vcf(orig_file, bam_file, dbsnp_file, ref_file, config):
"""
broad_runner = broad.runner_from_config(config)
out_file = "%s-gatkann%s" % os.path.splitext(orig_file)
- annotations = get_gatk_annotations(config)
if not file_exists(out_file):
with file_transaction(out_file) as tx_out_file:
+ annotations = get_gatk_annotations(config)
params = ["-T", "VariantAnnotator",
"-R", ref_file,
"-I", bam_file,
diff --git a/bcbio/variation/genotype.py b/bcbio/variation/genotype.py
index <HASH>..<HASH> 100644
--- a/bcbio/variation/genotype.py
+++ b/bcbio/variation/genotype.py
@@ -38,8 +38,6 @@ def _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp, region, out_file
coverage_depth = config["algorithm"].get("coverage_depth", "high").lower()
variant_regions = config["algorithm"].get("variant_regions", None)
confidence = "4.0" if coverage_depth in ["low"] else "30.0"
- if out_file is None:
- out_file = "%s-variants.vcf" % os.path.splitext(align_bams[0])[0]
region = subset_variant_regions(variant_regions, region, out_file)
params = ["-R", ref_file,
@@ -56,16 +54,18 @@ def _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp, region, out_file
params += ["--dbsnp", dbsnp]
if region:
params += ["-L", bamprep.region_to_gatk(region), "--interval_set_rule", "INTERSECTION"]
- return broad_runner, params, out_file
+ return broad_runner, params
def unified_genotyper(align_bams, ref_file, config, dbsnp=None,
region=None, out_file=None):
"""Perform SNP genotyping on the given alignment file.
"""
- broad_runner, params, out_file = \
- _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp,
- region, out_file)
+ if out_file is None:
+ out_file = "%s-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not file_exists(out_file):
+ broad_runner, params = \
+ _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp,
+ region, out_file)
if (not isinstance(region, (list, tuple)) and
not all(has_aligned_reads(x, region) for x in align_bams)):
write_empty_vcf(out_file)
@@ -83,12 +83,14 @@ def haplotype_caller(align_bams, ref_file, config, dbsnp=None,
This requires the full non open-source version of GATK.
"""
- broad_runner, params, out_file = \
- _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp,
- region, out_file)
- assert broad_runner.gatk_type() == "restricted", \
- "Require full version of GATK 2.4+ for haplotype calling"
+ if out_file is None:
+ out_file = "%s-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not file_exists(out_file):
+ broad_runner, params = \
+ _shared_gatk_call_prep(align_bams, ref_file, config, dbsnp,
+ region, out_file)
+ assert broad_runner.gatk_type() == "restricted", \
+ "Require full version of GATK 2.4+ for haplotype calling"
if not all(has_aligned_reads(x, region) for x in align_bams):
write_empty_vcf(out_file)
else:
|
Avoid extra calls to retrieve GATK version hidden in retrieval of annotation parameters. This speeds up re-runs with large samples
|
bcbio_bcbio-nextgen
|
train
|
1236c9b55473ac6929c2a6ee6bee01487d960253
|
diff --git a/lib/Doctrine/ODM/PHPCR/Mapping/ClassMetadataFactory.php b/lib/Doctrine/ODM/PHPCR/Mapping/ClassMetadataFactory.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/PHPCR/Mapping/ClassMetadataFactory.php
+++ b/lib/Doctrine/ODM/PHPCR/Mapping/ClassMetadataFactory.php
@@ -29,7 +29,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory
/**
* {@inheritdoc}
*/
- protected $cacheSalt = '\$PHPCRODMCLASSMETADATA';
+ protected $cacheSalt = '__PHPCRODMCLASSMETADATA';
/**
* @var DocumentManagerInterface
|
Make cache salt compatible with PSR-<I>
|
doctrine_phpcr-odm
|
train
|
e105ae425e77ad51bf6ac23fb1db65e22c41d439
|
diff --git a/lib/feathers-mongo-databases.js b/lib/feathers-mongo-databases.js
index <HASH>..<HASH> 100644
--- a/lib/feathers-mongo-databases.js
+++ b/lib/feathers-mongo-databases.js
@@ -10,17 +10,25 @@ module.exports = function(db, scope) {
var adminDB = db.admin();
var dbService = {
+
+ setup: function(app) {
+ this.db = db;
+ this.service = app.service.bind(app);
+ },
+
// Scope is either 'server' or 'database'.
// If scope is server, use adminDB, otherwise, it's a single db.
scope:scope,
find: function(params, callback) {
+ console.log('find');
+
var dbList = [];
// Async function to add stats to each db.
function addStats(database, cb){
// If a databaseName is present, it's a single db. No need to switch.
- changeDB = database.databaseName ? database : db.db(database.name);
+ var changeDB = database.databaseName ? database : db.db(database.name);
// Get the stats
changeDB.stats(function(err, stats){
@@ -28,6 +36,11 @@ module.exports = function(db, scope) {
if (stats.collections) {
stats.collections--;
}
+
+ // Add the db name as the _id
+ stats._id = stats.db;
+ stats.name = stats.db;
+
// Rename collections to avoid collisions on the client app.
stats.collectionCount = stats.collections;
delete stats.collections;
@@ -37,14 +50,15 @@ module.exports = function(db, scope) {
});
}
+ // If scope is server, we have multiple database access.
if (scope === 'server') {
// Get a list of all databases on the server.
adminDB.listDatabases(function(err, dbs){
async.each(dbs.databases, addStats, function(err){
if (err) {
- console.log(err)
- callback(err);
+ console.log(err);
+ return callback(err);
} else {
dbList.sort(function(a, b){
return a.db.toLowerCase().localeCompare(b.db.toLowerCase());
@@ -57,30 +71,49 @@ module.exports = function(db, scope) {
// We only have access to one database.
} else {
addStats(db, function(err){
- callback(null, dbList);
+ if (err) {
+ return callback(err);
+ }
+ return callback(null, dbList);
});
}
},
create: function(data, params, callback) {
- console.log(data);
- callback(null, data);
+ if (!data.name) {
+ return callback({error:'name is required'});
+ }
+ db.db(data.name);
+
+ // Create dummy stats. Use the db name as the _id.
+ data = {
+ _id: data.name,
+ db: data.name,
+ objects: 0,
+ avgObjSize: 0,
+ dataSize: 0,
+ storageSize: 0,
+ numExtents: 0,
+ indexes: 0,
+ indexSize: 0,
+ fileSize: 0,
+ nsSizeMB: 0,
+ dataFileVersion: {},
+ ok: 1,
+ collectionCount: 0
+ };
+ return callback(null, data);
},
update: function(id, data, params, callback) {
console.log(data);
- callback(err, data);
+ callback(null, data);
},
remove: function(id, params, callback) {
- console.log(data);
- callback(err, data);
- },
-
- setup: function(app) {
- console.log(path);
- // this.service = app.service.bind(app);
+ console.log(params);
+ callback(null, id);
}
};
|
Can create dbs. find now sets up db name as _id.
|
marshallswain_feathers-mongo-databases
|
train
|
0d409c6352d0f8d5aa320eb92c1e0c9caf7b2a2f
|
diff --git a/src/sos/controller.py b/src/sos/controller.py
index <HASH>..<HASH> 100644
--- a/src/sos/controller.py
+++ b/src/sos/controller.py
@@ -124,7 +124,8 @@ class DotProgressBar:
sys.stderr.flush()
elif self._update_str:
# print update message
- sys.stderr.write(self._update_str)
+ sys.stderr.write('\b \b'*self._pulse_cnt + self._update_str)
+ self._pulse_cnt = 0
sys.stderr.flush()
self.update_event.clear()
@@ -133,30 +134,25 @@ class DotProgressBar:
if time.time() - self._substep_last_updated < 1:
return
if self._substep_cnt == self._subprogressbar_size:
- self._update_str = '\b \b'*(self._pulse_cnt + self._substep_cnt)
+ self._update_str = '\b \b'* self._substep_cnt + '\033[90m.\033[0m'
self._substep_cnt = 0
else:
- self._update_str = '\b \b'*self._pulse_cnt
- self._update_str += '\033[90m.\033[0m'
+ self._update_str = '\033[90m.\033[0m'
self._substep_cnt += 1
- self._pulse_cnt = 0
self._substep_last_updated = time.time()
elif type == 'substep_completed':
if time.time() - self._substep_last_updated < 1:
return
if self._substep_cnt == self._subprogressbar_size:
- self._update_str = '\b \b'*(self._pulse_cnt + self._substep_cnt)
+ self._update_str = '\b \b'* self._substep_cnt + '\033[32m.\033[0m'
self._substep_cnt = 0
else:
- self._update_str = '\b \b'*self._pulse_cnt
- self._update_str += '\033[32m.\033[0m'
+ self._update_str = '\033[32m.\033[0m'
self._substep_cnt += 1
- self._pulse_cnt = 0
self._substep_last_updated = time.time()
elif type == 'step_completed':
- self._update_str = '\b \b'*(self._pulse_cnt + self._substep_cnt)
+ self._update_str = '\b \b'*self._substep_cnt
self._substep_cnt = 0
- self._pulse_cnt = 0
if status == 1: # completed
self._update_str += '\033[32m#\033[0m'
elif status == 0: # completed
@@ -166,7 +162,7 @@ class DotProgressBar:
else: # untracked (no signature)
self._update_str += '\033[33m#\033[0m'
elif type == 'done':
- self._update_str = '\b \b' * (self._pulse_cnt + self._substep_cnt)
+ self._update_str = '\b \b' * self._substep_cnt
self._update_str += f'\033[32m]\033[0m {status}\n'
self.update_event.set()
|
Resolve a possible timing issue of progress bar #<I>
|
vatlab_SoS
|
train
|
ea5edbff50bcb102e0c559adbf7820bc5242e8b1
|
diff --git a/library/CM/Model/Splittest.php b/library/CM/Model/Splittest.php
index <HASH>..<HASH> 100644
--- a/library/CM/Model/Splittest.php
+++ b/library/CM/Model/Splittest.php
@@ -125,11 +125,17 @@ class CM_Model_Splittest extends CM_Model_Abstract {
}
protected function _onDeleteBefore() {
+ if ($this->_withoutPersistence) {
+ return;
+ }
CM_Db_Db::delete('cm_splittestVariation', array('splittestId' => $this->getId()));
CM_Db_Db::delete('cm_splittestVariation_fixture', array('splittestId' => $this->getId()));
}
protected function _onDelete() {
+ if ($this->_withoutPersistence) {
+ return;
+ }
CM_Db_Db::delete('cm_splittest', array('id' => $this->getId()));
}
diff --git a/tests/library/CM/Model/SplittestTest.php b/tests/library/CM/Model/SplittestTest.php
index <HASH>..<HASH> 100644
--- a/tests/library/CM/Model/SplittestTest.php
+++ b/tests/library/CM/Model/SplittestTest.php
@@ -119,6 +119,14 @@ class CM_Model_SplittestTest extends CMTest_TestCase {
CMTest_TH::clearConfig();
}
+
+ public function testWithoutPersistenceDelete() {
+ CM_Config::get()->CM_Model_Splittest->withoutPersistence = true;
+ $test = new CM_Model_Splittest_Mock('foo');
+ $test->delete();
+
+ CMTest_TH::clearConfig();
+ }
}
class CM_Model_Splittest_Mock extends CM_Model_Splittest {
|
Allow to delete splittests in withoutPersistence-mode
|
cargomedia_cm
|
train
|
df5c5b57201515379d4103628ec551aa922e256b
|
diff --git a/lib/swissmatch/communities.rb b/lib/swissmatch/communities.rb
index <HASH>..<HASH> 100644
--- a/lib/swissmatch/communities.rb
+++ b/lib/swissmatch/communities.rb
@@ -61,6 +61,20 @@ module SwissMatch
@by_name[name]
end
+ # @return [SwissMatch::Communities]
+ # A SwissMatch::Communities collection with all SwissMatch::Community objects for which the block
+ # returned true (or a trueish value)
+ def select(*args, &block)
+ Communities.new(@all.select(*args, &block))
+ end
+
+ # @return [SwissMatch::Communities]
+ # A SwissMatch::Communities collection with all SwissMatch::Community objects for which the block
+ # returned false (or a falseish value)
+ def reject(*args, &block)
+ Communities.new(@all.reject(*args, &block))
+ end
+
# @return [Integer] The number of SwissMatch::Community objects in this collection.
def size
@all.size
|
Added SwissMatch::Communities#select and #reject.
|
apeiros_swissmatch-location
|
train
|
95135c95fe888cc5f16a62183147351c14097f51
|
diff --git a/lib/Doctrine/DBAL/Schema/Comparator.php b/lib/Doctrine/DBAL/Schema/Comparator.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/DBAL/Schema/Comparator.php
+++ b/lib/Doctrine/DBAL/Schema/Comparator.php
@@ -178,16 +178,7 @@ class Comparator
}
}
- // Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
- foreach ($tableDifferences->addedColumns AS $addedColumnName => $addedColumn) {
- foreach ($tableDifferences->removedColumns AS $removedColumnName => $removedColumn) {
- if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
- $tableDifferences->renamedColumns[$removedColumn->getName()] = $addedColumn;
- unset($tableDifferences->addedColumns[$addedColumnName]);
- unset($tableDifferences->removedColumns[$removedColumnName]);
- }
- }
- }
+ $this->detectColumnRenamings($tableDifferences);
$table1Indexes = $table1->getIndexes();
$table2Indexes = $table2->getIndexes();
@@ -251,6 +242,34 @@ class Comparator
}
/**
+ * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
+ * however ambiguouties between different possibilites should not lead to renaming at all.
+ *
+ * @param TableDiff $tableDifferences
+ */
+ private function detectColumnRenamings(TableDiff $tableDifferences)
+ {
+ $renameCandidates = array();
+ foreach ($tableDifferences->addedColumns AS $addedColumnName => $addedColumn) {
+ foreach ($tableDifferences->removedColumns AS $removedColumnName => $removedColumn) {
+ if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
+ $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn);
+ }
+ }
+ }
+
+ foreach ($renameCandidates AS $candidate => $candidateColumns) {
+ if (count($candidateColumns) == 1) {
+ list($removedColumn, $addedColumn) = $candidateColumns[0];
+
+ $tableDifferences->renamedColumns[$removedColumn->getName()] = $addedColumn;
+ unset($tableDifferences->addedColumns[$addedColumnName]);
+ unset($tableDifferences->removedColumns[$removedColumnName]);
+ }
+ }
+ }
+
+ /**
* @param ForeignKeyConstraint $key1
* @param ForeignKeyConstraint $key2
* @return bool
diff --git a/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php b/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
+++ b/tests/Doctrine/Tests/DBAL/Schema/ComparatorTest.php
@@ -581,6 +581,33 @@ class ComparatorTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('bar', $tableDiff->renamedColumns['foo']->getName());
}
+ /**
+ * You can easily have ambiguouties in the column renaming. If these
+ * are detected no renaming should take place, instead adding and dropping
+ * should be used exclusively.
+ *
+ * @group DBAL-24
+ */
+ public function testDetectRenameColumnAmbiguous()
+ {
+ $tableA = new Table("foo");
+ $tableA->addColumn('foo', 'integer');
+ $tableA->addColumn('bar', 'integer');
+
+ $tableB = new Table("foo");
+ $tableB->addColumn('baz', 'integer');
+
+ $c = new Comparator();
+ $tableDiff = $c->diffTable($tableA, $tableB);
+
+ $this->assertEquals(1, count($tableDiff->addedColumns), "'baz' should be added, not created through renaming!");
+ $this->assertArrayHasKey('baz', $tableDiff->addedColumns, "'baz' should be added, not created through renaming!");
+ $this->assertEquals(2, count($tableDiff->removedColumns), "'foo' and 'bar' should both be dropped, an ambigouty exists which one could be renamed to 'baz'.");
+ $this->assertArrayHasKey('foo', $tableDiff->removedColumns, "'foo' should be removed.");
+ $this->assertArrayHasKey('bar', $tableDiff->removedColumns, "'bar' should be removed.");
+ $this->assertEquals(0, count($tableDiff->renamedColumns), "no renamings should take place.");
+ }
+
public function testDetectChangeIdentifierType()
{
$this->markTestSkipped('DBAL-2 was reopened, this test cannot work anymore.');
|
DBAL-<I> - Detect ambiguouties in column renamings of the diffTable() method, doing nothing instead
|
doctrine_dbal
|
train
|
aa1ac47220bab3e63c508ad1f1998c5d00e0f4b1
|
diff --git a/Module.php b/Module.php
index <HASH>..<HASH> 100644
--- a/Module.php
+++ b/Module.php
@@ -98,16 +98,15 @@ class Module implements
public function onBootstrap(EventInterface $e)
{
$app = $e->getParam('application');
- $sm = $app->getServiceManager();
- $em = $app->getEventManager();
+ $em = $app->getEventManager();
$em->attach(MvcEvent::EVENT_DISPATCH, array($this, 'selectLayoutBasedOnRoute'));
}
public function selectLayoutBasedOnRoute(MvcEvent $e)
{
- $app = $e->getParam('application');
- $sm = $app->getServiceManager();
+ $app = $e->getParam('application');
+ $sm = $app->getServiceManager();
$config = $sm->get('config');
if (false === $config['zfcadmin']['use_admin_layout']) {
@@ -115,12 +114,11 @@ class Module implements
}
$match = $e->getRouteMatch();
-
if (!$match instanceof RouteMatch || 0 !== strpos($match->getMatchedRouteName(), 'zfcadmin')) {
return;
}
- $layout = $config['zfcadmin']['admin_layout_template'];
+ $layout = $config['zfcadmin']['admin_layout_template'];
$controller = $e->getTarget();
$controller->layout($layout);
}
|
CS issue fixes and removal of obsolete code
|
ZF-Commons_ZfcAdmin
|
train
|
c9f3bb17a49f96b1b3d128074d0194e559a5b51d
|
diff --git a/moban/hashstore.py b/moban/hashstore.py
index <HASH>..<HASH> 100644
--- a/moban/hashstore.py
+++ b/moban/hashstore.py
@@ -60,7 +60,7 @@ def get_file_hash(afile):
def get_hash(content):
md5 = hashlib.md5()
- md5.update(content)
+ md5.update(content.decode('utf-8'))
return md5.digest().decode('latin1')
|
:bug: should handle utf-8 content by default.
|
moremoban_moban
|
train
|
3e1ac2425f3a58a0e4ef06870ee28cb6b8a42d1f
|
diff --git a/package.js b/package.js
index <HASH>..<HASH> 100644
--- a/package.js
+++ b/package.js
@@ -18,9 +18,6 @@ Package.onUse(function (api) {
], 'client');
var scssFiles = [
- 'sass/components/date_picker/_default.date.scss',
- 'sass/components/date_picker/_default.scss',
- 'sass/components/date_picker/_default.time.scss',
'sass/components/forms/_checkboxes.scss',
'sass/components/forms/_file-input.scss',
'sass/components/forms/_forms.scss',
@@ -35,13 +32,14 @@ Package.onUse(function (api) {
'sass/components/_carousel.scss',
'sass/components/_chips.scss',
'sass/components/_collapsible.scss',
- 'sass/components/_color.scss',
+ 'sass/components/_color-classes.scss',
+ 'sass/components/_color-variables.scss',
+ 'sass/components/_datepicker.scss',
'sass/components/_dropdown.scss',
'sass/components/_global.scss',
'sass/components/_grid.scss',
'sass/components/_icons-material-design.scss',
'sass/components/_materialbox.scss',
- 'sass/components/_mixins.scss',
'sass/components/_modal.scss',
'sass/components/_navbar.scss',
'sass/components/_normalize.scss',
@@ -52,6 +50,7 @@ Package.onUse(function (api) {
'sass/components/_table_of_contents.scss',
'sass/components/_tabs.scss',
'sass/components/_tapTarget.scss',
+ 'sass/components/_timepicker.scss',
'sass/components/_toast.scss',
'sass/components/_tooltip.scss',
'sass/components/_transitions.scss',
|
update scss file list in meteor package
|
Dogfalo_materialize
|
train
|
0b1305792535b90b274c7180884e3dfb7fdc0f22
|
diff --git a/y/y.go b/y/y.go
index <HASH>..<HASH> 100644
--- a/y/y.go
+++ b/y/y.go
@@ -134,7 +134,7 @@ func ParseKey(key []byte) []byte {
return nil
}
- AssertTruef(len(key) > 8, "key=%q", key)
+ AssertTrue(len(key) > 8)
return key[:len(key)-8]
}
|
reduce allocations by avoiding AssertTruef (#<I>)
ParseKey is called *a lot*. Unfortunately, AssertTruef converts implicitly the
arguments to interfaces which implicitly allocates. This was showing up as the
primary source of allocations in go-ipfs by a wide margin.
|
dgraph-io_badger
|
train
|
15e26f04e223794e69e7a67436a4445eb1862418
|
diff --git a/tests/test_importer.py b/tests/test_importer.py
index <HASH>..<HASH> 100644
--- a/tests/test_importer.py
+++ b/tests/test_importer.py
@@ -1,5 +1,6 @@
from osmgraph.importer import GraphImporter
+
def test_importer():
gi = GraphImporter()
|
Insert blank line
To appease flake8
|
Mapkin_osmgraph
|
train
|
28a1dbd86c3d04f74bc4d1c8c55ef2600d2358ee
|
diff --git a/dev/com.ibm.ws.microprofile.faulttolerance.2.0_fat_tck/fat/src/com/ibm/ws/microprofile/faulttolerance/tck/FaultToleranceTck20Launcher.java b/dev/com.ibm.ws.microprofile.faulttolerance.2.0_fat_tck/fat/src/com/ibm/ws/microprofile/faulttolerance/tck/FaultToleranceTck20Launcher.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.microprofile.faulttolerance.2.0_fat_tck/fat/src/com/ibm/ws/microprofile/faulttolerance/tck/FaultToleranceTck20Launcher.java
+++ b/dev/com.ibm.ws.microprofile.faulttolerance.2.0_fat_tck/fat/src/com/ibm/ws/microprofile/faulttolerance/tck/FaultToleranceTck20Launcher.java
@@ -10,6 +10,10 @@
*******************************************************************************/
package com.ibm.ws.microprofile.faulttolerance.tck;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.PrintStream;
+
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -18,6 +22,9 @@ import org.junit.runner.RunWith;
import componenttest.annotation.AllowedFFDC;
import componenttest.annotation.Server;
import componenttest.custom.junit.runner.FATRunner;
+import componenttest.custom.junit.runner.Mode;
+import componenttest.custom.junit.runner.Mode.TestMode;
+import componenttest.custom.junit.runner.TestModeFilter;
import componenttest.topology.impl.LibertyServer;
import componenttest.topology.utils.MvnUtils;
@@ -94,9 +101,30 @@ public class FaultToleranceTck20Launcher {
* @throws Exception
*/
@Test
+ @Mode(TestMode.EXPERIMENTAL)
@AllowedFFDC // The tested exceptions cause FFDC so we have to allow for this.
public void launchFaultToleranceTCK() throws Exception {
MvnUtils.runTCKMvnCmd(server, "com.ibm.ws.microprofile.faulttolerance.2.0_fat_tck", this.getClass() + ":launchFaultToleranceTCK");
}
+ @Mode(TestMode.LITE)
+ @Test
+ public void testThatDoesNothingAndCanAlwaysRunAndPass() {
+ if (TestModeFilter.FRAMEWORK_TEST_MODE != TestMode.EXPERIMENTAL) {
+ System.out.println("\n\n\n");
+ System.out.println("TCK MASTER BRANCH RUN NOT REQUESTED: fat.test.mode=" + TestModeFilter.FRAMEWORK_TEST_MODE
+ + ", run with '-Dfat.test.mode=experimental' to run the TCK");
+ System.out.println("\n\n\n");
+ // In FATs System.out is captured to a file, we try to be kind to any developer and give it to them straight
+ if (Boolean.valueOf(System.getProperty("fat.test.localrun"))) {
+ try (PrintStream screen = new PrintStream(new FileOutputStream(FileDescriptor.out))) {
+ screen.println("\n\n\n");
+ screen.println("TCK MASTER BRANCH RUN NOT REQUESTED: fat.test.mode=" + TestModeFilter.FRAMEWORK_TEST_MODE
+ + ", run with '-Dfat.test.mode=experimental' to run the TCK");
+ screen.println("\n\n\n");
+ }
+ }
+ }
+ }
+
}
|
Make TCK only run in experimental mode
It's won't pass until updates are made to the arquillian container to
capture deployment failures correctly.
|
OpenLiberty_open-liberty
|
train
|
1a8e3060b8f6d6362c27903dcfc69d17db5f1d36
|
diff --git a/semantic_release/history/logs.py b/semantic_release/history/logs.py
index <HASH>..<HASH> 100644
--- a/semantic_release/history/logs.py
+++ b/semantic_release/history/logs.py
@@ -106,7 +106,11 @@ def generate_changelog(from_version: str, to_version: str = None) -> dict:
if message[1] not in changes:
continue
- changes[message[1]].append((_hash, message[3][0]))
+ changes[message[1]].append((
+ _hash,
+ # Capitalize the first letter of the message
+ message[3][0][0].upper() + message[3][0][1:]
+ ))
# Handle breaking change message
parts = None
diff --git a/tests/test_history.py b/tests/test_history.py
index <HASH>..<HASH> 100644
--- a/tests/test_history.py
+++ b/tests/test_history.py
@@ -164,6 +164,12 @@ class GenerateChangelogTests(TestCase):
changelog = generate_changelog('0.0.0')
self.assertEqual(changelog['breaking'][0][1], expected_description)
+ def test_messages_are_capitalized(self):
+ with mock.patch('semantic_release.history.logs.get_commit_log',
+ lambda *a, **k: [('23', 'fix(x): abcd')]):
+ changelog = generate_changelog('0.0.0')
+ self.assertEqual(changelog['fix'][0][1], 'Abcd')
+
def test_current_version_should_return_correct_version():
assert get_current_version() == semantic_release.__version__
|
feat(history): capitalize changelog messages
Capitalize the first letter of messages in the changelog regardless of
whether they are capitalized in the commit itself.
|
relekang_python-semantic-release
|
train
|
7b7214333405814f6cdfdc04d66ed164841e0471
|
diff --git a/app/jobs/characterize_job.rb b/app/jobs/characterize_job.rb
index <HASH>..<HASH> 100644
--- a/app/jobs/characterize_job.rb
+++ b/app/jobs/characterize_job.rb
@@ -6,7 +6,7 @@ class CharacterizeJob < Hyrax::ApplicationJob
# @param [String, NilClass] filepath the cached file within the Hyrax.config.working_path
def perform(file_set, file_id, filepath = nil)
filename = Hyrax::WorkingDirectory.find_or_retrieve(file_id, file_set.id, filepath)
- raise LoadError, "#{file_set.class.characterization_proxy} was not found" unless file_set.characterization_proxy?
+ raise "#{file_set.class.characterization_proxy} was not found" unless file_set.characterization_proxy?
Hydra::Works::CharacterizationService.run(file_set.characterization_proxy, filename)
Rails.logger.debug "Ran characterization on #{file_set.characterization_proxy.id} (#{file_set.characterization_proxy.mime_type})"
file_set.characterization_proxy.save!
diff --git a/spec/jobs/characterize_job_spec.rb b/spec/jobs/characterize_job_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/jobs/characterize_job_spec.rb
+++ b/spec/jobs/characterize_job_spec.rb
@@ -29,7 +29,7 @@ RSpec.describe CharacterizeJob do
context 'when the characterization proxy content is absent' do
before { allow(file_set).to receive(:characterization_proxy?).and_return(false) }
it 'raises an error' do
- expect { described_class.perform_now(file_set, file.id) }.to raise_error(LoadError, 'original_file was not found')
+ expect { described_class.perform_now(file_set, file.id) }.to raise_error(StandardError, 'original_file was not found')
end
end
|
Raise StandardError when a data file can't be found
LoadError should be used when loading code, not when a data file doesn't
exist. See <URL>
|
samvera_hyrax
|
train
|
014d05658911c1be980dde1aa58419cf9aea5bde
|
diff --git a/packages/cozy-client/src/CozyClient.js b/packages/cozy-client/src/CozyClient.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/CozyClient.js
+++ b/packages/cozy-client/src/CozyClient.js
@@ -450,7 +450,9 @@ class CozyClient {
// "Included" documents will be stored in the `documents` store
const uniqueDocuments = uniqBy(flatten(documents), '_id')
- const included = flatten(responses.map(r => r.included || r.data))
+ const included = uniqBy(
+ flatten(responses.map(r => r.included || r.data), '_id')
+ )
.concat(uniqueDocuments)
.filter(Boolean)
diff --git a/packages/cozy-client/src/CozyClient.spec.js b/packages/cozy-client/src/CozyClient.spec.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/CozyClient.spec.js
+++ b/packages/cozy-client/src/CozyClient.spec.js
@@ -833,10 +833,6 @@ describe('CozyClient', () => {
{
_id: 'ab794478d016457e99bd6241ff6c0d32',
_type: 'io.cozy.fake'
- },
- {
- _id: 'ab794478d016457e99bd6241ff6c0d32',
- _type: 'io.cozy.fake'
}
]
})
|
fix(client): Make association query responses unique in included 📝
Documents were uniques but not responses from query.
|
cozy_cozy-client
|
train
|
266a8c436760a9990b300da06cbcf81810a0d2c1
|
diff --git a/klab/bio/fragments/post_processing.py b/klab/bio/fragments/post_processing.py
index <HASH>..<HASH> 100644
--- a/klab/bio/fragments/post_processing.py
+++ b/klab/bio/fragments/post_processing.py
@@ -204,15 +204,28 @@ def post_process(task_dir):
glob.glob(os.path.join(task_dir, "*mers.gz"))
for frag_path in frag_paths:
+ frag_match = re.match('(.*)[.](\d+)[.](\d+)mers[.]?(gz)?', frag_path)
+ score_match = re.match('(.*_frags)[.](\d+)[.]score[.](\d+)[.](\d+)mers[.]?(gz)?', frag_path)
+
+ # Kale wanted to change the filename for the scores so that it is
+ # easier to distinguish between score and fragments files using glob.
+ # Do this test first because score files will match the fragment file
+ # pattern.
+
+ if score_match and segment_map:
+ assert score_match.group(2) == score_match.group(4)
+ frag_sizes = int(score_match.group(2))
+ num_fragments = int(score_match.group(3))
+ backup_filepath = '%s.%s.%smers.backup.score.%s' % (score_match.group(1), score_match.group(3), score_match.group(4), score_match.group(5))
+ new_filepath = ('%s.%s.%smers.rewrite.score.%s' % (score_match.group(1), score_match.group(3), score_match.group(4), score_match.group(5))).replace('.gz', '')
+ rewrite_score_file(task_dir, frag_path, backup_filepath, new_filepath, segment_map, frag_sizes, num_fragments)
# Perform any post-processing on the fragment file itself. Keep track
# of the path to the most processed file, which is presumably the file
# the end-user will be the most interested in, so we can record it in a
# JSON file at the end.
- frag_match = re.match('(....)[.](\d+)[.](\d+)mers[.]?(gz)?', os.path.basename(frag_path))
-
- if frag_match:
+ elif frag_match:
processed_path = frag_path
frag_sizes = int(frag_match.group(3))
num_fragments = int(frag_match.group(2))
@@ -220,10 +233,9 @@ def post_process(task_dir):
# If a segment map exists, use it to reindex the fragment file.
if segment_map:
- old_filepath = frag_match.group(0)
backup_filepath = '%s.%s.%smers.backup.%s' % (frag_match.group(1), frag_match.group(2), frag_match.group(3), frag_match.group(4))
new_filepath = ('%s.%s.%smers.rewrite.%s' % (frag_match.group(1), frag_match.group(2), frag_match.group(3), frag_match.group(4))).replace('.gz', '')
- processed_path = rewrite_fragments_file(task_dir, old_filepath, backup_filepath, new_filepath, segment_map, frag_sizes, num_fragments)
+ processed_path = rewrite_fragments_file(task_dir, frag_path, backup_filepath, new_filepath, segment_map, frag_sizes, num_fragments)
# If a secondary structure filter exists, use it to remove any
# fragments that don't have the specified secondary structure.
@@ -239,20 +251,6 @@ def post_process(task_dir):
'num_fragments': num_fragments,
}
- # Kale wanted to change the filename for the scores so that it is
- # easier to distinguish between score and fragments files using glob.
-
- score_match = re.match('(...._frags)[.](\d+)[.]score[.](\d+)[.](\d+)mers[.]?(gz)?', os.path.basename(frag_path))
-
- if score_match and segment_map:
- assert score_match.group(2) == score_match.group(4)
- frag_sizes = int(score_match.group(2))
- num_fragments = int(score_match.group(3))
- old_filepath = score_match.group(0)
- backup_filepath = '%s.%s.%smers.backup.score.%s' % (score_match.group(1), score_match.group(3), score_match.group(4), score_match.group(5))
- new_filepath = ('%s.%s.%smers.rewrite.score.%s' % (score_match.group(1), score_match.group(3), score_match.group(4), score_match.group(5))).replace('.gz', '')
- rewrite_score_file(task_dir, old_filepath, backup_filepath, new_filepath, segment_map, frag_sizes, num_fragments)
-
with open(os.path.join(task_dir, 'fragment_file_map.json'), 'w') as file:
json.dump(frag_libs, file)
|
Make sure score files don't match the fragment file regex.
2nd try.
|
Kortemme-Lab_klab
|
train
|
d7523c4beb54ffdce859854442102d517f625b87
|
diff --git a/example/server.js b/example/server.js
index <HASH>..<HASH> 100644
--- a/example/server.js
+++ b/example/server.js
@@ -48,7 +48,10 @@ app.post('/upload', function(req, res) {
res.contentType('text/html');
// Really should return json when all files have been saved, but we are simplifying things a bit here.
- res.json({files: files.map(function (file) { return file.name; }) });
+ // We also delay it a bit, so we can see the nice loader
+ setTimeout((function() {
+ res.json({files: files.map(function (file) { return file.name; }) });
+ }), 2000);
});
// Fallback route for angular
|
introduce a fake wait in the upload server so we can see an upload spinner or such
|
leon_angular-upload
|
train
|
a613168694fa65f55cdde6097054879fd06d81b5
|
diff --git a/lib/m4dbi/model.rb b/lib/m4dbi/model.rb
index <HASH>..<HASH> 100644
--- a/lib/m4dbi/model.rb
+++ b/lib/m4dbi/model.rb
@@ -8,6 +8,10 @@ module M4DBI
extend Enumerable
+ def self.prepare( sql )
+ st[sql] ||= dbh.prepare(sql)
+ end
+
def self.[]( first_arg, *args )
if args.size == 0
case first_arg
@@ -25,10 +29,9 @@ module M4DBI
values = [ first_arg ] + args
end
- row = dbh.select_one(
- "SELECT * FROM #{table} WHERE #{clause}",
- *values
- )
+ sql = "SELECT * FROM #{table} WHERE #{clause}"
+ stm = prepare(sql)
+ row = stm.select_one(*values)
if row
self.new( row )
@@ -36,9 +39,9 @@ module M4DBI
end
def self.pk_clause
- pk.map { |col|
- "#{col} = ?"
- }.join( ' AND ' )
+ pk.
+ map { |col| "#{col} = ?" }.
+ join( ' AND ' )
end
def self.from_rows( rows )
@@ -55,8 +58,9 @@ module M4DBI
sql = "SELECT * FROM #{table} WHERE #{cond}"
end
+ stm = prepare(sql)
self.from_rows(
- dbh.select_all( sql, *params )
+ stm.select_all(*params)
)
end
@@ -70,16 +74,16 @@ module M4DBI
sql = "SELECT * FROM #{table} WHERE #{cond} LIMIT 1"
end
- row = dbh.select_one( sql, *params )
+ stm = prepare(sql)
+ row = stm.select_one( *params )
if row
self.new( row )
end
end
def self.all
- self.from_rows(
- dbh.select_all( "SELECT * FROM #{table}" )
- )
+ stm = prepare("SELECT * FROM #{table}")
+ self.from_rows( stm.select_all )
end
# TODO: Perhaps we'll use cursors for Model#each.
@@ -88,14 +92,16 @@ module M4DBI
end
def self.one
- row = dbh.select_one( "SELECT * FROM #{table} LIMIT 1" )
+ stm = prepare("SELECT * FROM #{table} LIMIT 1")
+ row = stm.select_one
if row
self.new( row )
end
end
def self.count
- dbh.select_column( "SELECT COUNT(*) FROM #{table}" ).to_i
+ stm = prepare("SELECT COUNT(*) FROM #{table}")
+ stm.select_column.to_i
end
def self.create( hash = {} )
@@ -123,7 +129,8 @@ module M4DBI
else
sql = "INSERT INTO #{table} ( #{cols} ) VALUES ( #{value_placeholders} )"
end
- num_inserted = dbh_.execute( sql, *values ).affected_count
+ stm = prepare(sql)
+ num_inserted = stm.execute(*values).affected_count
if num_inserted > 0
pk_hash = hash.slice( *(
self.pk.map { |pk_col| pk_col.to_sym }
@@ -133,7 +140,7 @@ module M4DBI
self.pk.map { |pk_col| pk_col.to_s }
) )
end
- if not pk_hash.empty?
+ if ! pk_hash.empty?
rec = self.one_where( pk_hash )
else
begin
@@ -200,20 +207,16 @@ module M4DBI
set_clause, set_params = set_hash.to_set_clause
params = set_params + where_params
- dbh.execute(
- "UPDATE #{table} SET #{set_clause} WHERE #{where_clause}",
- *params
- )
+ stm = prepare("UPDATE #{table} SET #{set_clause} WHERE #{where_clause}")
+ stm.execute( *params )
end
def self.update_one( *args )
set_clause, set_params = args[ -1 ].to_set_clause
pk_values = args[ 0..-2 ]
params = set_params + pk_values
- dbh.execute(
- "UPDATE #{table} SET #{set_clause} WHERE #{pk_clause}",
- *params
- )
+ stm = prepare("UPDATE #{table} SET #{set_clause} WHERE #{pk_clause}")
+ stm.execute( *params )
end
# Example:
@@ -408,7 +411,7 @@ module M4DBI
:table => table,
:pk => pk_,
:columns => h.table_schema( table.to_sym ).columns,
- :st => Hash.new,
+ :st => Hash.new, # prepared statements for all queries
} )
meta_def( 'pk_str'.to_sym ) do
diff --git a/lib/m4dbi/statement.rb b/lib/m4dbi/statement.rb
index <HASH>..<HASH> 100644
--- a/lib/m4dbi/statement.rb
+++ b/lib/m4dbi/statement.rb
@@ -13,7 +13,7 @@ module M4DBI
end
def select_one( *bindvars )
- @st.select( *bindvars )[0]
+ select( *bindvars )[0]
end
def select_column( *bindvars )
diff --git a/lib/m4dbi/version.rb b/lib/m4dbi/version.rb
index <HASH>..<HASH> 100644
--- a/lib/m4dbi/version.rb
+++ b/lib/m4dbi/version.rb
@@ -1,3 +1,3 @@
module M4DBI
- VERSION = '0.7.3'
+ VERSION = '0.8.0'
end
|
Many conversions to use prepared statements in models. Not done yet.
|
Pistos_m4dbi
|
train
|
75d754a561cd13193fca8b560a1d67408b398110
|
diff --git a/commands/command_push.go b/commands/command_push.go
index <HASH>..<HASH> 100644
--- a/commands/command_push.go
+++ b/commands/command_push.go
@@ -1,6 +1,7 @@
package commands
import (
+ "fmt"
"io/ioutil"
"os"
@@ -43,10 +44,23 @@ func uploadsBetweenRefAndRemote(remote string, refs []string) *lfs.TransferQueue
if pushAll {
if len(refs) == 0 {
// no ref given as an arg, so scan all refs
- pointers, err := lfs.ScanRefs("", "", scanOpt)
+ opts := &lfs.ScanRefsOptions{ScanMode: lfs.ScanAllMode, SkipDeletedBlobs: false}
+ // This could be a long process so use the chan version & report progress
+ Print("Scanning for all objects ever referenced...")
+ spinner := lfs.NewSpinner()
+ var numObjs int64
+ pointerchan, err := lfs.ScanRefsToChan("", "", opts)
if err != nil {
- Panic(err, "Error scanning for all Git LFS files")
+ Panic(err, "Could not scan for Git LFS files")
}
+ pointers := make([]*lfs.WrappedPointer, 0)
+ for p := range pointerchan {
+ numObjs++
+ spinner.Print(OutputWriter, fmt.Sprintf("%d objects found", numObjs))
+ pointers = append(pointers, p)
+ }
+ spinner.Finish(OutputWriter, fmt.Sprintf("%d objects found", numObjs))
+ Print("Pushing objects...")
return uploadPointers(pointers)
} else {
scanOpt.ScanMode = lfs.ScanRefsMode
|
use the channel scanner when pushing ALL objects
|
git-lfs_git-lfs
|
train
|
2dff41167908da983a23a2eebe82fa6624b4f0b4
|
diff --git a/terraform/state.go b/terraform/state.go
index <HASH>..<HASH> 100644
--- a/terraform/state.go
+++ b/terraform/state.go
@@ -2,7 +2,10 @@ package terraform
import (
"bytes"
+ "encoding/gob"
+ "errors"
"fmt"
+ "io"
"sync"
"github.com/hashicorp/terraform/config"
@@ -38,6 +41,50 @@ func (s *State) String() string {
return buf.String()
}
+// The format byte is prefixed into the state file format so that we have
+// the ability in the future to change the file format if we want for any
+// reason.
+const stateFormatByte byte = 1
+
+// ReadState reads a state structure out of a reader in the format that
+// was written by WriteState.
+func ReadState(src io.Reader) (*State, error) {
+ var result *State
+
+ var formatByte [1]byte
+ n, err := src.Read(formatByte[:])
+ if err != nil {
+ return nil, err
+ }
+ if n != len(formatByte) {
+ return nil, errors.New("failed to read state version byte")
+ }
+
+ if formatByte[0] != stateFormatByte {
+ return nil, fmt.Errorf("unknown state file version: %d", formatByte[0])
+ }
+
+ dec := gob.NewDecoder(src)
+ if err := dec.Decode(&result); err != nil {
+ return nil, err
+ }
+
+ return result, nil
+}
+
+// WriteState writes a state somewhere in a binary format.
+func WriteState(d *State, dst io.Writer) error {
+ n, err := dst.Write([]byte{stateFormatByte})
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ return errors.New("failed to write state version byte")
+ }
+
+ return gob.NewEncoder(dst).Encode(d)
+}
+
// ResourceState holds the state of a resource that is used so that
// a provider can find and manage an existing resource as well as for
// storing attributes that are uesd to populate variables of child
diff --git a/terraform/state_test.go b/terraform/state_test.go
index <HASH>..<HASH> 100644
--- a/terraform/state_test.go
+++ b/terraform/state_test.go
@@ -1,6 +1,7 @@
package terraform
import (
+ "bytes"
"reflect"
"testing"
@@ -64,3 +65,27 @@ func TestResourceState_MergeDiff_nil(t *testing.T) {
t.Fatalf("bad: %#v", rs2.Attributes)
}
}
+
+func TestReadWriteState(t *testing.T) {
+ state := &State{
+ Resources: map[string]*ResourceState{
+ "foo": &ResourceState{
+ ID: "bar",
+ },
+ },
+ }
+
+ buf := new(bytes.Buffer)
+ if err := WriteState(state, buf); err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ actual, err := ReadState(buf)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if !reflect.DeepEqual(actual, state) {
+ t.Fatalf("bad: %#v", actual)
+ }
+}
|
terraform: read/write state to reader/writer
|
hashicorp_terraform
|
train
|
e891b1ba34239642e0f35639bf928595123bf2c8
|
diff --git a/programs/BuildDatabase.php b/programs/BuildDatabase.php
index <HASH>..<HASH> 100644
--- a/programs/BuildDatabase.php
+++ b/programs/BuildDatabase.php
@@ -13,7 +13,13 @@ use CarbonPHP\interfaces\iCommand;
class BuildDatabase implements iCommand
{
- use MySQL;
+ use MySQL {
+ cleanUp as removeFiles;
+ }
+
+ public function cleanUp($argv) : void {
+ $this->removeFiles();
+ }
public function usage() : void
{
diff --git a/programs/Rest.php b/programs/Rest.php
index <HASH>..<HASH> 100755
--- a/programs/Rest.php
+++ b/programs/Rest.php
@@ -22,7 +22,7 @@ class Rest implements iCommand
public function cleanUp($argv)
{
- $this->cleanUp and $this->removeFiles($argv);
+ $this->cleanUp and $this->removeFiles();
}
public function usage(): void
|
Update interface, moving to php <I>
|
RichardTMiles_CarbonPHP
|
train
|
c64e3654d7ddced5ab589e85656ecf7a32b44b90
|
diff --git a/pptx/parts/image.py b/pptx/parts/image.py
index <HASH>..<HASH> 100644
--- a/pptx/parts/image.py
+++ b/pptx/parts/image.py
@@ -184,10 +184,10 @@ class _ImageCollection(_PartCollection):
return existing_image
# otherwise add it to collection and return new image
self._values.append(image)
- self.__rename_images()
+ self._rename_images()
return image
- def __rename_images(self):
+ def _rename_images(self):
"""
Assign partnames like ``/ppt/media/image9.png`` to all images in the
collection. The name portion is always ``image``. The number part
|
reorg: image.py leading dunderscores to single
|
scanny_python-pptx
|
train
|
90744b3196958f7a61ac60abbce4bb329de9cb82
|
diff --git a/js/scheduler.js b/js/scheduler.js
index <HASH>..<HASH> 100644
--- a/js/scheduler.js
+++ b/js/scheduler.js
@@ -576,11 +576,11 @@
if (recur.BYDAY === 'MO,TU,WE,TH,FR') {
item = 'weekdays';
} else {
- item = this.$element.find('.repeat-days-of-the-week .btn-group');
- item.find('label').removeClass('active');
+ var el = this.$element.find('.repeat-days-of-the-week .btn-group');
+ el.find('label').removeClass('active');
temp = recur.BYDAY.split(',');
for (i = 0, l = temp.length; i < l; i++) {
- item.find('input[data-value="' + temp[i] + '"]').prop('checked',true).parent().addClass('active');
+ el.find('input[data-value="' + temp[i] + '"]').prop('checked',true).parent().addClass('active');
}
}
}
|
Item variable shouldn't be used for multiple purposes
|
ExactTarget_fuelux
|
train
|
66755430f4937c06744f36aa6e95ff1800754cb4
|
diff --git a/cassiopeia/type/core/staticdata.py b/cassiopeia/type/core/staticdata.py
index <HASH>..<HASH> 100644
--- a/cassiopeia/type/core/staticdata.py
+++ b/cassiopeia/type/core/staticdata.py
@@ -757,6 +757,9 @@ class ItemStats(cassiopeia.type.core.common.CassiopeiaObject):
def __init__(self, data, scraped_stats={}):
super().__init__(data)
+ for k,v in scraped_stats.items():
+ if 'percent' in k and v > 1.0:
+ scraped_stats[k] = v/100.0
self.__scraped_stats = scraped_stats
def __str__(self):
|
minor fix to %s for item stats so they return fractional values more consistently rather than percents
|
meraki-analytics_cassiopeia
|
train
|
f78f1761c17b474a227b028da215571c5af7390e
|
diff --git a/aiotg/bot.py b/aiotg/bot.py
index <HASH>..<HASH> 100644
--- a/aiotg/bot.py
+++ b/aiotg/bot.py
@@ -8,7 +8,6 @@ import aiohttp
from aiohttp import web
import json
-from functools import partialmethod
from . chat import Chat, Sender
from . reloader import run_with_reloader
@@ -365,8 +364,6 @@ class Bot:
url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path)
return self.session.get(url, headers=headers)
- _get_user_profile_photos = partialmethod(api_call, "getUserProfilePhotos")
-
def get_user_profile_photos(self, user_id, **options):
"""
Get a list of profile pictures for a user
@@ -375,7 +372,8 @@ class Bot:
:param options: Additional getUserProfilePhotos options (see
https://core.telegram.org/bots/api#getuserprofilephotos)
"""
- return self._get_user_profile_photos(
+ return self.api_call(
+ "getUserProfilePhotos",
user_id=str(user_id),
**options
)
diff --git a/aiotg/chat.py b/aiotg/chat.py
index <HASH>..<HASH> 100644
--- a/aiotg/chat.py
+++ b/aiotg/chat.py
@@ -1,6 +1,5 @@
import json
import logging
-from functools import partialmethod
logger = logging.getLogger("aiotg")
@@ -69,13 +68,6 @@ class Chat:
reply_markup=json.dumps(markup)
)
- def _send_to_chat(self, method, **options):
- return self.bot.api_call(
- method,
- chat_id=str(self.id),
- **options
- )
-
def get_chat(self):
"""
Get information about the chat.
@@ -115,7 +107,20 @@ class Chat:
user_id=str(user_id)
)
- send_sticker = partialmethod(_send_to_chat, "sendSticker")
+ def send_sticker(self, sticker, **options):
+ """
+ Send a sticker to the chat.
+
+ :param sticker: Sticker to send (file or string)
+ :param options: Additional sendSticker options (see
+ https://core.telegram.org/bots/api#sendsticker)
+ """
+ return self.bot.api_call(
+ "sendSticker",
+ chat_id=str(self.id),
+ sticker=sticker,
+ **options
+ )
def send_audio(self, audio, **options):
"""
diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py
index <HASH>..<HASH> 100644
--- a/tests/test_callbacks.py
+++ b/tests/test_callbacks.py
@@ -173,6 +173,9 @@ def test_send_methods():
chat.send_photo(b"foo")
assert "sendPhoto" in bot.calls
+ chat.send_sticker(b"foo")
+ assert "sendSticker" in bot.calls
+
chat.send_video(b"foo")
assert "sendVideo" in bot.calls
|
Cleanup occurances of partialmethod
|
szastupov_aiotg
|
train
|
f400a6fc40778a431d9b7141c9627ceebc0e5593
|
diff --git a/src/scripts/build/cli.js b/src/scripts/build/cli.js
index <HASH>..<HASH> 100644
--- a/src/scripts/build/cli.js
+++ b/src/scripts/build/cli.js
@@ -13,7 +13,7 @@ const copyFiles = args.includes("--no-copy-files") ? [] : ["--copy-files"];
const config = ["--presets", here("../../config/babelrc.js")];
-const ignore = ["--ignore", ".test.js,__mocks__"];
+const ignore = ["--ignore", ".test.js"];
const result = spawn.sync(
resolveBin("babel-cli", { executable: "babel" }),
|
FIX: Excluding mocks from CLI-style build means needed mocks are not included in this package.
|
Orckestra_orc-scripts
|
train
|
7ae507d86c1c8ef878c0a841a3d004cceb304918
|
diff --git a/src/layer/FrameStatisticsLayer.js b/src/layer/FrameStatisticsLayer.js
index <HASH>..<HASH> 100644
--- a/src/layer/FrameStatisticsLayer.js
+++ b/src/layer/FrameStatisticsLayer.js
@@ -89,7 +89,7 @@ define([
}
var frameStats = worldWindow.frameStatistics;
- this.frameTime.text = "Frame time " + frameStats.frameTimeAverage.toFixed(0) + " ms (" + frameStats.frameTimeMin + " - " + frameStats.frameTimeMax + ")";
+ this.frameTime.text = "Frame time " + frameStats.frameTimeAverage.toFixed(0) + " ms (" + frameStats.frameTimeMin.toFixed(0) + " - " + frameStats.frameTimeMax.toFixed(0) + ")";
this.frameRate.text = "Frame rate " + frameStats.frameRateAverage.toFixed(0) + " fps";
};
|
Corrected the frame time text formatting in FrameStatisticsLayer.
|
NASAWorldWind_WebWorldWind
|
train
|
b607e7b669b8d1a17969e9a157ebdabb3deb9420
|
diff --git a/externs/browser/webgl.js b/externs/browser/webgl.js
index <HASH>..<HASH> 100644
--- a/externs/browser/webgl.js
+++ b/externs/browser/webgl.js
@@ -3368,3 +3368,31 @@ ANGLE_instanced_arrays.prototype.drawElementsInstancedANGLE = function(
ANGLE_instanced_arrays.prototype.vertexAttribDivisorANGLE = function(
index, divisor) {};
+
+/**
+ * @see https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_half_float/
+ * @interface
+ */
+function EXT_color_buffer_half_float() {}
+
+/** @const {number} */
+EXT_color_buffer_half_float.prototype.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT;
+
+/** @const {number} */
+EXT_color_buffer_half_float.prototype.RGB16F_EXT;
+
+/** @const {number} */
+EXT_color_buffer_half_float.prototype.RGBA16F_EXT;
+
+/** @const {number} */
+EXT_color_buffer_half_float.prototype.UNSIGNED_NORMALIZED_EXT;
+
+
+/**
+ * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/
+ * @interface
+ */
+function WEBGL_compressed_texture_etc1() {}
+
+/** @const {number} */
+WEBGL_compressed_texture_etc1.prototype.COMPRESSED_RGB_ETC1_WEBGL;
|
Add EXT_color_buffer_half_float and WEBGL_compressed_texture_etc1 to externs
TypeScript <I> added the WebGL extensions EXT_color_buffer_half_float and WEBGL_compressed_texture_etc1 to its standard lib.dom.d.ts typings. This adds the same to the default JavaScript externs.
PiperOrigin-RevId: <I>
|
google_closure-compiler
|
train
|
cbfb04d1ea112ad0e2f41d0d3533b49a1f809210
|
diff --git a/src/Protocol/Packets/StatusResponsePacket.php b/src/Protocol/Packets/StatusResponsePacket.php
index <HASH>..<HASH> 100644
--- a/src/Protocol/Packets/StatusResponsePacket.php
+++ b/src/Protocol/Packets/StatusResponsePacket.php
@@ -102,15 +102,17 @@ class StatusResponsePacket extends ClientboundPacket {
* Expects format:
* <code>
* [
- * {
+ * [
* 'name': 'name',
* 'id': 'uuid'
- * },
- * {
+ * ],
+ * [
* ... another one e.t.c. ...
- * }
+ * ]
* ]
* </code>
+ * UUID is the player UUID with the - included, doesn't look like it's validated so you can use 000000000000-0000-0000-0000-00000000 if you want.
+ *
* @param array $online_players list of online player names.
* @return StatusResponsePacket
*/
|
added the documentation about the UUID value
|
Eluinhost_minecraft-auth
|
train
|
5f23cb5d076cccfabb80ec28c8b1d99a19014077
|
diff --git a/djcelery/admin.py b/djcelery/admin.py
index <HASH>..<HASH> 100644
--- a/djcelery/admin.py
+++ b/djcelery/admin.py
@@ -19,6 +19,7 @@ from celery.utils import abbrtask
from djcelery import loaders
from djcelery.models import TaskState, WorkerState
from djcelery.models import PeriodicTask, IntervalSchedule, CrontabSchedule
+from djcelery.utils import naturaldate
TASK_STATE_COLORS = {states.SUCCESS: "green",
@@ -77,6 +78,10 @@ def eta(task):
return """<span style="color: gray;">none</span>"""
return escape(task.eta)
+@display_field(_("when"), "tstamp")
+def tstamp(task):
+ return naturaldate(task.tstamp)
+
@display_field(_("name"), "name")
def name(task):
@@ -135,7 +140,7 @@ class TaskMonitor(ModelMonitor):
fieldsets = (
(None, {
"fields": ("state", "task_id", "name", "args", "kwargs",
- "eta", "runtime", "worker"),
+ "eta", "runtime", "worker", "tstamp"),
"classes": ("extrapretty", ),
}),
("Details", {
@@ -149,10 +154,11 @@ class TaskMonitor(ModelMonitor):
fixedwidth("args", pretty=True),
fixedwidth("kwargs", pretty=True),
eta,
+ tstamp,
"worker")
readonly_fields = ("state", "task_id", "name", "args", "kwargs",
"eta", "runtime", "worker", "result", "traceback",
- "expires")
+ "expires", "tstamp")
list_filter = ("state", "name", "tstamp", "eta", "worker")
search_fields = ("name", "task_id", "args", "kwargs", "worker__hostname")
actions = ["revoke_tasks",
diff --git a/djcelery/models.py b/djcelery/models.py
index <HASH>..<HASH> 100644
--- a/djcelery/models.py
+++ b/djcelery/models.py
@@ -260,8 +260,7 @@ class TaskState(models.Model):
max_length=36, unique=True)
name = models.CharField(_(u"name"),
max_length=200, null=True)
- tstamp = models.DateTimeField(_(u"event received at"),
- editable=False)
+ tstamp = models.DateTimeField(_(u"event received at"))
args = models.CharField(_(u"Arguments"),
max_length=200, null=True)
kwargs = models.CharField(_(u"Keyword arguments"),
|
Admin monitor: Show timestamp in task list
|
celery_django-celery
|
train
|
e7ae5a5b195340acf27ffa72a2e28eaf82704c63
|
diff --git a/daemon/cmd/daemon_main.go b/daemon/cmd/daemon_main.go
index <HASH>..<HASH> 100644
--- a/daemon/cmd/daemon_main.go
+++ b/daemon/cmd/daemon_main.go
@@ -1706,7 +1706,7 @@ func initKubeProxyReplacementOptions() {
if strict {
log.Fatal(msg)
} else {
- log.Warn(fmt.Sprintf("%s. Disabling the feature.", msg))
+ log.Warnf("%s. Disabling the feature.", msg)
option.Config.EnableSessionAffinity = false
}
|
daemon: Simplify logging
|
cilium_cilium
|
train
|
e2fc5013827433c110f813074da09d2c92150b7c
|
diff --git a/config/config.go b/config/config.go
index <HASH>..<HASH> 100644
--- a/config/config.go
+++ b/config/config.go
@@ -22,6 +22,8 @@ var Config = struct {
DB struct {
Name string `default:"qor_example"`
Adapter string `default:"mysql"`
+ Host string `default:"localhost"`
+ Port string `default:"3306"`
User string
Password string
}
diff --git a/db/db.go b/db/db.go
index <HASH>..<HASH> 100644
--- a/db/db.go
+++ b/db/db.go
@@ -26,7 +26,7 @@ func init() {
dbConfig := config.Config.DB
if config.Config.DB.Adapter == "mysql" {
- DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%v@/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Name))
+ DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name))
} else if config.Config.DB.Adapter == "postgres" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgres://%v:%v@localhost/%v?sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Name))
} else if config.Config.DB.Adapter == "sqlite" {
|
Connect to remote mysql server
|
qor_qor-example
|
train
|
90de97339a30f254ee6a61956ff8ce10bc823905
|
diff --git a/source/P/Application.php b/source/P/Application.php
index <HASH>..<HASH> 100644
--- a/source/P/Application.php
+++ b/source/P/Application.php
@@ -42,14 +42,12 @@ class Application implements \ArrayAccess
$arg1 = func_get_arg(0);
if (is_array($arg1)) {
$configuration = new Configuration($arg1);
- $this->bootstrapBaseServices(array('Configuration' => $configuration));
+ $this->bootstrapBaseServices(new ServiceLocator(array('Configuration' => $configuration)));
} elseif ($arg1 instanceof ServiceLocator) {
$this->bootstrapBaseServices($arg1);
} elseif (!$arg1 instanceof Configuration) {
throw new \InvalidArgumentException('An array or Configuration object is required');
}
-
-
}
protected function bootstrapBaseServices(ServiceLocator $sl)
@@ -60,10 +58,7 @@ class Application implements \ArrayAccess
$this->applicationState = new ApplicationState($sl);
// router
- $router = (!$sl->has('Router')) ? $sl->get('Router') : new Router;
- $router = new Router(new Router\RouteStack);
- $sl->set('Router', $router);
-
+ $router = ($sl->has('Router')) ? $sl->get('Router') : ($sl->set('Router', new Router)->get('Router'));
$routerSource = $router->getSource();
$sl->set('RouterSource', $routerSource);
@@ -95,7 +90,7 @@ class Application implements \ArrayAccess
}
/**
- * @return void
+ * @return $this
*/
public function initialize()
{
|
Updated Router service wiring for injectability
|
pframework_p
|
train
|
a30f460b028048f78a3ec89cb25618fbff507c15
|
diff --git a/TYPO3.Neos/Resources/Public/JavaScript/Content/Navigate/AbstractNodeTree.js b/TYPO3.Neos/Resources/Public/JavaScript/Content/Navigate/AbstractNodeTree.js
index <HASH>..<HASH> 100644
--- a/TYPO3.Neos/Resources/Public/JavaScript/Content/Navigate/AbstractNodeTree.js
+++ b/TYPO3.Neos/Resources/Public/JavaScript/Content/Navigate/AbstractNodeTree.js
@@ -911,7 +911,7 @@ define(
refresh: function() {
var node = this.$nodeTree.dynatree('getRoot').getChildren()[0];
node.removeChildren();
- this.loadNode(node, 0);
+ this.loadNode(node, this.get('loadingDepth'));
},
/**
|
TASK: Use loadingDepth in refresh()
When the (abstract) tree was refreshed, it would always load nodes without
any depth limitation, even though the initial load observes the loadingDepth
setting.
This is not an issue with the navigation tree, since that never uses refresh
but does it's own (filtered) loading.
Now the refresh function uses the configured loadingDepth.
|
neos_neos-development-collection
|
train
|
369786b00918e935e776d81c656edf1bd36c4285
|
diff --git a/lib/fluent/plugin/buf_file.rb b/lib/fluent/plugin/buf_file.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/buf_file.rb
+++ b/lib/fluent/plugin/buf_file.rb
@@ -83,6 +83,7 @@ module Fluent
end
config_param :buffer_path, :string
+ config_param :flush_at_shutdown, :bool, :default => false
# 'symlink_path' is currently only for out_file.
# That is the reason why this is not config_param, but attr_accessor.
@@ -106,11 +107,6 @@ module Fluent
@buffer_path_suffix = ".log"
end
- if conf['flush_at_shutdown']
- @flush_at_shutdown = true
- else
- @flush_at_shutdown = false
- end
end
def start
|
configure flush_at_shutdown properly for buf_file
|
fluent_fluentd
|
train
|
1ad5e8debfa755a2ef1eb1e173af307125339caf
|
diff --git a/src/com/google/javascript/jscomp/ClosureCodingConvention.java b/src/com/google/javascript/jscomp/ClosureCodingConvention.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/ClosureCodingConvention.java
+++ b/src/com/google/javascript/jscomp/ClosureCodingConvention.java
@@ -87,6 +87,8 @@ public class ClosureCodingConvention extends DefaultCodingConvention {
} else if (callNode.getChildCount() == 3) {
// goog.inherits(SubClass, SuperClass)
subclass = callName.getNext();
+ } else {
+ return null;
}
if (type == SubclassType.MIXIN) {
diff --git a/test/com/google/javascript/jscomp/ClosureCodingConventionTest.java b/test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
+++ b/test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
@@ -145,6 +145,10 @@ public class ClosureCodingConventionTest extends TestCase {
assertNotClassDefining("goog.mixin(A, B)");
}
+ public void testInheritanceDetection14() {
+ assertNotClassDefining("goog$mixin((function(){}).prototype)");
+ }
+
public void testInheritanceDetectionPostCollapseProperties() {
assertDefinesClasses("goog$inherits(A, B);", "A", "B");
assertNotClassDefining("goog$inherits(A);");
|
fix an NPE
R=acleung
DELTA=6 (6 added, 0 deleted, 0 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=<I>
git-svn-id: <URL>
|
google_closure-compiler
|
train
|
74fb45b53e8ab09ba3a970d36f4ade2da0053047
|
diff --git a/prospector/tools/mypy/__init__.py b/prospector/tools/mypy/__init__.py
index <HASH>..<HASH> 100644
--- a/prospector/tools/mypy/__init__.py
+++ b/prospector/tools/mypy/__init__.py
@@ -3,6 +3,7 @@ from __future__ import absolute_import
from mypy import api
+from prospector.message import Location, Message
from prospector.tools import ToolBase
@@ -16,7 +17,30 @@ class MypyTool(ToolBase):
def __init__(self, *args, **kwargs):
super(MypyTool, self).__init__(*args, **kwargs)
self.checker = api
+ self.options = ['--show-column-numbers']
def run(self, found_files):
- import pdb ; pdb.set_trace()
- mypy = self.checker.run(found_files)
\ No newline at end of file
+ paths = [path for path in found_files.iter_module_paths()]
+ paths.extend(self.options)
+ report, err, status = self.checker.run(paths)
+ messages = []
+
+ for message in report.splitlines():
+ path, line, char, err_type, *err_msg = message.split(':')
+ location = Location(
+ path=path,
+ module=None,
+ function=None,
+ line=line,
+ character=char,
+ absolute_path=True
+ )
+ message = Message(
+ source='mypy',
+ code=err_type,
+ location=location,
+ message=''.join(err_msg).strip()
+ )
+ messages.append(message)
+
+ return messages
\ No newline at end of file
|
Format mypy messages into proper prospector messages
|
PyCQA_prospector
|
train
|
12623a8ccf2ef59aa9b85401e753f8a266175665
|
diff --git a/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java b/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java
+++ b/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java
@@ -36,7 +36,14 @@ import com.google.gwt.dev.util.Util;
@LinkerOrder(Order.PRIMARY)
public class MinimalLinker extends AbstractLinker {
- private static final String PREFIX = "(function(){var $wnd=this;var $doc={};";
+ /*
+ * Call gwtLoad as per the normal GWT linker (provided in {@code ModuleUtils}), this is in order
+ * to invoke the {@code onModuleLoad} methods of loaded modules. The gwtOnLoad method then sets
+ * {@code $moduleName} and {@code $moduleBase}, shadow them here so they don't leak into the
+ * global scope.
+ */
+ private static final String PREFIX =
+ "(function(){var $wnd=this; var $doc={}; var $moduleName, $moduleBase;";
private static final String SUFFIX = "typeof gwtOnLoad==='function'&&gwtOnLoad()})();";
@Override
|
Update MinimalLinker to shadow some variables emitted by ModuleUtils. Add
explanation of the prefix/suffix changes.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
9c7a1a31f2288ad90fcff58e43dde2be3c433bab
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -23,6 +23,7 @@ Version 1.1.16 under development
- Bug #2778: Fixed throwing unnecessary exception in CFileValidator when validating MIME types for a file upload that failed (Rupert-RR)
- Bug #2785: Use table name with schema in composeMultipleInsertCommand (nineinchnick)
- Bug #2836: Fixed rendering when try-catching widget Exception while 'captureOutput' is set to true (darkheir)
+- Bug #2845: Fixed 1.1.14 regression affecting non-strict comparison in `CRangeValidator` validator (samdark)
- Bug #2855: Fixed issue with Component::__call() and normal properties holding a Closure (cebe)
- Bug #2862: Fixed array_merge caused renumbering of $data indexes in CHtml::radioButtonList() (ligser)
- Bug #2864: Fixed CGridView ajax calls failing CSRF validation when ajaxType is set to POST (nineinchnick)
diff --git a/framework/validators/CRangeValidator.php b/framework/validators/CRangeValidator.php
index <HASH>..<HASH> 100644
--- a/framework/validators/CRangeValidator.php
+++ b/framework/validators/CRangeValidator.php
@@ -59,7 +59,7 @@ class CRangeValidator extends CValidator
{
foreach($this->range as $r)
{
- $result=(strcmp($r,$value)===0);
+ $result = $r === '' || $value === '' ? $r === $value : $r == $value;
if($result)
break;
}
diff --git a/tests/framework/validators/CRangeValidatorTest.php b/tests/framework/validators/CRangeValidatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/framework/validators/CRangeValidatorTest.php
+++ b/tests/framework/validators/CRangeValidatorTest.php
@@ -32,4 +32,31 @@ class CRangeValidatorTest extends CTestCase
$this->assertArrayNotHasKey('string1', $model->getErrors());
$this->assertArrayHasKey('string2', $model->getErrors());
}
+
+ /**
+ * https://github.com/yiisoft/yii/issues/2845
+ */
+ public function testNonStrict()
+ {
+ $comparisons = array(
+ array(1, true),
+ array('1', true),
+ array(' 1', true),
+ array('1 ', true),
+ array(2, false),
+ array(12, false),
+ );
+
+ foreach ($comparisons as $comparison) {
+ $model = new ValidatorTestModel('CRangeValidatorTest');
+ $model->string3 = $comparison[0];
+ $model->validate(array('string3'));
+
+ if ($comparison[1]) {
+ $this->assertArrayNotHasKey('string3', $model->getErrors(), var_export($comparison[0], true) . ' should be valid but it is not.');
+ } else {
+ $this->assertArrayHasKey('string3', $model->getErrors(), var_export($comparison[0], true) . ' should not be valid but it is.');
+ }
+ }
+ }
}
diff --git a/tests/framework/validators/ValidatorTestModel.php b/tests/framework/validators/ValidatorTestModel.php
index <HASH>..<HASH> 100644
--- a/tests/framework/validators/ValidatorTestModel.php
+++ b/tests/framework/validators/ValidatorTestModel.php
@@ -37,6 +37,7 @@ class ValidatorTestModel extends CFormModel
array('string1', 'in', 'allowEmpty' => false, 'range' => array(0,1,7,13), 'on' => 'CRangeValidatorTest'),
array('string2', 'in', 'allowEmpty' => false, 'range' => array('',1,7,13), 'on' => 'CRangeValidatorTest'),
+ array('string3', 'in', 'allowEmpty' => false, 'range' => array(1), 'on' => 'CRangeValidatorTest', 'strict' => false),
array('uploaded_file', 'file', 'on' => 'CFileValidatorTest'),
);
|
Fixes #<I>: Fixed <I> regression affecting non-strict comparison in `CRangeValidator` validator
|
yiisoft_yii
|
train
|
f78b5a134773c05b3066a0de2f8445fbb24d5c56
|
diff --git a/pymzn/_mzn/_solvers.py b/pymzn/_mzn/_solvers.py
index <HASH>..<HASH> 100644
--- a/pymzn/_mzn/_solvers.py
+++ b/pymzn/_mzn/_solvers.py
@@ -193,7 +193,7 @@ class Gecode(Solver):
args.append(parallel)
if timeout > 0:
args.append('-time')
- args.append(int(timeout * 1000)) # Gecode takes milliseconds
+ args.append(str(timeout * 1000)) # Gecode takes milliseconds
if seed != 0:
args.append('-r')
args.append(seed)
@@ -344,4 +344,3 @@ optimathsat = Optimathsat(path=config.get('optimathsat'))
#: Default Opturion instance.
opturion = Opturion(path=config.get('opturion'))
-
|
solver: fix bug with timeout cast to str
|
paolodragone_pymzn
|
train
|
b23d455b47fd1f55ddb896ec2a4541bc4152cfca
|
diff --git a/lib/match/encrypt.rb b/lib/match/encrypt.rb
index <HASH>..<HASH> 100644
--- a/lib/match/encrypt.rb
+++ b/lib/match/encrypt.rb
@@ -17,14 +17,7 @@ module Match
UI.important "Enter the passphrase that should be used to encrypt/decrypt your certificates"
UI.important "This passphrase is specific per repository and will be stored in your local keychain"
UI.important "Make sure to remember the password, as you'll need it when you run match on a different machine"
- while password.to_s.length == 0
- password = ask("Passphrase for Git Repo: ".yellow) { |q| q.echo = "*" }
- password2 = ask("Type passphrase again: ".yellow) { |q| q.echo = "*" }
- if password != password2
- UI.error("Passhprases differ. Try again")
- password = ""
- end
- end
+ password = ChangePassword.ask_password()
store_password(git_url, password)
end
|
Reuse single function to ask passphrase twice
|
fastlane_fastlane
|
train
|
6a1b3363897446a3cd68ed36449fddc52ce3f765
|
diff --git a/openpnm/algorithms/ReactiveTransport.py b/openpnm/algorithms/ReactiveTransport.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/ReactiveTransport.py
+++ b/openpnm/algorithms/ReactiveTransport.py
@@ -291,8 +291,8 @@ class ReactiveTransport(GenericTransport):
phase.regenerate_models(propnames=iterative_props)
for geometry in geometries:
geometry.regenerate_models(iterative_props)
- for physic in physics:
- physic.regenerate_models(iterative_props)
+ for phys in physics:
+ phys.regenerate_models(iterative_props)
def _apply_sources(self):
"""r
@@ -300,42 +300,49 @@ class ReactiveTransport(GenericTransport):
Notes
-----
- Applying source terms to ``A`` and ``b`` is performed after (optionally)
+ - Applying source terms to ``A`` and ``b`` is performed after (optionally)
under-relaxing the source term to improve numerical stability. Physics
are also updated before applying source terms to ensure that source
terms values are associated with the current value of 'quantity'.
+ - For source term under-relaxation, old values of S1 and S2 need to be
+ stored somewhere, we chose to store them on the algorithm object. This is
+ because storing them on phase/physics creates unintended problems, ex.
+ storing them on physics -> IO complains added depth to the NestedDict, and
+ storing them on the phase object results in NaNs in case source term is
+ only added to a subset of nodes, which breaks our _sanity_check algorithm.
+
Warnings
--------
In the case of a transient simulation, the updates in ``A`` and ``b``
also depend on the time scheme. So, ``_correct_apply_sources()`` needs to
be run afterwards to correct the already applied relaxed source terms.
+
"""
phase = self.project.phases()[self.settings['phase']]
w = self.settings['relaxation_source']
for item in self.settings['sources']:
+ element, prop = item.split(".")
+ _item = ".".join([element, "_" + prop])
+ first_iter = False if _item + ".S1.old" in self.keys() else True
Ps = self.pores(item)
+ # Fetch S1/S2 and their old values (don't exist on 1st iter)
+ S1 = phase[item + ".S1"][Ps]
+ S2 = phase[item + ".S2"][Ps]
+ X1 = self[_item + ".S1.old"][Ps] if not first_iter else S1
+ X2 = self[_item + ".S2.old"][Ps] if not first_iter else S2
# Source term relaxation
- S1, S2 = [phase[item + '.' + x][Ps] for x in ['S1', 'S2']]
- # Get old values of S1 and S2
- try:
- X1, X2 = [phase[item + '.' + x + '.old'][Ps] for x in ['S1', 'S2']]
- # S1.old and S2.old are not yet available in 1st iteration
- except KeyError:
- X1, X2 = S1.copy(), S2.copy()
- S1 = phase[item + '.' + 'S1'][Ps] = w * S1 + (1-w) * X1
- S2 = phase[item + '.' + 'S2'][Ps] = w * S2 + (1-w) * X2
- # Add "relaxed" S1 and S2 to A and b
+ S1 = phase[item + '.S1'][Ps] = w * S1 + (1.0 - w) * X1
+ S2 = phase[item + '.S2'][Ps] = w * S2 + (1.0 - w) * X2
+ # Modify A and b based on "relaxed" S1/S2
datadiag = self._A.diagonal().copy()
datadiag[Ps] = datadiag[Ps] - S1
self._A.setdiag(datadiag)
self._b[Ps] = self._b[Ps] + S2
-
- # Replace old values of S1 and S2 by their current values
- for item in self.settings['sources']:
- phase[item + '.' + 'S1.old'] = phase[item + '.' + 'S1'].copy()
- phase[item + '.' + 'S2.old'] = phase[item + '.' + 'S2'].copy()
+ # Replace old values of S1/S2 by their current values
+ self[_item + ".S1.old"] = phase[item + ".S1"]
+ self[_item + ".S2.old"] = phase[item + ".S2"]
def run(self, x0=None):
r"""
|
Refactored _apply_sources: S1.old and S2.old must not be stored on phase nor physics, but on algorithm
|
PMEAL_OpenPNM
|
train
|
d32cd6301b1d64c19711e597dba5a02a77a0334f
|
diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py
index <HASH>..<HASH> 100755
--- a/examples/adwords/authentication/generate_refresh_token.py
+++ b/examples/adwords/authentication/generate_refresh_token.py
@@ -98,7 +98,7 @@ def main(client_id, client_secret, scopes):
print('Log into the Google Account you use to access your AdWords account '
'and go to the following URL: \n%s\n' % auth_url)
print('After approving the token enter the verification code (if specified).')
- code = raw_input('Code: ').strip()
+ code = input('Code: ').strip()
try:
flow.fetch_token(code=code)
|
Undeclared Variable Removal (#<I>)
The variable raw_input have no declaration, this was replaced by input.
|
googleads_googleads-python-lib
|
train
|
b56b9579d372225d4396553c8c88db153a85cbfc
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -3,6 +3,3 @@
module.exports = require('./linter');
module.exports.Rule = require('./rules/base');
module.exports.ASTHelpers = require('./helpers/ast-node-info');
-
-module.exports.WARNING_SEVERITY = require('./linter').WARNING_SEVERITY;
-module.exports.ERROR_SEVERITY = require('./linter').ERROR_SEVERITY;
diff --git a/lib/linter.js b/lib/linter.js
index <HASH>..<HASH> 100644
--- a/lib/linter.js
+++ b/lib/linter.js
@@ -6,9 +6,6 @@ const chalk = require('chalk');
const EditorConfigResolver = require('./get-editor-config');
let path = require('path');
-const WARNING_SEVERITY = 1;
-const ERROR_SEVERITY = 2;
-
function buildErrorMessage(moduleId, error) {
let message = {
fatal: true,
@@ -45,12 +42,12 @@ class Linter {
_defaultSeverityForRule(ruleName, pendingStatus) {
if (typeof pendingStatus === 'boolean') {
- return pendingStatus ? WARNING_SEVERITY : ERROR_SEVERITY;
+ return pendingStatus ? this.WARNING_SEVERITY : this.ERROR_SEVERITY;
} else if (pendingStatus.only) {
if (pendingStatus.only.indexOf(ruleName) > -1) {
- return WARNING_SEVERITY;
+ return this.WARNING_SEVERITY;
} else {
- return ERROR_SEVERITY;
+ return this.ERROR_SEVERITY;
}
}
@@ -190,6 +187,9 @@ class Linter {
this.console.log(message);
}
+ static WARNING_SEVERITY = 1;
+ static ERROR_SEVERITY = 2;
+
static errorsToMessages(filePath, errors, options) {
errors = errors || [];
options = options || {
@@ -213,7 +213,7 @@ class Linter {
message += chalk.dim(` ${line}:${column}`);
- if (error.severity === WARNING_SEVERITY) {
+ if (error.severity === this.WARNING_SEVERITY) {
message += ` ${chalk.yellow('warning')}`;
} else {
message += ` ${chalk.red('error')}`;
@@ -230,5 +230,3 @@ class Linter {
}
module.exports = Linter;
-module.exports.WARNING_SEVERITY = WARNING_SEVERITY;
-module.exports.ERROR_SEVERITY = ERROR_SEVERITY;
|
Move SEVERITY constants to static class fields
Not to mutate the Linter class when exporting the index module.
|
ember-template-lint_ember-template-lint
|
train
|
32de8f8f4e09278bb72b816ef6a6a3184d19bfe6
|
diff --git a/lib/rest-ftp-daemon/server.rb b/lib/rest-ftp-daemon/server.rb
index <HASH>..<HASH> 100644
--- a/lib/rest-ftp-daemon/server.rb
+++ b/lib/rest-ftp-daemon/server.rb
@@ -17,6 +17,7 @@ class RestFtpDaemonServer < Sinatra::Base
disable :logging
end
+
# Server initialization
def initialize
# Setup logger
@@ -31,6 +32,20 @@ class RestFtpDaemonServer < Sinatra::Base
super
end
+
+ # Test URLs
+ # Server test
+ get "/test" do
+ begin
+ raise RestFtpDaemon::DummyException
+ rescue RestFtpDaemon::RestFtpDaemonException => exception
+ return api_error 501, exception
+ else
+ return api_success 200, ({success: true, reason: :dont_know_why})
+ end
+ end
+
+
# Server global status
get "/" do
# Debug query
|
added GET /test to test DummyException
|
bmedici_rest-ftp-daemon
|
train
|
7934a9e7e4d3a87af5c8649627e9438821c76edb
|
diff --git a/inject/src/main/java/io/micronaut/inject/beans/visitor/IntrospectedTypeElementVisitor.java b/inject/src/main/java/io/micronaut/inject/beans/visitor/IntrospectedTypeElementVisitor.java
index <HASH>..<HASH> 100644
--- a/inject/src/main/java/io/micronaut/inject/beans/visitor/IntrospectedTypeElementVisitor.java
+++ b/inject/src/main/java/io/micronaut/inject/beans/visitor/IntrospectedTypeElementVisitor.java
@@ -63,7 +63,6 @@ public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Object
private Map<String, BeanIntrospectionWriter> writers = new LinkedHashMap<>(10);
private List<AbstractIntrospection> abstractIntrospections = new ArrayList<>();
private AbstractIntrospection currentAbstractIntrospection;
- private BeanIntrospectionWriter currentRecordWriter;
@Override
public int getOrder() {
@@ -75,7 +74,6 @@ public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Object
public void visitClass(ClassElement element, VisitorContext context) {
// reset
currentAbstractIntrospection = null;
- currentRecordWriter = null;
if (!element.isPrivate() && element.hasStereotype(Introspected.class)) {
final AnnotationValue<Introspected> introspected = element.getAnnotation(Introspected.class);
if (introspected != null && !writers.containsKey(element.getName())) {
@@ -126,21 +124,6 @@ public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Object
));
propertyElement.writeMethod = element;
}
- } else if (currentRecordWriter != null) {
- if (element.getParameters().length == 0) {
- Optional<ParameterElement> parameterElement = Arrays.stream(currentRecordWriter.getConstructor().getParameters())
- .filter(p -> p.getName().equals(methodName))
- .findFirst();
- parameterElement.ifPresent(value -> currentRecordWriter.visitProperty(
- element.getReturnType(),
- element.getGenericReturnType(),
- methodName,
- element,
- null,
- true,
- value.getAnnotationMetadata(),
- element.getReturnType().getTypeArguments()));
- }
}
}
@@ -348,11 +331,7 @@ public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Object
}
ClassElement classElement = writer.getClassElement();
- if (classElement.isRecord()) {
- this.currentRecordWriter = writer;
- } else {
- processBeanProperties(writer, beanProperties, includes, excludes, ignored, indexedAnnotations, metadata);
- }
+ processBeanProperties(writer, beanProperties, includes, excludes, ignored, indexedAnnotations, metadata);
writers.put(writer.getBeanType().getClassName(), writer);
}
|
Simplify record handling (#<I>)
|
micronaut-projects_micronaut-core
|
train
|
0946b52e8642cb581776435e1040dc510ad32b1f
|
diff --git a/packages/generator/app/templates/package.json b/packages/generator/app/templates/package.json
index <HASH>..<HASH> 100644
--- a/packages/generator/app/templates/package.json
+++ b/packages/generator/app/templates/package.json
@@ -12,7 +12,7 @@
"lint": "eslint . && npm run stylelint",
"stylelint": "stylelint --ignore-path .gitignore **/*.css",
"ci-test": "npm run lint && karma start",
- "start": "webpack-dev-server -d --history-api-fallback --inline --hot --colors --port <%= port %>"
+ "start": "webpack serve --mode=development --history-api-fallback --hot --color --port <%= port %>"
},
"dependencies": {
"@babel/core": "^7.15.0",
diff --git a/packages/generator/app/templates/webpack.config.js b/packages/generator/app/templates/webpack.config.js
index <HASH>..<HASH> 100644
--- a/packages/generator/app/templates/webpack.config.js
+++ b/packages/generator/app/templates/webpack.config.js
@@ -59,13 +59,6 @@ const webpackConfig = () => ({
]
},
devServer: {<%- additionalDevServerOptions %>
- stats: {
- assets: false,
- children: false,
- chunks: false,
- hash: false,
- version: false
- }
},
plugins: [
new HtmlWebpackPlugin({
diff --git a/packages/generator/hub-widget/index.js b/packages/generator/hub-widget/index.js
index <HASH>..<HASH> 100644
--- a/packages/generator/hub-widget/index.js
+++ b/packages/generator/hub-widget/index.js
@@ -27,8 +27,7 @@ const INDENT = 2;
const additionalDevServerOptions = `
headers: {
'Access-Control-Allow-Origin': '*'
- },
- disableHostCheck: true,`;
+ },`;
const additionalWebpackPlugins = `,
new (require('copy-webpack-plugin'))({patterns: ['manifest.json']}, {})
|
RG-<I> fix running `npm start` command in generated app
|
JetBrains_ring-ui
|
train
|
58ada3f9d115caf91881323a28118fae484c5810
|
diff --git a/system/Test/FeatureTestTrait.php b/system/Test/FeatureTestTrait.php
index <HASH>..<HASH> 100644
--- a/system/Test/FeatureTestTrait.php
+++ b/system/Test/FeatureTestTrait.php
@@ -167,7 +167,7 @@ trait FeatureTestTrait
$request = $this->populateGlobals($method, $request, $params);
// Make sure the RouteCollection knows what method we're using...
- $routes = $this->routes ?: Services::routes(); // @phpstan-ignore-line
+ $routes = $this->routes ?? Services::routes();
$routes->setHTTPVerb($method);
// Make sure any other classes that might call the request
|
Use null coalescing to routes resolution
|
codeigniter4_CodeIgniter4
|
train
|
31b58fb39c1a11de7cc5e85dee2e15707039cd59
|
diff --git a/core/src/main/java/com/google/common/truth/Subject.java b/core/src/main/java/com/google/common/truth/Subject.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/common/truth/Subject.java
+++ b/core/src/main/java/com/google/common/truth/Subject.java
@@ -20,6 +20,8 @@ import static com.google.common.truth.StringUtil.format;
import static com.google.common.truth.SubjectUtils.accumulate;
import com.google.common.base.Objects;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import java.util.List;
@@ -168,10 +170,10 @@ public class Subject<S extends Subject<S,T>,T> {
* Fails if the subject is equal to any element in the given iterable.
*/
public void isNotIn(Iterable<?> iterable) {
- if (Iterables.contains(iterable, getSubject())) {
- // TODO(kak): We might want to beef up the error message to include the index at which the
- // unexpected element actually occurred.
- fail("is not equal to any element in", iterable);
+ int index = Iterables.indexOf(iterable, Predicates.<Object>equalTo(getSubject()));
+ if (index != -1 ) {
+ failWithRawMessage("Not true that %s is not in %s. It was found at index %s",
+ getDisplaySubject(), iterable, index);
}
}
@@ -179,12 +181,7 @@ public class Subject<S extends Subject<S,T>,T> {
* Fails if the subject is equal to any of the given elements.
*/
public void isNoneOf(@Nullable Object first, @Nullable Object second, @Nullable Object... rest) {
- List<Object> list = accumulate(first, second, rest);
- if (list.contains(getSubject())) {
- // TODO(kak): We might want to beef up the error message to include the index at which the
- // unexpected element actually occurred.
- fail("is not equal to any of", list);
- }
+ isNotIn(accumulate(first, second, rest));
}
protected T getSubject() {
diff --git a/core/src/test/java/com/google/common/truth/SubjectTest.java b/core/src/test/java/com/google/common/truth/SubjectTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/google/common/truth/SubjectTest.java
+++ b/core/src/test/java/com/google/common/truth/SubjectTest.java
@@ -495,7 +495,8 @@ public class SubjectTest {
assertThat("b").isNotIn(oneShotIterable("a", "b", "c"));
fail("Should have thrown.");
} catch (AssertionError e) {
- assertThat(e).hasMessage("Not true that <\"b\"> is not equal to any element in <[a, b, c]>");
+ assertThat(e)
+ .hasMessage("Not true that <\"b\"> is not in [a, b, c]. It was found at index 1");
}
}
@@ -509,7 +510,7 @@ public class SubjectTest {
fail("Should have thrown.");
} catch (AssertionError e) {
assertThat(e)
- .hasMessage("Not true that <\"null\"> is not equal to any element in <[a, b, null]>");
+ .hasMessage("Not true that <\"null\"> is not in [a, b, null]. It was found at index 2");
}
}
@@ -526,7 +527,8 @@ public class SubjectTest {
assertThat("b").isNoneOf("a", "b", "c");
fail("Should have thrown.");
} catch (AssertionError e) {
- assertThat(e).hasMessage("Not true that <\"b\"> is not equal to any of <[a, b, c]>");
+ assertThat(e)
+ .hasMessage("Not true that <\"b\"> is not in [a, b, c]. It was found at index 1");
}
}
@@ -539,7 +541,8 @@ public class SubjectTest {
assertThat((String) null).isNoneOf("a", "b", (String) null);
fail("Should have thrown.");
} catch (AssertionError e) {
- assertThat(e).hasMessage("Not true that <\"null\"> is not equal to any of <[a, b, null]>");
+ assertThat(e)
+ .hasMessage("Not true that <\"null\"> is not in [a, b, null]. It was found at index 2");
}
}
|
Include index at which the unexpected item was found in the list.
-------------
Created by MOE: <URL>
|
google_truth
|
train
|
d3ed8402ac6b50ccdd3083b14bf6c4f0869f4143
|
diff --git a/src/components/minmaxinputs/minmaxinputs.js b/src/components/minmaxinputs/minmaxinputs.js
index <HASH>..<HASH> 100644
--- a/src/components/minmaxinputs/minmaxinputs.js
+++ b/src/components/minmaxinputs/minmaxinputs.js
@@ -12,19 +12,17 @@ const ZOOMEDMAX = "zoomedMax";
const MinMaxInputs = Component.extend({
- /**
- * Initializes the Component.
- * Executed once before any template is rendered.
- * @param config The options passed to the component
- * @param context The component's parent
- */
+ /**
+ * Initializes the Component.
+ * Executed once before any template is rendered.
+ * @param config The options passed to the component
+ * @param context The component's parent
+ */
init(config, context) {
this.name = "gapminder-minmaxinputs";
this.template = require("./minmaxinputs.html");
- const _this = this;
-
this.model_expects = [{
name: "marker",
type: "model"
@@ -39,21 +37,24 @@ const MinMaxInputs = Component.extend({
this.markerID = config.markerID;
if (!config.markerID) utils.warn("minmaxinputs.js complains on 'markerID' property: " + config.markerID);
- this.model_binds = {};
- this.model_binds["translate:locale"] = function(evt) {
- _this.updateView();
- };
- this.model_binds["change:marker." + this.markerID] = function(evt) {
- _this.updateView();
- };
- this.model_binds["ready"] = function(evt) {
- _this.updateView();
+ this.model_binds = {
+ "translate:locale": () => {
+ this.updateView();
+ },
+
+ [`change:marker.${this.markerID}`]: () => {
+ this.updateView();
+ },
+
+ ready: () => {
+ this.updateView();
+ }
};
- //contructor is the same as any component
+ // contructor is the same as any component
this._super(config, context);
- // SPECIFIC COMPONENT UI! NOT TOOLMODEL UI!
+ // SPECIFIC COMPONENT UI! NOT TOOLMODEL UI!
this.ui = utils.extend({
selectDomainMinMax: false,
selectZoomedMinMax: false
@@ -98,7 +99,7 @@ const MinMaxInputs = Component.extend({
});
this.element.selectAll("input")
- .on("keypress", e => {
+ .on("keypress", () => {
if (d3.event.which == 13) document.activeElement.blur();
});
},
@@ -130,10 +131,14 @@ const MinMaxInputs = Component.extend({
return d3.format(".2r")(n);
};
- this.el_domain_fieldMin.property("value", formatter(this.model.marker[this.markerID].getScale().domain()[0]));
- this.el_domain_fieldMax.property("value", formatter(this.model.marker[this.markerID].getScale().domain()[1]));
- this.el_zoomed_fieldMin.property("value", formatter(this.model.marker[this.markerID].zoomedMin));
- this.el_zoomed_fieldMax.property("value", formatter(this.model.marker[this.markerID].zoomedMax));
+ const marker = this.model.marker[this.markerID];
+ const [domainMin, domainMax] = marker.getScale().domain();
+ const { zoomedMin, zoomedMax } = marker;
+
+ this.el_domain_fieldMin.property("value", formatter(domainMin));
+ this.el_domain_fieldMax.property("value", formatter(domainMax));
+ this.el_zoomed_fieldMin.property("value", formatter(zoomedMin === null ? domainMin : zoomedMin));
+ this.el_zoomed_fieldMax.property("value", formatter(zoomedMax === null ? domainMax : zoomedMax));
},
_setModel(what, value) {
|
Fix/empty min max inputs (#<I>)
* Reformat minmaxinputs.js
* Get zoomedMin and zoomedMax from domain if they are null
* Set domainMin/max to zoomMin/Max if zoom is null
* Remove setting of zoomed min/max, add a stupid solution, hope it will hold
|
vizabi_vizabi
|
train
|
e095a1572fb8a2ba17ea231abcb3704cf83a96e4
|
diff --git a/commands.go b/commands.go
index <HASH>..<HASH> 100644
--- a/commands.go
+++ b/commands.go
@@ -736,23 +736,30 @@ func (cli *DockerCli) CmdPush(args ...string) error {
return err
}
- if len(strings.SplitN(name, "/", 2)) == 1 {
- return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
+ if *registry == "" {
+ // If we're not using a custom registry, we know the restrictions
+ // applied to repository names and can warn the user in advance.
+ // Custom repositories can have different rules, and we must also
+ // allow pushing by image ID.
+ if len(strings.SplitN(name, "/", 2)) == 1 {
+ return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
+ }
+
+ nameParts := strings.SplitN(name, "/", 2)
+ validNamespace := regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
+ if !validNamespace.MatchString(nameParts[0]) {
+ return fmt.Errorf("Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", nameParts[0])
+ }
+ validRepo := regexp.MustCompile(`^([a-zA-Z0-9-_.]+)$`)
+ if !validRepo.MatchString(nameParts[1]) {
+ return fmt.Errorf("Invalid repository name (%s), only [a-zA-Z0-9-_.] are allowed", nameParts[1])
+ }
}
buf, err := json.Marshal(cli.authConfig)
if err != nil {
return err
}
- nameParts := strings.SplitN(name, "/", 2)
- validNamespace := regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
- if !validNamespace.MatchString(nameParts[0]) {
- return fmt.Errorf("Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", nameParts[0])
- }
- validRepo := regexp.MustCompile(`^([a-zA-Z0-9-_.]+)$`)
- if !validRepo.MatchString(nameParts[1]) {
- return fmt.Errorf("Invalid repository name (%s), only [a-zA-Z0-9-_.] are allowed", nameParts[1])
- }
v := url.Values{}
v.Set("registry", *registry)
|
Allow push by ID when using a custom registry
|
containers_storage
|
train
|
5b9560e5233b43520768133ac2b7280284531b36
|
diff --git a/app/models/spree/product_decorator.rb b/app/models/spree/product_decorator.rb
index <HASH>..<HASH> 100644
--- a/app/models/spree/product_decorator.rb
+++ b/app/models/spree/product_decorator.rb
@@ -2,7 +2,7 @@ Spree::Product.class_eval do
has_many :relations, :as => :relatable
def self.relation_types
- RelationType.find_all_by_applies_to(self.to_s, :order => :name)
+ Spree::RelationType.find_all_by_applies_to(self.to_s, :order => :name)
end
def method_missing(method, *args)
|
fix missing Spree:: in product_decorator
|
solidusio-contrib_solidus_related_products
|
train
|
ff7154dda893a42a2f2649666647cf4693cb27c9
|
diff --git a/src/article/shared/ArticleToolbarPackage.js b/src/article/shared/ArticleToolbarPackage.js
index <HASH>..<HASH> 100644
--- a/src/article/shared/ArticleToolbarPackage.js
+++ b/src/article/shared/ArticleToolbarPackage.js
@@ -161,8 +161,8 @@ export default {
hideDisabled: true,
displayActiveCommand: true,
items: [
- { type: 'command', name: 'open-manuscript', label: 'manuscript' },
- { type: 'command', name: 'open-metadata', label: 'metadata' }
+ { type: 'command', name: 'open-manuscript', label: 'open-manuscript', icon: 'manuscript' },
+ { type: 'command', name: 'open-metadata', label: 'open-metadata', icon: 'metadata' }
]
}
])
@@ -200,6 +200,8 @@ export default {
config.addIcon('bold', { 'fontawesome': 'fa-bold' })
config.addIcon('italic', { 'fontawesome': 'fa-italic' })
config.addIcon('link', { 'fontawesome': 'fa-link' })
+ config.addIcon('manuscript', { 'fontawesome': 'fa-align-left' })
+ config.addIcon('metadata', { 'fontawesome': 'fa-th-list' })
// Format tools labels
config.addLabel('format', 'Format')
@@ -310,6 +312,8 @@ export default {
config.addLabel('move-up-metadata-field', 'Move Up Metadata Field')
config.addLabel('remove-metadata-field', 'Remove Metadata Field')
// Mode
- config.addLabel('manuscript', 'Manuscript')
+ config.addLabel('mode', 'Mode')
+ config.addLabel('open-manuscript', 'Manuscript')
+ config.addLabel('open-metadata', 'Details')
}
}
|
Keep icons and labels for view switching in article toolbar package.
|
substance_texture
|
train
|
3f71131de8353594a33f367ae06a4478358ba2e2
|
diff --git a/spec/project_haystack/point_spec.rb b/spec/project_haystack/point_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/project_haystack/point_spec.rb
+++ b/spec/project_haystack/point_spec.rb
@@ -39,11 +39,10 @@ describe ProjectHaystack::Point do
describe '#data' do
context 'valid id and range' do
before do
- @data = @point.data('yesterday')
+ @data = @point.data('2015-06-15')
@d = @data.first
end
it 'returns data with expected format' do
- @d = @data.first
expect(@d[:time]).to_not be_nil
expect(@d[:value]).to_not be_nil
end
|
use date that is known to have data
|
NREL_haystack_ruby
|
train
|
111b5a9070439440e8968a27e8106717faa03bcc
|
diff --git a/src/Concerns/WaitsForElements.php b/src/Concerns/WaitsForElements.php
index <HASH>..<HASH> 100644
--- a/src/Concerns/WaitsForElements.php
+++ b/src/Concerns/WaitsForElements.php
@@ -139,7 +139,7 @@ trait WaitsForElements
return $this->waitUsing($seconds, 100, function () use ($token) {
return $this->driver->executeScript("return typeof window['{$token}'] === 'undefined';");
- });
+ }, 'Waited %s seconds for page reload.');
}
/**
|
Add helpful failure message to waitForReload
|
laravel_dusk
|
train
|
6a101f4dadd9a03e3113569ceaf9c5afa8ddf6e4
|
diff --git a/googletrans/translator.py b/googletrans/translator.py
index <HASH>..<HASH> 100644
--- a/googletrans/translator.py
+++ b/googletrans/translator.py
@@ -74,6 +74,11 @@ Advanced usage:
result.append(translated)
return result
+ if dest not in LANGUAGES.keys():
+ raise ValueError('incorrect destination language')
+ if src != 'auto' and src not in LANGUAGES.keys():
+ raise ValueError('incorrect source language')
+
result = ''
sess = agent() # acquire requests session
origin = text
|
Fix: check availability of both source and destination language
refs #2
|
ssut_py-googletrans
|
train
|
533e1f220b35adfe3d512980e41e8feca3cd91ed
|
diff --git a/src/Kernel.php b/src/Kernel.php
index <HASH>..<HASH> 100644
--- a/src/Kernel.php
+++ b/src/Kernel.php
@@ -19,6 +19,7 @@ use function defined;
use function get_class;
use Illuminate\Console\Application as Artisan;
use Illuminate\Foundation\Console\Kernel as BaseKernel;
+use Illuminate\Foundation\Console\TestMakeCommand;
use function in_array;
use LaravelZero\Framework\Providers\CommandRecorder\CommandRecorderRepository;
use ReflectionClass;
@@ -120,7 +121,15 @@ class Kernel extends BaseKernel
$commands = $commands->merge($this->developmentCommands);
}
- $commands = $commands->diff($toRemoveCommands = $config->get('commands.remove', []));
+ $toRemoveCommands = $config->get('commands.remove', []);
+
+ if ($this->app->environment() === 'production') {
+ $toRemoveLaravelCommands = [
+ TestMakeCommand::class,
+ ];
+ }
+
+ $commands = $commands->diff(array_merge($toRemoveCommands, $toRemoveLaravelCommands ?? []));
Artisan::starting(
function ($artisan) use ($toRemoveCommands) {
diff --git a/tests/LoadConfigurationsTest.php b/tests/LoadConfigurationsTest.php
index <HASH>..<HASH> 100755
--- a/tests/LoadConfigurationsTest.php
+++ b/tests/LoadConfigurationsTest.php
@@ -53,4 +53,9 @@ final class LoadConfigurationsTest extends TestCase
{
$this->assertArrayNotHasKey('fake:removed', Artisan::all());
}
+
+ public function testMakeTestCommandIsRemoved(): void
+ {
+ $this->assertArrayNotHasKey('make:test', Artisan::all());
+ }
}
|
Updated Kernel.php; Added a check that will remove laravel commands.
Updated LoadConfigurationsTest.php; Added a test to make sure the `make:test` command is removed.
|
laravel-zero_framework
|
train
|
1110045e0d28a461e75d2f57d5f01533d59ef239
|
diff --git a/lib/rules/spaced-comment.js b/lib/rules/spaced-comment.js
index <HASH>..<HASH> 100644
--- a/lib/rules/spaced-comment.js
+++ b/lib/rules/spaced-comment.js
@@ -249,7 +249,8 @@ module.exports = {
beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"),
hasExceptions: exceptions.length > 0,
- markers: new RegExp(`^(${markers.map(escape).join("|")})`, "u")
+ captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"),
+ markers: new Set(markers)
};
return rule;
@@ -322,8 +323,8 @@ module.exports = {
rule = styleRules[type],
commentIdentifier = type === "block" ? "/*" : "//";
- // Ignores empty comments.
- if (node.value.length === 0) {
+ // Ignores empty comments and comments that consist only of a marker.
+ if (node.value.length === 0 || rule.markers.has(node.value)) {
return;
}
@@ -333,7 +334,7 @@ module.exports = {
// Checks.
if (requireSpace) {
if (!beginMatch) {
- const hasMarker = rule.markers.exec(node.value);
+ const hasMarker = rule.captureMarker.exec(node.value);
const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
if (rule.hasExceptions) {
diff --git a/tests/lib/rules/spaced-comment.js b/tests/lib/rules/spaced-comment.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/spaced-comment.js
+++ b/tests/lib/rules/spaced-comment.js
@@ -304,6 +304,44 @@ ruleTester.run("spaced-comment", rule, {
{
code: "/***\u2028*/",
options: ["always", { exceptions: ["*"] }]
+ },
+
+ // ignore marker-only comments, https://github.com/eslint/eslint/issues/12036
+ {
+ code: "//#endregion",
+ options: ["always", { line: { markers: ["#endregion"] } }]
+ },
+ {
+ code: "/*foo*/",
+ options: ["always", { block: { markers: ["foo"] } }]
+ },
+ {
+ code: "/*foo*/",
+ options: ["always", { block: { markers: ["foo"], balanced: true } }]
+ },
+ {
+ code: "/*foo*/ /*bar*/",
+ options: ["always", { markers: ["foo", "bar"] }]
+ },
+ {
+ code: "//foo\n//bar",
+ options: ["always", { markers: ["foo", "bar"] }]
+ },
+ {
+ code: "/* foo */",
+ options: ["never", { markers: [" foo "] }]
+ },
+ {
+ code: "// foo ",
+ options: ["never", { markers: [" foo "] }]
+ },
+ {
+ code: "//*", // "*" is a marker by default
+ options: ["always"]
+ },
+ {
+ code: "/***/", // "*" is a marker by default
+ options: ["always"]
}
],
@@ -586,6 +624,65 @@ ruleTester.run("spaced-comment", rule, {
output: null,
options: ["never"],
errors: 1
+ },
+
+ // not a marker-only comment, regression tests for https://github.com/eslint/eslint/issues/12036
+ {
+ code: "//#endregionfoo",
+ output: "//#endregion foo",
+ options: ["always", { line: { markers: ["#endregion"] } }],
+ errors: [{
+ message: "Expected space or tab after '//#endregion' in comment.",
+ type: "Line"
+ }]
+ },
+ {
+ code: "/*#endregion*/",
+ output: "/* #endregion*/", // not an allowed marker for block comments
+ options: ["always", { line: { markers: ["#endregion"] } }],
+ errors: [{
+ message: "Expected space or tab after '/*' in comment.",
+ type: "Block"
+ }]
+ },
+ {
+ code: "/****/",
+ output: "/** **/",
+ options: ["always"],
+ errors: [{
+ message: "Expected space or tab after '/**' in comment.",
+ type: "Block"
+ }]
+ },
+ {
+ code: "/****/",
+ output: "/** * */",
+ options: ["always", { block: { balanced: true } }],
+ errors: [
+ {
+ message: "Expected space or tab after '/**' in comment.",
+ type: "Block"
+ },
+ {
+ message: "Expected space or tab before '*/' in comment.",
+ type: "Block"
+ }
+ ]
+ },
+ {
+ code: "/* foo */",
+ output: "/*foo*/",
+ options: ["never", { block: { markers: ["foo"], balanced: true } }], // not " foo "
+ errors: [
+ {
+ message: "Unexpected space or tab after '/*' in comment.",
+ type: "Block"
+ },
+ {
+ message: "Unexpected space or tab before '*/' in comment.",
+ type: "Block"
+ }
+ ]
}
]
|
Fix: ignore marker-only comments in spaced-comment (fixes #<I>) (#<I>)
|
eslint_eslint
|
train
|
ff2f44785aac0fbe80f186aa951d12acddaa962e
|
diff --git a/benchmark/src/main/java/com/github/gumtree/dist/ActionsCollector.java b/benchmark/src/main/java/com/github/gumtree/dist/ActionsCollector.java
index <HASH>..<HASH> 100644
--- a/benchmark/src/main/java/com/github/gumtree/dist/ActionsCollector.java
+++ b/benchmark/src/main/java/com/github/gumtree/dist/ActionsCollector.java
@@ -85,6 +85,8 @@ public class ActionsCollector {
Run.initGenerators();
List<Path> paths = Files.walk(Paths.get(RES_DIR)).filter(
p -> p.getFileName().toString().matches(".*_v0_.*\\.xml")).collect(Collectors.toList());
+ boolean dirty = false;
+ StringBuffer b = new StringBuffer();
for (Path path : paths) {
Path otherPath = Paths.get(path.toString().replace("_v0_","_v1_"));
TreeContext src = TreeIoUtils.fromXml().generateFromFile(path.toString());
@@ -98,28 +100,55 @@ public class ActionsCollector {
ActionsIoUtils.toText(src, actions, matcher.getMappings()).writeTo(w);
Path refPath = Paths.get(path.toString().replace("_v0_","_actions_"));
String ref = Paths.get(REF_DIR, refPath.getFileName().toString()).toString();
- StringReader r = new StringReader(w.toString());
- if (!contentEquals(r, new FileReader(ref))) {
- System.err.println("Content not equals for : " + ref);
- System.exit(-1);
+ if (!contentEquals(new StringReader(w.toString()), new FileReader(ref))) {
+ dirty = true;
+ b.append("Content not equals for: " + ref + ". Now " + countLines(new StringReader(w.toString())) +
+ "Was " + countLines(new FileReader(ref)) + "\n");
}
}
+ if (dirty) {
+ System.err.println(b.toString());
+ System.exit(-1);
+ }
}
public static boolean contentEquals(Reader input1, Reader input2) throws IOException {
- if (!(input1 instanceof BufferedReader))
- input1 = new BufferedReader(input1);
- if (!(input2 instanceof BufferedReader))
- input2 = new BufferedReader(input2);
- int ch = input1.read();
- while (-1 != ch) {
+ try {
+ if (!(input1 instanceof BufferedReader))
+ input1 = new BufferedReader(input1);
+ if (!(input2 instanceof BufferedReader))
+ input2 = new BufferedReader(input2);
+ int ch = input1.read();
+ while (-1 != ch) {
+ int ch2 = input2.read();
+ if (ch != ch2)
+ return false;
+ ch = input1.read();
+ }
int ch2 = input2.read();
- if (ch != ch2)
- return false;
- ch = input1.read();
+ return (ch2 == -1);
+ } finally {
+ input1.close();
+ input2.close();
+ }
+ }
+
+ public static int countLines(Reader r) throws IOException {
+ try {
+ char[] c = new char[1024];
+ int count = 0;
+ int readChars = 0;
+ boolean empty = true;
+ while ((readChars = r.read(c)) != -1) {
+ empty = false;
+ for (int i = 0; i < readChars; ++i)
+ if (c[i] == '\n')
+ ++count;
+ }
+ return (count == 0 && !empty) ? 1 : count;
+ } finally {
+ r.close();
}
- int ch2 = input2.read();
- return (ch2 == -1);
}
}
|
checkActions count and displays changes
|
GumTreeDiff_gumtree
|
train
|
c02f516fa17c883b4af6a4567284979a28987e5e
|
diff --git a/core/src/main/java/jenkins/model/queue/AsynchronousExecution.java b/core/src/main/java/jenkins/model/queue/AsynchronousExecution.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/jenkins/model/queue/AsynchronousExecution.java
+++ b/core/src/main/java/jenkins/model/queue/AsynchronousExecution.java
@@ -28,6 +28,8 @@ import hudson.model.Computer;
import hudson.model.Executor;
import hudson.model.ExecutorListener;
import hudson.model.OneOffExecutor;
+import hudson.model.Queue.Executable;
+import hudson.model.Queue.FlyweightTask;
import hudson.model.Resource;
import hudson.model.ResourceActivity;
import hudson.model.ResourceController;
@@ -39,12 +41,12 @@ import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Special means of indicating that an executable will proceed in the background without consuming a native thread ({@link Executor}).
- * May be thrown from {@link hudson.model.Queue.Executable#run} after doing any preparatory work synchronously.
+ * May be thrown from {@link Executable#run} after doing any preparatory work synchronously.
* <p>{@link Executor#isActive} will remain true (even though {@link Executor#isAlive} is not) until {@link #completed} is called.
* The thrower will need to hold on to a reference to this instance as a handle to call {@link #completed}.
* <p>The execution may not extend into another Jenkins session; if you wish to model a long-running execution, you must schedule a new task after restart.
* This class is not serializable anyway.
- * <p>Mainly intended for use with {@link OneOffExecutor} (from a {@link hudson.model.Queue.FlyweightTask}), of which there could be many,
+ * <p>Mainly intended for use with {@link OneOffExecutor} (from a {@link FlyweightTask}), of which there could be many,
* but could also be used with a heavyweight executor even though the number of executors is bounded by node configuration.
* <p>{@link ResourceController}/{@link ResourceActivity}/{@link ResourceList}/{@link Resource} are not currently supported.
* Nor are {@link hudson.model.Queue.Task#getSubTasks} other than the primary task.
@@ -94,7 +96,7 @@ public abstract class AsynchronousExecution extends RuntimeException {
/**
* To be called when the task is actually complete.
- * @param error normally null (preferable to handle errors yourself), but may be specified to simulate an exception from {@link hudson.model.Queue.Executable#run}, as per {@link ExecutorListener#taskCompletedWithProblems}
+ * @param error normally null (preferable to handle errors yourself), but may be specified to simulate an exception from {@link Executable#run}, as per {@link ExecutorListener#taskCompletedWithProblems}
*/
public final void completed(@CheckForNull Throwable error) {
executor.completedAsynchronous(error);
|
javadoc formatting fix for better readability from code editor
|
jenkinsci_jenkins
|
train
|
8af2250bf4fd17ea52e560f4f04e299f1c1a4df0
|
diff --git a/webapps/client/scripts/controller/cam-tasklist-view-ctrl.js b/webapps/client/scripts/controller/cam-tasklist-view-ctrl.js
index <HASH>..<HASH> 100644
--- a/webapps/client/scripts/controller/cam-tasklist-view-ctrl.js
+++ b/webapps/client/scripts/controller/cam-tasklist-view-ctrl.js
@@ -126,14 +126,14 @@ define([
focused = filter;
}
}
- if(currentFilter) {
+
+ if(currentFilter && currentFilter.id !== focused.id) {
var currentPage = getPropertyFromLocation('page');
if (currentPage) {
updateSilently({
page: '1'
});
}
-
}
if(focused && focused.id !== filterId) {
@@ -299,7 +299,6 @@ define([
currentFilter = null;
tasklistData.changed('currentFilter');
-
});
}];
});
|
fix(page): only change page when another filter is selected
related to CAM-<I>
|
camunda_camunda-bpm-platform
|
train
|
534e99eecd7b2d348af17721e52f6ef016e41f76
|
diff --git a/Geonames.php b/Geonames.php
index <HASH>..<HASH> 100644
--- a/Geonames.php
+++ b/Geonames.php
@@ -139,8 +139,8 @@ final class Geonames extends AbstractHttpProvider implements LocaleAwareGeocoder
for ($level = 1; $level <= AdminLevelCollection::MAX_LEVEL_DEPTH; ++$level) {
$adminNameProp = 'adminName'.$level;
$adminCodeProp = 'adminCode'.$level;
- if (!empty($item->$adminNameProp) || !empty($item->$adminCodeProp)) {
- $builder->addAdminLevel($level, $item->$adminNameProp ?? null, $item->$adminCodeProp ?? null);
+ if (!empty($item->$adminNameProp)) {
+ $builder->addAdminLevel($level, $item->$adminNameProp, $item->$adminCodeProp ?? null);
}
}
|
Fixed some code smell (#<I>)
* Fixed type issues
* Fixed code smell
|
geocoder-php_geonames-provider
|
train
|
0163fd08a36055e3ce4a59f960346b59b5177d81
|
diff --git a/lib/transactions/multisignature.js b/lib/transactions/multisignature.js
index <HASH>..<HASH> 100644
--- a/lib/transactions/multisignature.js
+++ b/lib/transactions/multisignature.js
@@ -20,7 +20,6 @@
var crypto = require('./crypto.js');
var constants = require('../constants.js');
var slots = require('../time/slots.js');
-var transaction = require('./transaction.js');
/**
* @method createTransaction
@@ -62,8 +61,8 @@ function createTransaction (recipientId, amount, secret, secondSecret, requester
transaction.id = crypto.getId(transaction);
transaction.signatures = [];
- return transaction;
+ return transaction;
}
/**
|
Removes transactions as library in multisig
|
OnzCoin_onz-js
|
train
|
8ef4fa5a4043d9cbf2fb42fd42ddd96ccad1248a
|
diff --git a/lib/goldiloader/active_record_patches.rb b/lib/goldiloader/active_record_patches.rb
index <HASH>..<HASH> 100644
--- a/lib/goldiloader/active_record_patches.rb
+++ b/lib/goldiloader/active_record_patches.rb
@@ -66,7 +66,9 @@ ActiveRecord::Associations::Association.class_eval do
!association_info.group? &&
!association_info.from? &&
# Joins not properly eager loaded - See https://github.com/salsify/goldiloader/issues/11
- !association_info.joins?
+ !association_info.joins? &&
+ # Unscope not properly eager loaded - https://github.com/salsify/goldiloader/issues/13
+ !association_info.unscope?
end
def load_with_auto_include(load_method, *args)
diff --git a/lib/goldiloader/association_info.rb b/lib/goldiloader/association_info.rb
index <HASH>..<HASH> 100644
--- a/lib/goldiloader/association_info.rb
+++ b/lib/goldiloader/association_info.rb
@@ -5,6 +5,16 @@ module Goldiloader
@association = association
end
+ if Gem::Version.new(::ActiveRecord::VERSION::STRING) >= Gem::Version.new('4.1')
+ def unscope?
+ @association.association_scope.unscope_values.present?
+ end
+ else
+ def unscope?
+ false
+ end
+ end
+
if ActiveRecord::VERSION::MAJOR >= 4
def read_only?
@association.association_scope.readonly_value.present?
diff --git a/spec/db/schema.rb b/spec/db/schema.rb
index <HASH>..<HASH> 100644
--- a/spec/db/schema.rb
+++ b/spec/db/schema.rb
@@ -125,6 +125,10 @@ class User < ActiveRecord::Base
has_one :address
has_one :address_without_auto_include, auto_include: false, class_name: 'Address'
+ if Gem::Version.new(::ActiveRecord::VERSION::STRING) >= Gem::Version.new('4.1')
+ has_one :scoped_address_with_default_scope_remove, -> { unscope(where: :city) }, class_name: 'ScopedAddress'
+ end
+
if Goldiloader::Compatibility.mass_assignment_security_enabled?
attr_accessible :name
end
@@ -138,6 +142,16 @@ class Address < ActiveRecord::Base
end
end
+class ScopedAddress < ActiveRecord::Base
+ self.table_name = 'addresses'
+ default_scope { where(city: ['Philadelphia'])}
+ belongs_to :user
+
+ if Goldiloader::Compatibility.mass_assignment_security_enabled?
+ attr_accessible :city
+ end
+end
+
class Group < ActiveRecord::Base
has_many :tags, as: :owner
diff --git a/spec/goldiloader/goldiloader_spec.rb b/spec/goldiloader/goldiloader_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/goldiloader/goldiloader_spec.rb
+++ b/spec/goldiloader/goldiloader_spec.rb
@@ -333,6 +333,29 @@ describe Goldiloader do
it_behaves_like "it doesn't auto eager the association", :authors_with_join
end
end
+
+ if Gem::Version.new(::ActiveRecord::VERSION::STRING) >= Gem::Version.new('4.1')
+ context "associations with an unscoped" do
+ let(:authors) { User.order(:id).to_a }
+
+ before do
+ author1.address.update_attributes!(city: 'Boston')
+ author2.address.update_attributes!(city: 'Philadelphia')
+ author3.address.update_attributes!(city: 'Philadelphia')
+ authors.first.scoped_address_with_default_scope_remove
+ end
+
+ it "applies the unscope correctly" do
+ expect(authors.first.scoped_address_with_default_scope_remove).to be_present
+ end
+
+ it "doesn't auto eager the association" do
+ authors.drop(1).each do |author|
+ expect(author.association(:scoped_address_with_default_scope_remove)).to_not be_loaded
+ end
+ end
+ end
+ end
end
context "associations with a uniq" do
|
Workaround #<I> - Don't auto eager load associations with an unscope until <URL>
|
salsify_goldiloader
|
train
|
85a6e084a955027ec5e1a7b58851fd36bd955468
|
diff --git a/sass_processor/version.py b/sass_processor/version.py
index <HASH>..<HASH> 100644
--- a/sass_processor/version.py
+++ b/sass_processor/version.py
@@ -20,4 +20,4 @@ Release logic:
13. git push
"""
-__version__ = '0.4.1'
+__version__ = '0.4.2'
|
Bump to version <I>
|
jrief_django-sass-processor
|
train
|
0b4d718fd52a29e1e90850826526c6fb0a37f781
|
diff --git a/app/src/Bolt/Controllers/Async.php b/app/src/Bolt/Controllers/Async.php
index <HASH>..<HASH> 100644
--- a/app/src/Bolt/Controllers/Async.php
+++ b/app/src/Bolt/Controllers/Async.php
@@ -503,21 +503,12 @@ class Async implements ControllerProviderInterface
$namespace = $request->request->get('namespace', 'files');
$filename = $request->request->get('filename');
-
- $filePath = $app['resources']->getPath($namespace)
- . DIRECTORY_SEPARATOR
- . $filename;
-
-
- // TODO: ensure that we are deleting a file inside /files folder
-
- if (is_file($filePath) && is_readable($filePath)) {
- @unlink($filePath);
+ $filesystem = $app['filesystem']->getManager($namespace);
+
+ if ($filesystem->delete($filename)) {
return true;
- } else {
- return false;
- }
-
+ }
+ return false;
}
/**
@@ -568,27 +559,18 @@ class Async implements ControllerProviderInterface
$oldName = $request->request->get('oldname');
$newName = $request->request->get('newname');
- $oldPath = $app['resources']->getPath($namespace)
- . DIRECTORY_SEPARATOR
- . $parentPath
- . $oldName;
-
- $newPath = $app['resources']->getPath($namespace)
- . DIRECTORY_SEPARATOR
- . $parentPath
- . $newName;
-
- $fileSystemHelper = new Filesystem;
-
- try {
- $fileSystemHelper->rename($oldPath, $newPath, false /* Don't rename if target exists already! */);
- } catch (IOException $exception) {
-
- /* Thrown if target already exists or renaming failed. */
- return false;
+ $oldPath = $parentPath . $oldName;
+ $newPath = $parentPath. $newName;
+
+ $filesystem = $app['filesystem']->getManager($namespace);
+
+ var_dump($oldPath, $newPath); exit;
+
+ if($filesystem->rename($oldPath, $newpath)) {
+ return true;
}
-
- return true;
+
+ return false;
}
/**
|
updated file delete to use new filesystem
|
bolt_bolt
|
train
|
f53324c23f0758f62fdbd3823a6c04ded51d4c87
|
diff --git a/generators/generator-constants.js b/generators/generator-constants.js
index <HASH>..<HASH> 100644
--- a/generators/generator-constants.js
+++ b/generators/generator-constants.js
@@ -32,7 +32,7 @@ const DOCKER_MEMCACHED = 'memcached:1.5.16-alpine';
const DOCKER_KEYCLOAK = 'jboss/keycloak:6.0.1';
const DOCKER_ELASTICSEARCH = 'docker.elastic.co/elasticsearch/elasticsearch:6.4.3'; // The version should be coerent with the one from spring-data-elasticsearch project
const DOCKER_KAFKA = 'confluentinc/cp-kafka:5.3.0';
-const DOCKER_ZOOKEEPER = 'confluentinc/cp-zookeeper:5.2.2';
+const DOCKER_ZOOKEEPER = 'confluentinc/cp-zookeeper:5.3.0';
const DOCKER_SONAR = 'sonarqube:7.9-community';
const DOCKER_JHIPSTER_CONSOLE = 'jhipster/jhipster-console:v4.0.0';
const DOCKER_JHIPSTER_CURATOR = 'jhipster/jhipster-curator:v4.0.0';
|
Update confluentinc/cp-zookeeper docker image to <I>
|
jhipster_generator-jhipster
|
train
|
4a4c52048f33e4d3ced6fa7c1140059f74092976
|
diff --git a/spec/fixtures/project-content-with-invalid-types/index.js b/spec/fixtures/project-content-with-invalid-types/index.js
index <HASH>..<HASH> 100644
--- a/spec/fixtures/project-content-with-invalid-types/index.js
+++ b/spec/fixtures/project-content-with-invalid-types/index.js
@@ -1,9 +1,9 @@
// @flow
type FlowType = {
- value: string
+ value: string,
}
export default (): FlowType => ({
- weird: 'test'
+ weird: 'test',
})
diff --git a/spec/fixtures/project-content-with-prettier-errors/index.js b/spec/fixtures/project-content-with-prettier-errors/index.js
index <HASH>..<HASH> 100644
--- a/spec/fixtures/project-content-with-prettier-errors/index.js
+++ b/spec/fixtures/project-content-with-prettier-errors/index.js
@@ -1,3 +1,5 @@
-const a = 1
+const a = {
+ a: 1
+}
console.log({a})
diff --git a/spec/fixtures/project-content-with-types/index.js b/spec/fixtures/project-content-with-types/index.js
index <HASH>..<HASH> 100644
--- a/spec/fixtures/project-content-with-types/index.js
+++ b/spec/fixtures/project-content-with-types/index.js
@@ -1,9 +1,9 @@
// @flow
type FlowType = {
- value: string
+ value: string,
}
export default (): FlowType => ({
- value: 'test'
+ value: 'test',
})
diff --git a/spec/fixtures/project-content/object-rest.spec.js b/spec/fixtures/project-content/object-rest.spec.js
index <HASH>..<HASH> 100644
--- a/spec/fixtures/project-content/object-rest.spec.js
+++ b/spec/fixtures/project-content/object-rest.spec.js
@@ -6,7 +6,7 @@ describe('super test', function() {
x: 1,
y: 2,
z: { a: 3, b: 4 },
- n: { x: 1, y: 2, a: 3, b: 4 }
+ n: { x: 1, y: 2, a: 3, b: 4 },
})
})
})
diff --git a/spec/fixtures/project-with-css-modules/src/index.js b/spec/fixtures/project-with-css-modules/src/index.js
index <HASH>..<HASH> 100644
--- a/spec/fixtures/project-with-css-modules/src/index.js
+++ b/spec/fixtures/project-with-css-modules/src/index.js
@@ -3,5 +3,5 @@ import componentB from './component-b'
export default {
componentA,
- componentB
+ componentB,
}
diff --git a/src/javascript-eslintrc.json b/src/javascript-eslintrc.json
index <HASH>..<HASH> 100644
--- a/src/javascript-eslintrc.json
+++ b/src/javascript-eslintrc.json
@@ -23,7 +23,8 @@
"singleQuote": true,
"parser": "flow",
"semi": false,
- "printWidth": 100
+ "printWidth": 100,
+ "trailingComma": "es5"
} ]
}
}
diff --git a/template/base/sagui.config.js b/template/base/sagui.config.js
index <HASH>..<HASH> 100644
--- a/template/base/sagui.config.js
+++ b/template/base/sagui.config.js
@@ -3,5 +3,5 @@
* see: http://sagui.js.org/
*/
module.exports = {
- pages: ['index']
+ pages: ['index'],
}
|
Add trailing comma config to prettier ⛑
This has a positive impact on reviewing git diffs
|
saguijs_sagui
|
train
|
c76c7a1bb4d1aa7d64acea601305e6b4ff0e6b4f
|
diff --git a/mt940/__about__.py b/mt940/__about__.py
index <HASH>..<HASH> 100644
--- a/mt940/__about__.py
+++ b/mt940/__about__.py
@@ -6,7 +6,7 @@ A library to parse MT940 files and returns smart Python collections for
statistics and manipulation.
'''.strip().split())
__email__ = 'wolph@wol.ph'
-__version__ = '4.25.0'
+__version__ = '4.26.0'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015 Rick van Hattem (wolph)'
__url__ = 'https://github.com/WoLpH/mt940'
|
Incrementing version to <I>
|
WoLpH_mt940
|
train
|
1eec5bf0584051b6d0e7dc6a31030573f7e86768
|
diff --git a/builder/amazon/ebssurrogate/step_register_ami.go b/builder/amazon/ebssurrogate/step_register_ami.go
index <HASH>..<HASH> 100644
--- a/builder/amazon/ebssurrogate/step_register_ami.go
+++ b/builder/amazon/ebssurrogate/step_register_ami.go
@@ -24,15 +24,23 @@ func (s *StepRegisterAMI) Run(state multistep.StateBag) multistep.StepAction {
ui.Say("Registering the AMI...")
- blockDevices := s.BlockDevices
- blockDevices = append(blockDevices, s.RootDevice.createBlockDeviceMapping(snapshotId))
+ blockDevicesExcludingRoot := make([]*ec2.BlockDeviceMapping, 0, len(s.BlockDevices)-1)
+ for _, blockDevice := range s.BlockDevices {
+ if *blockDevice.DeviceName == s.RootDevice.SourceDeviceName {
+ continue
+ }
+
+ blockDevicesExcludingRoot = append(blockDevicesExcludingRoot, blockDevice)
+ }
+
+ blockDevicesExcludingRoot = append(blockDevicesExcludingRoot, s.RootDevice.createBlockDeviceMapping(snapshotId))
registerOpts := &ec2.RegisterImageInput{
Name: &config.AMIName,
Architecture: aws.String(ec2.ArchitectureValuesX8664),
RootDeviceName: aws.String(s.RootDevice.DeviceName),
VirtualizationType: aws.String(config.AMIVirtType),
- BlockDeviceMappings: blockDevices,
+ BlockDeviceMappings: blockDevicesExcludingRoot,
}
if config.AMIEnhancedNetworking {
|
builder/amazon-ebssurrogate: Exclude duplicate root volume
This commit removes the root volume from the list of launch block device
mappings passed to the image, since it is already passed in the form of
a snapshot (which is then configured to be the root device). Without
this commit, AMIs created using this builder have two root volumes
attached on launch.
|
hashicorp_packer
|
train
|
f7d5471e581fa1c0f9e1db7d74dfbde2520eb900
|
diff --git a/behaviors/YwPlugin.php b/behaviors/YwPlugin.php
index <HASH>..<HASH> 100644
--- a/behaviors/YwPlugin.php
+++ b/behaviors/YwPlugin.php
@@ -12,17 +12,36 @@ class YwPlugin extends CBehavior
{
protected $_assetsUrl;
+ protected static $_api;
+
+ /**
+ * Returns
+ * @param $path
+ * @return mixed
+ */
public function getAssetsUrl($path)
{
if (isset($this->_assetsUrl))
return $this->_assetsUrl;
else
{
- $forceCopyAssets = Yii::app()->getComponent('yiiwheels')->getCore()->forceCopyAssets;
+ $forceCopyAssets = $this->getApi()->forceCopyAssets;
$assetsUrl = Yii::app()->assetManager->publish($path, false, -1, $forceCopyAssets);
return $this->_assetsUrl = $assetsUrl;
}
}
+
+ /**
+ * @return TbApi
+ */
+ public function getApi()
+ {
+ if(self::$_api === null)
+ {
+ self::$_api = Yii::app()->getComponent('yiiwheels')->getApi();
+ }
+ return self::$_api;
+ }
}
\ No newline at end of file
|
added helper method to access the api
|
2amigos_yiiwheels
|
train
|
9db45d344d590037332d097565f6530c39688816
|
diff --git a/molgenis-security/src/main/java/org/molgenis/security/settings/AuthenticationSettingsImpl.java b/molgenis-security/src/main/java/org/molgenis/security/settings/AuthenticationSettingsImpl.java
index <HASH>..<HASH> 100644
--- a/molgenis-security/src/main/java/org/molgenis/security/settings/AuthenticationSettingsImpl.java
+++ b/molgenis-security/src/main/java/org/molgenis/security/settings/AuthenticationSettingsImpl.java
@@ -77,7 +77,9 @@ public class AuthenticationSettingsImpl extends DefaultSettingsEntity
TwoFactorAuthenticationSetting.ENABLED.getLabel(),
TwoFactorAuthenticationSetting.ENFORCED.getLabel()))
.setLabel("Two Factor Authentication")
- .setDescription("Enable or enforce users to sign in with Google Authenticator.")
+ .setDescription(
+ "Enable or enforce users to sign in with Google Authenticator. "
+ + "Must be disabled if you specify OpenID Connect authentication servers")
.setValidationExpression(getSignIn2FAValidationExpression());
}
|
doc: Explain that 2FA cannot be used with OIDC in the attribute description
|
molgenis_molgenis
|
train
|
cefaac074d3abb24df2240581704195687d58cd4
|
diff --git a/library/WT/Controller/Family.php b/library/WT/Controller/Family.php
index <HASH>..<HASH> 100644
--- a/library/WT/Controller/Family.php
+++ b/library/WT/Controller/Family.php
@@ -93,7 +93,7 @@ class WT_Controller_Family extends WT_Controller_GedcomRecord {
if ($this->record) {
return $this->record;
}
- return parent::getSignifcantFamily();
+ return parent::getSignificantFamily();
}
// $tags is an array of HUSB/WIFE/CHIL
|
Type on GetSignificant, thanks Wes
|
fisharebest_webtrees
|
train
|
84e96ec491758d9d7f41d5ac7f44f1d90f01108b
|
diff --git a/common/render.go b/common/render.go
index <HASH>..<HASH> 100644
--- a/common/render.go
+++ b/common/render.go
@@ -164,7 +164,9 @@ func (rs *RenderSystem) New(w *ecs.World) {
addCameraSystemOnce(w)
if !engo.Headless() {
- initShaders(w)
+ if err := initShaders(w); err != nil {
+ panic(err)
+ }
engo.Gl.Enable(engo.Gl.MULTISAMPLE)
}
|
add panic if shaders don't compile. This will allow custom shaders to know if their shaders have errors
|
EngoEngine_engo
|
train
|
96d9b6f56574d5a1eb91a2abaecffde9bff82706
|
diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java
index <HASH>..<HASH> 100644
--- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java
+++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java
@@ -61,7 +61,6 @@ import org.bson.codecs.BsonDocumentCodec;
import org.bson.codecs.DocumentCodec;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -147,27 +146,11 @@ public final class ClusterFixture {
return versionList;
}
- public static Document getBuildInfo() {
- return new CommandWriteOperation<Document>("admin", new BsonDocument("buildInfo", new BsonInt32(1)), new DocumentCodec())
- .execute(getBinding());
- }
-
public static Document getServerStatus() {
return new CommandWriteOperation<Document>("admin", new BsonDocument("serverStatus", new BsonInt32(1)), new DocumentCodec())
.execute(getBinding());
}
- @SuppressWarnings("unchecked")
- public static boolean isEnterpriseServer() {
- Document buildInfo = getBuildInfo();
- List<String> modules = Collections.emptyList();
- if (buildInfo.containsKey("modules")) {
- modules = (List<String>) buildInfo.get("modules");
- }
-
- return modules.contains("enterprise");
- }
-
public static boolean supportsFsync() {
Document serverStatus = getServerStatus();
Document storageEngine = (Document) serverStatus.get("storageEngine");
@@ -400,19 +383,19 @@ public final class ClusterFixture {
}
}
- public static <T> T executeSync(final WriteOperation<T> op) throws Throwable {
+ public static <T> T executeSync(final WriteOperation<T> op) {
return executeSync(op, getBinding());
}
- public static <T> T executeSync(final WriteOperation<T> op, final ReadWriteBinding binding) throws Throwable {
+ public static <T> T executeSync(final WriteOperation<T> op, final ReadWriteBinding binding) {
return op.execute(binding);
}
- public static <T> T executeSync(final ReadOperation<T> op) throws Throwable {
+ public static <T> T executeSync(final ReadOperation<T> op) {
return executeSync(op, getBinding());
}
- public static <T> T executeSync(final ReadOperation<T> op, final ReadWriteBinding binding) throws Throwable {
+ public static <T> T executeSync(final ReadOperation<T> op, final ReadWriteBinding binding) {
return op.execute(binding);
}
@@ -490,7 +473,7 @@ public final class ClusterFixture {
return results;
}
- public static <T> List<T> collectCursorResults(final BatchCursor<T> batchCursor) throws Throwable {
+ public static <T> List<T> collectCursorResults(final BatchCursor<T> batchCursor) {
List<T> results = new ArrayList<T>();
while (batchCursor.hasNext()) {
results.addAll(batchCursor.next());
|
Remove unused methods and redundant throws clauses in ClusterFixture
|
mongodb_mongo-java-driver
|
train
|
748834d3e632bf168363f5b8f94c5027b206c68a
|
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index <HASH>..<HASH> 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -1,3 +1,2 @@
<?php
-require dirname(__DIR__) . '/vendor/autoload.php';
-require __DIR__ . '/getallheaders.php';
+require __DIR__ . '/../vendor/autoload.php';
|
remove unused declarations in PHP Unit bootstrapper
|
slimphp_Slim-Http
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.