hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
20d0aae5e179e259cc084842bd93b382684498a2
|
diff --git a/lib/instana/version.rb b/lib/instana/version.rb
index <HASH>..<HASH> 100644
--- a/lib/instana/version.rb
+++ b/lib/instana/version.rb
@@ -1,4 +1,4 @@
module Instana
- VERSION = "1.4.0"
+ VERSION = "1.4.1"
VERSION_FULL = "instana-#{VERSION}"
end
|
Bump gem version to <I>
|
instana_ruby-sensor
|
train
|
8c6511d30a418ea9651437e6f35f549bc4547498
|
diff --git a/js/directives.js b/js/directives.js
index <HASH>..<HASH> 100644
--- a/js/directives.js
+++ b/js/directives.js
@@ -12,7 +12,7 @@ angular.module('kibana.directives', [])
' <span class="editlink panelextra pointer" style="right:15px;top:0px" ' +
'bs-modal="\'partials/paneleditor.html\'" ng-show="panel.editable != false">'+
'<span class="small">{{panel.type}}</span> <i class="icon-cog pointer"></i> '+
- '</span><h4>'+
+ '</span><h4 ng-show="panel.title">'+
'{{panel.title}} '+
'<i class="icon-spinner smaller icon-spin icon-large" ng-show="panelMeta.loading == true && panel.title"></i>'+
'</h4>';
@@ -24,7 +24,8 @@ angular.module('kibana.directives', [])
return {
restrict: 'E',
link: function(scope, elem, attrs) {
- var _t = '<i class="icon-question-sign" bs-tooltip="\''+elem.text()+'\'"></i>';
+ var _t = '<i class="icon-'+(attrs.icon||'question-sign')+'" bs-tooltip="\''+
+ kbn.addslashes(elem.text())+'\'"></i>';
elem.replaceWith($compile(angular.element(_t))(scope));
}
};
@@ -96,5 +97,37 @@ angular.module('kibana.directives', [])
});
});
};
-}]);
+}])
+.directive('dashUpload', function(timer, dashboard, alertSrv){
+ return {
+ restrict: 'A',
+ link: function(scope, elem, attrs) {
+ function file_selected(evt) {
+ var files = evt.target.files; // FileList object
+
+ // files is a FileList of File objects. List some properties.
+ var output = [];
+ var readerOnload = function(theFile) {
+ return function(e) {
+ dashboard.dash_load(JSON.parse(e.target.result));
+ scope.$apply();
+ };
+ };
+ for (var i = 0, f; f = files[i]; i++) {
+ var reader = new FileReader();
+ reader.onload = (readerOnload)(f);
+ reader.readAsText(f);
+ }
+ }
+
+ // Check for the various File API support.
+ if (window.File && window.FileReader && window.FileList && window.Blob) {
+ // Something
+ document.getElementById('dashupload').addEventListener('change', file_selected, false);
+ } else {
+ alertSrv.set('Oops','Sorry, the HTML5 File APIs are not fully supported in this browser.','error');
+ }
+ }
+ };
+});
|
Moved dashUpload, added icon attribute to tip directive
|
grafana_grafana
|
train
|
52699bd6ddedc399a2d93af8f630dde2a4d2ad63
|
diff --git a/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java b/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java
index <HASH>..<HASH> 100644
--- a/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java
+++ b/handler/src/test/java/io/netty/handler/ssl/SSLEngineTest.java
@@ -63,6 +63,7 @@ import java.security.KeyStore;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
@@ -82,6 +83,7 @@ import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManagerFactorySpi;
@@ -2637,6 +2639,28 @@ public abstract class SSLEngineTest {
}
}
+ @Test
+ public void testInvalidCipher() throws Exception {
+ SelfSignedCertificate cert = new SelfSignedCertificate();
+ List<String> cipherList = new ArrayList<String>();
+ Collections.addAll(cipherList, ((SSLSocketFactory) SSLSocketFactory.getDefault()).getDefaultCipherSuites());
+ cipherList.add("InvalidCipher");
+ SSLEngine server = null;
+ try {
+ serverSslCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(sslClientProvider())
+ .ciphers(cipherList).build();
+ server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ // expected when invalid cipher is used.
+ } catch (SSLException expected) {
+ // expected when invalid cipher is used.
+ } finally {
+ cert.delete();
+ cleanupServerSslEngine(server);
+ }
+ }
+
protected SSLEngine wrapEngine(SSLEngine engine) {
return engine;
}
|
Add test to verify that invalid ciphers are handled in all SSLEngine implementations correctly. (#<I>)
Motivation:
<URL>
|
netty_netty
|
train
|
8aa445ca97b15c5182f0b7248634d89a1001b504
|
diff --git a/lib/formatting.js b/lib/formatting.js
index <HASH>..<HASH> 100644
--- a/lib/formatting.js
+++ b/lib/formatting.js
@@ -204,7 +204,7 @@ function $formatQuery(query, values) {
var value = formatValue(values[i]); // expect a simple value;
if (value === null) {
// error: not a simple value;
- throw new Error("Cannot convert type '" + typeof(values[i]) + "' of parameter with index " + i);
+ throw new Error("Cannot convert type '" + typeof(values[i]) + "' of array element with index " + i);
}
query = query.replace(new RegExp(pattern, 'g'), value);
}
diff --git a/test/formatSpec.js b/test/formatSpec.js
index <HASH>..<HASH> 100644
--- a/test/formatSpec.js
+++ b/test/formatSpec.js
@@ -228,19 +228,19 @@ describe("Method as.format", function () {
expect(function(){
pgp.as.format("$1,$2", [{}, {}]);
- }).toThrow("Cannot convert type 'object' of parameter with index 0");
+ }).toThrow("Cannot convert type 'object' of array element with index 0");
// test that errors in type conversion are
// detected and reported from left to right;
expect(function(){
pgp.as.format("$1, $2", [true, function () {}]);
- }).toThrow("Cannot convert type 'function' of parameter with index 1");
+ }).toThrow("Cannot convert type 'function' of array element with index 1");
// test that once a conversion issue is encountered,
// the rest of parameters are not verified;
expect(function(){
pgp.as.format("$1,$2,$3,$4,$5", [1, 2, {}, {}, {}, {}]);
- }).toThrow("Cannot convert type 'object' of parameter with index 2");
+ }).toThrow("Cannot convert type 'object' of array element with index 2");
// testing with lots of variables;
var source = "", dest = "", params = [];
|
Improving error messages for arrays, making them consistent.
|
vitaly-t_pg-promise
|
train
|
356cb84419c23f464eb14668f9f0f2249fdfe2b4
|
diff --git a/directory_components/context_processors.py b/directory_components/context_processors.py
index <HASH>..<HASH> 100644
--- a/directory_components/context_processors.py
+++ b/directory_components/context_processors.py
@@ -70,7 +70,7 @@ def header_footer_processor(request):
'performance': urls.PERFORMANCE_DASHBOARD,
'privacy_and_cookies': urls.PRIVACY_AND_COOKIES,
'terms_and_conditions': urls.TERMS_AND_CONDITIONS,
- 'market_access': urls.build_great_url('market-access/')
+ 'market_access': urls.build_great_url('report-trade-barrier/')
}
if settings.FEATURE_FLAGS['EXPORT_JOURNEY_ON']:
header_footer_urls = {**header_footer_urls, **export_journey_urls}
diff --git a/directory_components/templates/directory_components/header_footer/header.html b/directory_components/templates/directory_components/header_footer/header.html
index <HASH>..<HASH> 100644
--- a/directory_components/templates/directory_components/header_footer/header.html
+++ b/directory_components/templates/directory_components/header_footer/header.html
@@ -143,7 +143,8 @@
{% if features.MARKET_ACCESS_ON %}
<li class="links-list-item column-{{ menu_width }}">
<a id="header-services-market-access" href="{{ header_footer_urls.market_access }}" rel="noopener noreferrer">
- <span> Trade barriers </span>
+ <span>Trade barriers</span>
+ <p>Tell us if you’re having problems getting goods, services or investments into overseas markets</p>
</a>
</li>
{% endif %}
diff --git a/tests/test_context_processors.py b/tests/test_context_processors.py
index <HASH>..<HASH> 100644
--- a/tests/test_context_processors.py
+++ b/tests/test_context_processors.py
@@ -130,7 +130,7 @@ def test_header_footer_processor_export_journey_off(settings):
'performance': 'https://exred.com/performance-dashboard/',
'privacy_and_cookies': 'https://exred.com/privacy-and-cookies/',
'terms_and_conditions': 'https://exred.com/terms-and-conditions/',
- 'market_access': 'https://exred.com/market-access/'
+ 'market_access': 'https://exred.com/report-trade-barrier/'
}
diff --git a/tests/test_header_footer.py b/tests/test_header_footer.py
index <HASH>..<HASH> 100644
--- a/tests/test_header_footer.py
+++ b/tests/test_header_footer.py
@@ -639,7 +639,7 @@ def test_market_access_journey_feature_flag_shows_and_hides_links(
assert not soup.find(id=link_id) is False
assert soup.find(
id=link_id
- ).attrs['href'] == urls.build_great_url('market-access/')
+ ).attrs['href'] == urls.build_great_url('report-trade-barrier/')
else:
assert not soup.find(id=link_id) is True
|
added description and changed market access url
|
uktrade_directory-components
|
train
|
15bb03c969bd2f8ba5ab9b04fd68c983eddb1de1
|
diff --git a/lib/emir/recipes/test/worker.py b/lib/emir/recipes/test/worker.py
index <HASH>..<HASH> 100644
--- a/lib/emir/recipes/test/worker.py
+++ b/lib/emir/recipes/test/worker.py
@@ -87,6 +87,9 @@ class Worker(object):
def para_map(worker, data, nthreads=4, daemons=True):
+ if nthreads <= 1:
+ return map(worker, data)
+
wp = WorkerPool()
for i in data:
|
Using map if the number of threads is 1
|
guaix-ucm_pyemir
|
train
|
c1fa8ce974ddf3326c3c3e6ed6781fd0def47058
|
diff --git a/osmnx/io.py b/osmnx/io.py
index <HASH>..<HASH> 100644
--- a/osmnx/io.py
+++ b/osmnx/io.py
@@ -105,11 +105,11 @@ def save_graphml(G, filepath=None, gephi=False, encoding="utf-8"):
G : networkx.MultiDiGraph
input graph
filepath : string
- path to the GraphML file including extension. if None, use
- default data folder + graph.graphml
+ path to the GraphML file including extension. if None, use default
+ data folder + graph.graphml
gephi : bool
- if True, give each edge a unique key to work around Gephi's
- restrictive interpretation of the GraphML specification
+ if True, give each edge a unique key to workaround Gephi's restrictive
+ interpretation of the GraphML specification
encoding : string
the character encoding for the saved file
@@ -131,38 +131,35 @@ def save_graphml(G, filepath=None, gephi=False, encoding="utf-8"):
if gephi:
- gdf_nodes, gdf_edges = utils_graph.graph_to_gdfs(G)
+ # set each edge's "key" attr as a unique id for gephi compatibility
+ uvk_range = zip(G.edges(keys=True), range(len(G.edges)))
+ nx.set_edge_attributes(G, values=dict(uvk_range), name="key")
- # turn each edge's key into a unique ID for Gephi compatibility
- gdf_edges["key"] = range(len(gdf_edges))
-
- # gephi doesn't handle node attrs named x and y well, so rename
- gdf_nodes["xcoord"] = gdf_nodes["x"]
- gdf_nodes["ycoord"] = gdf_nodes["y"]
- G = utils_graph.graph_from_gdfs(gdf_nodes, gdf_edges)
+ # gephi doesn't handle node attrs named x and y well, so rename them
+ nx.set_node_attributes(G, values=nx.get_node_attributes(G, "x"), name="xcoord")
+ nx.set_node_attributes(G, values=nx.get_node_attributes(G, "y"), name="ycoord")
# remove graph attributes as Gephi only accepts node and edge attrs
G.graph = dict()
else:
# if not gephi, keep graph attrs but stringify all of them for saving
- for dict_key in G.graph:
- G.graph[dict_key] = str(G.graph[dict_key])
+ for attr, value in G.graph.items():
+ G.graph[attr] = str(value)
# stringify all the node attribute values
for _, data in G.nodes(data=True):
- for dict_key in data:
- if gephi and dict_key in {"xcoord", "ycoord"}:
- # don't convert x y values to string if saving for gephi
+ for attr, value in data.items():
+ if gephi and attr in {"xcoord", "ycoord"}:
+ # don't stringify x and y coords if saving for gephi
continue
else:
- # convert all the node attribute values to strings
- data[dict_key] = str(data[dict_key])
+ data[attr] = str(value)
# stringify all the edge attribute values
for _, _, data in G.edges(keys=False, data=True):
- for dict_key in data:
- data[dict_key] = str(data[dict_key])
+ for attr, value in data.items():
+ data[attr] = str(value)
nx.write_graphml(G, path=filepath, encoding=encoding)
utils.log(f'Saved graph as GraphML file at "{filepath}"')
|
speed up gephi graphml saving
|
gboeing_osmnx
|
train
|
5826156c837739ffa122c823546272d4e932debe
|
diff --git a/src/Mapper/Memory/ArrayMapper.php b/src/Mapper/Memory/ArrayMapper.php
index <HASH>..<HASH> 100644
--- a/src/Mapper/Memory/ArrayMapper.php
+++ b/src/Mapper/Memory/ArrayMapper.php
@@ -135,11 +135,8 @@ abstract class ArrayMapper extends BaseMapper
}
$storedData[$primaryValue] = NULL;
$this->saveEntityData($storedData);
- } catch (\Exception $e) { // finally workaround
- }
- $this->unlock();
- if (isset($e)) {
- throw $e;
+ } finally {
+ $this->unlock();
}
}
diff --git a/src/Repository/Repository.php b/src/Repository/Repository.php
index <HASH>..<HASH> 100644
--- a/src/Repository/Repository.php
+++ b/src/Repository/Repository.php
@@ -310,14 +310,10 @@ abstract class Repository extends Object implements IRepository
$this->fireEvent($entity, 'onAfterPersist');
}
- } catch (\Exception $e) {} // finally workaround
-
- if ($isRunner) {
- $queue = NULL;
- }
-
- if (isset($e)) {
- throw $e;
+ } finally {
+ if ($isRunner) {
+ $queue = NULL;
+ }
}
return $entity;
|
php <I>: removed finally workarounds
|
nextras_orm
|
train
|
2afa8b6b81dfdd0ac89661e61d5ed7df7e7d0765
|
diff --git a/core/src/main/java/jenkins/model/ModelObjectWithContextMenu.java b/core/src/main/java/jenkins/model/ModelObjectWithContextMenu.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/jenkins/model/ModelObjectWithContextMenu.java
+++ b/core/src/main/java/jenkins/model/ModelObjectWithContextMenu.java
@@ -25,6 +25,7 @@ import org.xml.sax.helpers.DefaultHandler;
import javax.servlet.ServletException;
import java.io.IOException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -190,7 +191,11 @@ public interface ModelObjectWithContextMenu extends ModelObject {
public ContextMenu subMenu;
public MenuItem(String url, String icon, String displayName) {
- this.url = URI.create(Stapler.getCurrentRequest().getRequestURI()).resolve(url).toString();
+ try {
+ this.url = new URI(Stapler.getCurrentRequest().getRequestURI()).resolve(new URI(url)).toString();
+ } catch (URISyntaxException x) {
+ throw new IllegalArgumentException("Bad URI from " + Stapler.getCurrentRequest().getRequestURI() + " vs. " + url, x);
+ }
this.icon = icon;
this.displayName = Util.escape(displayName);
}
|
Better diagnosis of URISyntaxException thrown when constructing context menus.
|
jenkinsci_jenkins
|
train
|
0358c8e3e445509095b7daf510162dd2c663d4c4
|
diff --git a/lib/secure_headers/configuration.rb b/lib/secure_headers/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/secure_headers/configuration.rb
+++ b/lib/secure_headers/configuration.rb
@@ -71,6 +71,7 @@ module SecureHeaders
ALL_HEADER_CLASSES.each do |klass|
config.send("#{klass::CONFIG_KEY}=", OPT_OUT)
end
+ config.dynamic_csp = OPT_OUT
end
add_configuration(NOOP_CONFIGURATION, noop_config)
diff --git a/lib/secure_headers/headers/policy_management.rb b/lib/secure_headers/headers/policy_management.rb
index <HASH>..<HASH> 100644
--- a/lib/secure_headers/headers/policy_management.rb
+++ b/lib/secure_headers/headers/policy_management.rb
@@ -196,6 +196,7 @@ module SecureHeaders
# additions = { script_src: %w(google.com)} then idempotent_additions? would return
# because google.com is already in the config.
def idempotent_additions?(config, additions)
+ return true if config == OPT_OUT && additions == OPT_OUT
return false if config == OPT_OUT
config == combine_policies(config, additions)
end
diff --git a/spec/lib/secure_headers_spec.rb b/spec/lib/secure_headers_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/secure_headers_spec.rb
+++ b/spec/lib/secure_headers_spec.rb
@@ -38,6 +38,7 @@ module SecureHeaders
ALL_HEADER_CLASSES.each do |klass|
expect(hash[klass::CONFIG_KEY]).to be_nil
end
+ expect(hash.count).to eq(0)
end
it "allows you to override X-Frame-Options settings" do
|
Opting out of all protection would raise an exception because the idempotency check was wrong
|
twitter_secure_headers
|
train
|
2193d902ed7b8ba41a5d38462633d4d4c7e2efa9
|
diff --git a/collatex-core/src/main/java/eu/interedition/collatex/dekker/editgraphaligner/EditGraphAligner.java b/collatex-core/src/main/java/eu/interedition/collatex/dekker/editgraphaligner/EditGraphAligner.java
index <HASH>..<HASH> 100644
--- a/collatex-core/src/main/java/eu/interedition/collatex/dekker/editgraphaligner/EditGraphAligner.java
+++ b/collatex-core/src/main/java/eu/interedition/collatex/dekker/editgraphaligner/EditGraphAligner.java
@@ -165,10 +165,10 @@ public class EditGraphAligner extends CollationAlgorithm.Base {
Score fromUpper = calculateFromUpper(vertexSetByRank, scorer, y, x, previousY, witnessToken, cube);
Score max = max(asList(fromUpperLeft, fromLeft, fromUpper), comparingInt(score -> score.globalScore));
this.cells[y][x] = max;
- if (max.type.equals(Score.Type.match)) {
- // remove the matched token from vertexSetByRank so it won't be matched again.
- vertexSetByRank.get(x).removeIf(t -> comparator.compare(witnessToken, t.tokens().iterator().next()) == 0);
- }
+// if (max.type.equals(Score.Type.match)) {
+// // remove the matched token from vertexSetByRank so it won't be matched again.
+// vertexSetByRank.get(x).removeIf(t -> comparator.compare(witnessToken, t.tokens().iterator().next()) == 0);
+// }
}));
// debug only
@@ -196,11 +196,14 @@ public class EditGraphAligner extends CollationAlgorithm.Base {
private Score calculateFromUpper(Map<Integer, Set<VariantGraph.Vertex>> vertexSetByRank, Scorer scorer, int y, int x, int previousY, Token witnessToken, MatchCube matchCube) {
Score fromUpperAsGap = scorer.gap(x, y, this.cells[previousY][x]);
-// boolean canMatch = matchCube.hasMatch(previousY, x);
-
- boolean canMatch = vertexSetByRank.get(x).stream()//
- .map(v -> v.tokens().iterator().next())//
- .anyMatch(t -> comparator.compare(t, witnessToken) == 0);
+ boolean canMatch = matchCube.hasMatch(previousY-1, x-1);
+//
+// boolean canMatch1 = vertexSetByRank.get(x).stream()//
+// .map(v -> v.tokens().iterator().next())//
+// .anyMatch(t -> comparator.compare(t, witnessToken) == 0);
+// if (canMatch!=canMatch1){
+// System.err.println("discrepancy for x="+x+", y="+y+", should be "+canMatch1);
+// }
if (canMatch) {
Score fromUpperAsScore = scorer.score(x, y, this.cells[previousY][x]);
return fromUpperAsScore.type.equals(Score.Type.match) ? fromUpperAsScore : fromUpperAsGap;
|
[COL-1] Use comparator for TokenIndex only, breaks 2 tests with repeating tokens.
|
interedition_collatex
|
train
|
4fb4e8763541026e7abf667788d893043a078576
|
diff --git a/modules/citrus-admin/src/main/java/com/consol/citrus/admin/service/TestCaseService.java b/modules/citrus-admin/src/main/java/com/consol/citrus/admin/service/TestCaseService.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-admin/src/main/java/com/consol/citrus/admin/service/TestCaseService.java
+++ b/modules/citrus-admin/src/main/java/com/consol/citrus/admin/service/TestCaseService.java
@@ -61,9 +61,9 @@ public class TestCaseService {
@Autowired
private AppContextHolder appContextHolder;
-
- /** Project home property name */
- private static final String PROJECT_HOME = "project.home";
+
+ @Autowired
+ private ConfigService configService;
/** Base package for test cases to look for */
private static final String BASE_PACKAGE = "test.base.package";
@@ -123,7 +123,7 @@ public class TestCaseService {
result.setTestCase(testCase);
try {
- Citrus citrus = new Citrus(new GnuParser().parse(new CitrusCliOptions(), new String[] { "-test", testName, "-testdir", System.getProperty(PROJECT_HOME) }));
+ Citrus citrus = new Citrus(new GnuParser().parse(new CitrusCliOptions(), new String[] { "-test", testName, "-testdir", configService.getProjectHome().getAbsolutePath() }));
citrus.run();
result.setSuccess(true);
|
test case service now using config service
|
citrusframework_citrus
|
train
|
c756e5092a1a810ec7a811854028645a69231085
|
diff --git a/src/main/java/act/util/ClassDetector.java b/src/main/java/act/util/ClassDetector.java
index <HASH>..<HASH> 100644
--- a/src/main/java/act/util/ClassDetector.java
+++ b/src/main/java/act/util/ClassDetector.java
@@ -35,6 +35,7 @@ public abstract class ClassDetector extends ByteCodeVisitor {
private static class FilteredClassDetector extends ClassDetector {
private final ClassFilter filter;
private boolean found = false;
+ private boolean skip = false;
FilteredClassDetector(ClassFilter filter) {
E.NPE(filter);
@@ -67,9 +68,11 @@ public abstract class ClassDetector extends ByteCodeVisitor {
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
if (filter.noAbstract() && ((access & ACC_ABSTRACT) != 0 || (access & ACC_INTERFACE) != 0)) {
+ skip = true;
return;
}
if (filter.publicOnly() && (access & ACC_PUBLIC) != 1) {
+ skip = true;
return;
}
Class<?> superType = filter.superType();
@@ -94,7 +97,7 @@ public abstract class ClassDetector extends ByteCodeVisitor {
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
AnnotationVisitor av = super.visitAnnotation(desc, visible);
- if (found) {
+ if (found || skip) {
return av;
}
if (isExtendsAnnotation(desc)) {
|
fix issue: the public and non abstract restriction not applied to AnnotationClassFinder
|
actframework_actframework
|
train
|
ba37b4ba11eddcebe1eded3a37df962f385b3f8e
|
diff --git a/js2py/internals/simplex.py b/js2py/internals/simplex.py
index <HASH>..<HASH> 100644
--- a/js2py/internals/simplex.py
+++ b/js2py/internals/simplex.py
@@ -147,10 +147,10 @@ def js_dtoa(number):
elif number == 0.:
return u'0'
elif abs(number) < 1e-6 or abs(number) >= 1e21:
- frac, exponent = unicode(float(number)).split('e')
+ frac, exponent = unicode(repr(float(number))).split('e')
# Remove leading zeros from the exponent.
exponent = int(exponent)
return frac + ('e' if exponent < 0 else 'e+') + unicode(exponent)
elif isinstance(number, long) or number.is_integer(): # dont print .0
return unicode(int(number))
- return unicode(number) # python representation should be equivalent.
\ No newline at end of file
+ return unicode(repr(number)) # python representation should be equivalent.
|
Fix inconsistency between py2 and py3 jsdtoa
|
PiotrDabkowski_Js2Py
|
train
|
4771e550d34d0f85bb9512f49d02be248324bfd0
|
diff --git a/doc-src/HAML_CHANGELOG.md b/doc-src/HAML_CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/doc-src/HAML_CHANGELOG.md
+++ b/doc-src/HAML_CHANGELOG.md
@@ -3,6 +3,11 @@
* Table of contents
{:toc}
+## 2.2.10 (Unreleased)
+
+* Fixed a bug where elements with dynamic attributes and no content
+ would have too much whitespace between the opening and closing tag.
+
## [2.2.9](http://github.com/nex3/haml/commit/2.2.9)
* Fixed a bug where Haml's text was concatenated to the wrong buffer
diff --git a/lib/haml/precompiler.rb b/lib/haml/precompiler.rb
index <HASH>..<HASH> 100644
--- a/lib/haml/precompiler.rb
+++ b/lib/haml/precompiler.rb
@@ -727,6 +727,7 @@ END
raise SyntaxError.new("Self-closing tags can't have content.", last_line - 1) if self_closing && !value.empty?
self_closing ||= !!( !block_opened? && value.empty? && @options[:autoclose].include?(tag_name) )
+ value = nil if value.empty? && (block_opened? || self_closing)
dont_indent_next_line =
(nuke_outer_whitespace && !block_opened?) ||
@@ -751,7 +752,7 @@ END
return if tag_closed
else
flush_merged_text
- content = value.empty? || parse ? 'nil' : value.dump
+ content = parse ? 'nil' : value.inspect
if attributes_hashes.empty?
attributes_hashes = ''
elsif attributes_hashes.size == 1
@@ -769,7 +770,7 @@ END
return if self_closing
- if value.empty?
+ if value.nil?
push_and_tabulate([:element, [tag_name, nuke_outer_whitespace, nuke_inner_whitespace]])
@output_tabs += 1 unless nuke_inner_whitespace
return
diff --git a/test/haml/engine_test.rb b/test/haml/engine_test.rb
index <HASH>..<HASH> 100644
--- a/test/haml/engine_test.rb
+++ b/test/haml/engine_test.rb
@@ -123,6 +123,17 @@ class EngineTest < Test::Unit::TestCase
assert_equal("<p class='3'>foo</p>", render("%p{:class => 1+2} foo").chomp)
end
+ def test_dynamic_attributes_with_no_content
+ assert_equal(<<HTML, render(<<HAML))
+<p>
+ <a href='http://haml-lang.com'></a>
+</p>
+HTML
+%p
+ %a{:href => "http://" + "haml-lang.com"}
+HAML
+ end
+
def test_nil_should_render_empty_tag
assert_equal("<div class='no_attributes'></div>",
render(".no_attributes{:nil => nil}").chomp)
|
[Haml] Fix a bug with elements with dynamic attributes and no content.
Closes gh-<I>
|
sass_ruby-sass
|
train
|
4aa641e2fe20cf22c245d6cc0c10e90abbfc718d
|
diff --git a/lib/agent/providers/geo/index.js b/lib/agent/providers/geo/index.js
index <HASH>..<HASH> 100644
--- a/lib/agent/providers/geo/index.js
+++ b/lib/agent/providers/geo/index.js
@@ -9,7 +9,7 @@ function log_error(err, strategy) {
exports.get_location = function(cb) {
- strategies.google(google_cb)
+ strategies.native(native_cb)
function native_cb(err, res) {
if (err) {
diff --git a/test/lib/agent/providers/geo/index.js b/test/lib/agent/providers/geo/index.js
index <HASH>..<HASH> 100644
--- a/test/lib/agent/providers/geo/index.js
+++ b/test/lib/agent/providers/geo/index.js
@@ -40,28 +40,28 @@ describe('geoloc fallback', function() {
stubs = {};
}
- // describe('when all strategies fail', function() {
-
- // before(function() {
- // setup_stubs([err_cb]);
- // });
-
- // after(function() {
- // restore_stubs();
- // });
-
- // it('reaches geoip and return no location', function(done) {
- // geo.get_location(function(err, res) {
- // err.should.equal(err);
- // should(res).not.exist;
- // stubs.native.calledOnce.should.equal(true);
- // stubs.google.calledOnce.should.equal(true);
- // stubs.geoip.calledOnce.should.equal(true);
- // done();
- // });
- // });
-
- // });
+ describe('when all strategies fail', function() {
+
+ before(function() {
+ setup_stubs([err_cb]);
+ });
+
+ after(function() {
+ restore_stubs();
+ });
+
+ it('reaches geoip and return no location', function(done) {
+ geo.get_location(function(err, res) {
+ err.should.equal(err);
+ should(res).not.exist;
+ stubs.native.calledOnce.should.equal(true);
+ stubs.google.calledOnce.should.equal(true);
+ stubs.geoip.calledOnce.should.equal(true);
+ done();
+ });
+ });
+
+ });
describe('when running osx', function() {
|
Fix geofencing trigger strategies tests
|
prey_prey-node-client
|
train
|
fecd640b0a02122a060999662e159945cbb4d1e2
|
diff --git a/fluids/units.py b/fluids/units.py
index <HASH>..<HASH> 100644
--- a/fluids/units.py
+++ b/fluids/units.py
@@ -399,7 +399,7 @@ for name in dir(fluids):
obj = wrap_numpydoc_obj(obj)
elif type(obj) is types.ModuleType:
# Functions accessed with the namespace like friction.friction_factor
- # would call the original function - that's no good
+ # would call the original function - leads to user confusion if they are exposed
continue
elif isinstance(obj, str):
continue
|
Trigger readthedocs build for new release
|
CalebBell_fluids
|
train
|
2f9bf9f4182d303fb2a1515840a205229a5d56b6
|
diff --git a/src/Presenters/DashboardPresenter.php b/src/Presenters/DashboardPresenter.php
index <HASH>..<HASH> 100644
--- a/src/Presenters/DashboardPresenter.php
+++ b/src/Presenters/DashboardPresenter.php
@@ -100,7 +100,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create()
->setGraphTitle($this->translator->translate('dashboard.subscriptions.difference.title'))
- ->setGraphHelp($this->translator->translate('dashboard.subscriptions.difference.tooltip'));
+ ->setGraphHelp($this->translator->translate('dashboard.subscriptions.difference.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $graphDataItem) {
$control->addGraphDataItem($graphDataItem);
@@ -138,7 +140,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create()
->setGraphTitle($this->translator->translate('subscriptions.admin.dashboard.subscriptions_recurrency.title'))
- ->setGraphHelp($this->translator->translate('subscriptions.admin.dashboard.subscriptions_recurrency.tooltip'));
+ ->setGraphHelp($this->translator->translate('subscriptions.admin.dashboard.subscriptions_recurrency.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $graphDataItem) {
$control->addGraphDataItem($graphDataItem);
@@ -198,7 +202,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create()
->setGraphTitle($this->translator->translate('subscriptions.admin.dashboard.subscriptions_length.title'))
- ->setGraphHelp($this->translator->translate('subscriptions.admin.dashboard.subscriptions_length.tooltip'));
+ ->setGraphHelp($this->translator->translate('subscriptions.admin.dashboard.subscriptions_length.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $graphDataItem) {
$control->addGraphDataItem($graphDataItem);
@@ -245,7 +251,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create()
->setGraphTitle($this->translator->translate('dashboard.users.new_or_subscribers.title'))
- ->setGraphHelp($this->translator->translate('dashboard.users.new_or_subscribers.tooltip'));
+ ->setGraphHelp($this->translator->translate('dashboard.users.new_or_subscribers.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $graphDataItem) {
$control->addGraphDataItem($graphDataItem);
@@ -270,7 +278,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create();
$control->setGraphTitle($this->translator->translate('dashboard.subscriptions.by_type.title'))
->setGraphHelp($this->translator->translate('dashboard.subscriptions.by_type.tooltip'))
- ->addGraphDataItem($graphDataItem);
+ ->addGraphDataItem($graphDataItem)
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
return $control;
}
@@ -297,7 +307,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create();
$control->setGraphTitle($this->translator->translate('dashboard.subscriptions.only_new_by_type.title'))
->setGraphHelp($this->translator->translate('dashboard.subscriptions.only_new_by_type.tooltip'))
- ->addGraphDataItem($graphDataItem);
+ ->addGraphDataItem($graphDataItem)
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
return $control;
}
@@ -336,7 +348,9 @@ class DashboardPresenter extends AdminPresenter
$control = $factory->create()
->setGraphTitle($this->translator->translate('dashboard.subscriptions.ending.title'))
- ->setGraphHelp($this->translator->translate('dashboard.subscriptions.ending.tooltip'));
+ ->setGraphHelp($this->translator->translate('dashboard.subscriptions.ending.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $graphDataItem) {
$control->addGraphDataItem($graphDataItem);
@@ -388,7 +402,9 @@ SQL
$control = $factory->create();
$control->setGraphTitle($this->translator->translate('dashboard.subscriptions.access.title'))
- ->setGraphHelp($this->translator->translate('dashboard.subscriptions.access.tooltip'));
+ ->setGraphHelp($this->translator->translate('dashboard.subscriptions.access.tooltip'))
+ ->setFrom($this->dateFrom)
+ ->setTo($this->dateTo);
foreach ($items as $item) {
$control->addGraphDataItem($item);
|
Add support for date filter to `GoogleBarGraphGroup` and `GoogleLineGraphGroup`
remp/crm#<I>
|
remp2020_crm-subscriptions-module
|
train
|
6bc8eb818327d6ad4172253deb20d4bd2a4674a1
|
diff --git a/client/lib/purchases/stored-cards/store.js b/client/lib/purchases/stored-cards/store.js
index <HASH>..<HASH> 100644
--- a/client/lib/purchases/stored-cards/store.js
+++ b/client/lib/purchases/stored-cards/store.js
@@ -1,7 +1,21 @@
/**
+ * External Dependencies
+ */
+import assign from 'lodash/object/assign';
+import find from 'lodash/collection/find';
+
+/**
* Internal dependencies
*/
import { createReducerStore } from 'lib/store';
import { getInitialState, reducer } from './reducer';
-export default createReducerStore( reducer, getInitialState() );
+const StoredCardsStore = createReducerStore( reducer, getInitialState() );
+
+assign( StoredCardsStore, {
+ getByCardId( cardId ) {
+ return find( this.get().list, { id: cardId } );
+ }
+} );
+
+export default StoredCardsStore;
diff --git a/client/lib/purchases/stored-cards/test/store-test.js b/client/lib/purchases/stored-cards/test/store-test.js
index <HASH>..<HASH> 100644
--- a/client/lib/purchases/stored-cards/test/store-test.js
+++ b/client/lib/purchases/stored-cards/test/store-test.js
@@ -65,6 +65,16 @@ describe( 'Stored Cards Store', () => {
} );
} );
+ it( 'should return an object with a card for a specific id', () => {
+ expect( StoredCardsStore.getByCardId( 12345 ) ).to.be.eql( {
+ id: 12345,
+ expiry: '2016-11-30',
+ number: 2596,
+ type: 'amex',
+ name: 'Jane Doe'
+ } );
+ } );
+
it( 'should return an object with the previous list of cards and fetching disabled when fetching failed', () => {
Dispatcher.handleViewAction( {
type: ActionTypes.STORED_CARDS_FETCH_FAILED,
|
Purchases: Add method to retrieve a card by id in the Stored Cards store
|
Automattic_wp-calypso
|
train
|
6847298f736575e86be2b0c51dda1899b2fce5ad
|
diff --git a/packages/bonde-admin-canary/src/scenes/Logged/scenes/Home/components/TableCardGadget.js b/packages/bonde-admin-canary/src/scenes/Logged/scenes/Home/components/TableCardGadget.js
index <HASH>..<HASH> 100644
--- a/packages/bonde-admin-canary/src/scenes/Logged/scenes/Home/components/TableCardGadget.js
+++ b/packages/bonde-admin-canary/src/scenes/Logged/scenes/Home/components/TableCardGadget.js
@@ -19,7 +19,7 @@ const TableCardGadget = ({
onClickRow
}) => {
const showPagination = !!(
- pageIndex !== undefined && pageTotal && pageTotal > 0 && renderPagination
+ pageIndex !== undefined && pageTotal && pageTotal > 1 && renderPagination
)
return (
@@ -47,18 +47,7 @@ const TableCardGadget = ({
/>
)}
/>
- {showPagination && (
- <div
- style={{
- textAlign: 'right',
- position: 'absolute',
- bottom: '-7px',
- right: 0
- }}
- >
- {renderPagination()}
- </div>
- )}
+ {showPagination && renderPagination()}
</Flexbox>
</Gadget>
)
|
chore(admin-canary): remove layout absolute for pagination on Table
|
nossas_bonde-client
|
train
|
8616b766b1a3d619e61bf31cdfcdad94dcecbae9
|
diff --git a/src/oem/oem.go b/src/oem/oem.go
index <HASH>..<HASH> 100644
--- a/src/oem/oem.go
+++ b/src/oem/oem.go
@@ -74,7 +74,8 @@ func init() {
configs.Register(Config{
name: "ec2",
flags: map[string]string{
- "provider": "ec2",
+ "provider": "ec2",
+ "online-timeout": "0",
},
})
configs.Register(Config{
|
oem: remove timeout for EC2
We've seen cases if AWS taking <I> seconds to offer a DHCP lease. Rather
than playing cat and mouse with them, just remove the timeout
altogether. The emergency shell doesn't buy us anything anyway, given
that the console is not interactive.
|
coreos_ignition
|
train
|
e76102ffd51d781bb5f714dc65293051fe896916
|
diff --git a/lib/declarative_authorization/in_controller.rb b/lib/declarative_authorization/in_controller.rb
index <HASH>..<HASH> 100644
--- a/lib/declarative_authorization/in_controller.rb
+++ b/lib/declarative_authorization/in_controller.rb
@@ -416,6 +416,10 @@ module Authorization
# one. This is used to automatically load the parent object, e.g.
# @+company+ from params[:company_id] for a BranchController nested in
# a CompanyController.
+ # [:+shallow+]
+ # Only relevant when used in conjunction with +nested_in+. Specifies a nested resource
+ # as being a shallow nested resource, resulting in the controller not attempting to
+ # load a parent object for the following actions: :+show+, :+edit+, :+update+, :+destroy+
# [:+no_attribute_check+]
# Allows to set actions for which no attribute check should be perfomed.
# See filter_access_to on details. By default, with no +nested_in+,
@@ -449,7 +453,8 @@ module Authorization
unless options[:nested_in].blank?
load_parent_method = :"load_#{options[:nested_in].to_s.singularize}"
- before_filter do |controller|
+ shallow_exceptions = options[:shallow] ? {:except => [ :show, :edit, :update, :destroy ]} : {}
+ before_filter shallow_exceptions do |controller|
if controller.respond_to?(load_parent_method)
controller.send(load_parent_method)
else
diff --git a/test/controller_filter_resource_access_test.rb b/test/controller_filter_resource_access_test.rb
index <HASH>..<HASH> 100644
--- a/test/controller_filter_resource_access_test.rb
+++ b/test/controller_filter_resource_access_test.rb
@@ -101,10 +101,11 @@ class ParentMock < MockDataObject
end
end
class NestedResourcesController < MocksController
- filter_resource_access :nested_in => :parent_mocks
+ filter_resource_access :nested_in => :parent_mocks, :shallow => true
define_resource_actions
end
class NestedResourcesControllerTest < ActionController::TestCase
+
def test_nested_filter_index
reader = Authorization::Reader::DSLReader.new
reader.parse %{
@@ -119,12 +120,15 @@ class NestedResourcesControllerTest < ActionController::TestCase
allowed_user = MockUser.new(:allowed_role)
request!(MockUser.new(:another_role), :index, reader, :parent_mock_id => "2")
+ # assert !assigns(:parent_mock) # Fails
assert !@controller.authorized?
request!(allowed_user, :index, reader, :parent_mock_id => "2",
:clear => [:@nested_resource, :@parent_mock])
+ # assert !assigns(:parent_mock) # Fails
assert !@controller.authorized?
request!(allowed_user, :index, reader, :parent_mock_id => "1",
:clear => [:@nested_resource, :@parent_mock])
+ assert assigns(:parent_mock)
assert @controller.authorized?
end
@@ -143,8 +147,10 @@ class NestedResourcesControllerTest < ActionController::TestCase
allowed_user = MockUser.new(:allowed_role)
request!(allowed_user, :show, reader, :id => "2", :parent_mock_id => "2")
assert !@controller.authorized?
- request!(allowed_user, :show, reader, :id => "1", :parent_mock_id => "1",
+ request!(allowed_user, :show, reader, :id => "1",
:clear => [:@nested_resource, :@parent_mock])
+ assert !assigns(:parent_mock)
+ assert assigns(:nested_resource)
assert @controller.authorized?
end
@@ -163,10 +169,14 @@ class NestedResourcesControllerTest < ActionController::TestCase
allowed_user = MockUser.new(:allowed_role)
request!(allowed_user, :new, reader, :parent_mock_id => "2",
:nested_resource => {:id => "2"})
+ # assert !assigns(:parent_mock) # Fails
+ # assert !assigns(:nested_resource) # Fails
assert !@controller.authorized?
request!(allowed_user, :new, reader, :parent_mock_id => "1",
:nested_resource => {:id => "1"},
:clear => [:@nested_resource, :@parent_mock])
+ assert assigns(:parent_mock)
+ assert assigns(:nested_resource)
assert @controller.authorized?
end
end
|
Add :shallow option to filter_resource_access, allowing a nested resource to be declared as shallow.
This results in controller not attempting to load a parent object for the show, edit, update,
and destroy actions.
|
stffn_declarative_authorization
|
train
|
ddda5c19cb4d5f2da6d630f85181d910c0b301bd
|
diff --git a/worker.rb b/worker.rb
index <HASH>..<HASH> 100644
--- a/worker.rb
+++ b/worker.rb
@@ -27,7 +27,7 @@ begin
puts "sending results for #{j[:id]}"
@results.yput({:id => j[:id],
- :result => result,
+ :output => result,
:retval => retval.to_i})
# add job back onto stack
|
changed :result to :output, so it's more meaningful
|
flapjack_flapjack
|
train
|
2d7072afbc316cdc9c3dbfaabef6326ee0bdbdb2
|
diff --git a/dark/bowtie2.py b/dark/bowtie2.py
index <HASH>..<HASH> 100644
--- a/dark/bowtie2.py
+++ b/dark/bowtie2.py
@@ -166,10 +166,11 @@ class Bowtie2(object):
raise ValueError('makeBAM() has not yet been called.')
self._report("removing primers specified in %s" % bedFile)
+ tempTrimmedBam = "%s.trimmed" % self._bamFile
self._executor.execute(
- "ivar trim -b %s -p result-trimmed -i %s -q 20 -m 30 -s 4 -e" %
- (bedFile, self._bamFile))
- self._executor.execute("mv result-trimmed.bam '%s'" % self._bamFile)
+ "ivar trim -b %s -p %s -i %s -q 20 -m 30 -s 4 -e" %
+ (bedFile, tempTrimmedBam, self._bamFile))
+ self._executor.execute("mv %s '%s'" % (tempTrimmedBam, self._bamFile))
def markDuplicatesPicard(self, picardFile):
"""
|
fixed naming issue with temporary bam file that resulted in concurency problems
|
acorg_dark-matter
|
train
|
50153abc74e91b1f2ab914c2cf6d639f5e813087
|
diff --git a/test/cases/coerced_tests.rb b/test/cases/coerced_tests.rb
index <HASH>..<HASH> 100644
--- a/test/cases/coerced_tests.rb
+++ b/test/cases/coerced_tests.rb
@@ -129,7 +129,7 @@ class CalculationsTest < ActiveRecord::TestCase
coerce_tests! :test_limit_is_kept
def test_limit_is_kept_coerced
- queries = assert_sql { Account.limit(1).count }
+ queries = capture_sql_ss { Account.limit(1).count }
assert_equal 1, queries.length
queries.first.must_match %r{ORDER BY \[accounts\]\.\[id\] ASC OFFSET 0 ROWS FETCH NEXT @0 ROWS ONLY.*@0 = 1}
end
diff --git a/test/cases/helper_sqlserver.rb b/test/cases/helper_sqlserver.rb
index <HASH>..<HASH> 100644
--- a/test/cases/helper_sqlserver.rb
+++ b/test/cases/helper_sqlserver.rb
@@ -17,6 +17,7 @@ module ActiveRecord
include ARTest::SQLServer::CoerceableTest,
ARTest::SQLServer::ConnectionReflection,
+ ARTest::SQLServer::SqlCounterSqlserver,
ActiveSupport::Testing::Stream
let(:logger) { ActiveRecord::Base.logger }
diff --git a/test/support/sql_counter_sqlserver.rb b/test/support/sql_counter_sqlserver.rb
index <HASH>..<HASH> 100644
--- a/test/support/sql_counter_sqlserver.rb
+++ b/test/support/sql_counter_sqlserver.rb
@@ -1,32 +1,27 @@
module ARTest
module SQLServer
- extend self
+ module SqlCounterSqlserver
- attr_accessor :sql_counter_listenter
+ # Only return the log vs. log_all
+ def capture_sql_ss
+ ActiveRecord::SQLCounter.clear_log
+ yield
+ ActiveRecord::SQLCounter.log.dup
+ end
- def ignored_sql
- [ /SELECT SCOPE_IDENTITY/,
- /INFORMATION_SCHEMA\.(TABLES|VIEWS|COLUMNS)/,
- /SELECT @@version/,
- /SELECT @@TRANCOUNT/,
- /(BEGIN|COMMIT|ROLLBACK|SAVE) TRANSACTION/,
- /SELECT CAST\(.* AS .*\) AS value/ ]
end
- def sql_counter_listenters
- ActiveSupport::Notifications.notifier.listeners_for('sql.active_record').select do |listener|
- listener.inspect =~ /ActiveRecord::SQLCounter/
- end
- end
+ ignored_sql = [
+ /INFORMATION_SCHEMA\.(TABLES|VIEWS|COLUMNS)/im,
+ /SELECT @@version/,
+ /SELECT @@TRANCOUNT/,
+ /(BEGIN|COMMIT|ROLLBACK|SAVE) TRANSACTION/,
+ /SELECT CAST\(.* AS .*\) AS value/
+ ]
- def sql_counter_listenters_unsubscribe
- sql_counter_listenters.each { |listener| ActiveSupport::Notifications.unsubscribe(listener) }
- end
+ sqlcounter = ObjectSpace.each_object(ActiveRecord::SQLCounter).to_a.first
+ sqlcounter.instance_variable_set :@ignore, Regexp.union(ignored_sql.push(sqlcounter.ignore))
end
end
-
-ActiveRecord::SQLCounter.ignored_sql.concat ARTest::SQLServer.ignored_sql
-ARTest::SQLServer.sql_counter_listenters_unsubscribe
-ARTest::SQLServer.sql_counter_listenter = ActiveSupport::Notifications.subscribe 'sql.active_record', ActiveRecord::SQLCounter.new
|
[Rails5] New SQL counter hacks and helper.
|
rails-sqlserver_activerecord-sqlserver-adapter
|
train
|
8a298a274a3432c44343e091da0f62f5498b944e
|
diff --git a/workload/status/formatted.go b/workload/status/formatted.go
index <HASH>..<HASH> 100644
--- a/workload/status/formatted.go
+++ b/workload/status/formatted.go
@@ -7,6 +7,8 @@ import (
"strings"
)
+var allFields = strings.Split("unit machine id type payload-class tags status", " ")
+
type formattedPayload struct {
Unit string `json:"unit" yaml:"unit"`
Machine string `json:"machine" yaml:"machine"`
@@ -43,7 +45,7 @@ func (fp formattedPayload) lookUp(field string) string {
func (fp formattedPayload) strings(fields ...string) []string {
if len(fields) == 0 {
- fields = strings.Split("unit machine id type payload-class tags status", " ")
+ fields = allFields
}
var result []string
|
Factor out allFields.
|
juju_juju
|
train
|
762074a35adac44efe12e19ce0e810a57cc335c8
|
diff --git a/linux_backend/container_pool/container_pool.go b/linux_backend/container_pool/container_pool.go
index <HASH>..<HASH> 100644
--- a/linux_backend/container_pool/container_pool.go
+++ b/linux_backend/container_pool/container_pool.go
@@ -255,6 +255,7 @@ func (p *LinuxContainerPool) Create(spec warden.ContainerSpec) (linux_backend.Co
})
p.uidPool.Release(uid)
p.networkPool.Release(network)
+ p.destroy(p.logger, container.ID())
return nil, err
}
diff --git a/linux_backend/container_pool/container_pool_test.go b/linux_backend/container_pool/container_pool_test.go
index <HASH>..<HASH> 100644
--- a/linux_backend/container_pool/container_pool_test.go
+++ b/linux_backend/container_pool/container_pool_test.go
@@ -104,7 +104,6 @@ var _ = Describe("Container pool", func() {
Ω(pool.MaxContainers()).Should(Equal(42))
})
})
-
})
Describe("setup", func() {
@@ -490,13 +489,15 @@ var _ = Describe("Container pool", func() {
})
Context("when executing create.sh fails", func() {
+ var containerPath string
nastyError := errors.New("oh no!")
BeforeEach(func() {
fakeRunner.WhenRunning(
fake_command_runner.CommandSpec{
Path: "/root/path/create.sh",
- }, func(*exec.Cmd) error {
+ }, func(cmd *exec.Cmd) error {
+ containerPath = cmd.Args[1]
return nastyError
},
)
@@ -509,6 +510,23 @@ var _ = Describe("Container pool", func() {
Ω(fakeUIDPool.Released).Should(ContainElement(uint32(10000)))
Ω(fakeNetworkPool.Released).Should(ContainElement("1.2.0.0/30"))
})
+
+ It("deletes the container's directory", func() {
+ pool.Create(warden.ContainerSpec{})
+
+ executedCommands := fakeRunner.ExecutedCommands()
+ lastCommand := executedCommands[len(executedCommands)-1]
+ Ω(lastCommand.Path).Should(Equal("/root/path/destroy.sh"))
+ Ω(lastCommand.Args[1]).Should(Equal(containerPath))
+ })
+
+ It("cleans up the rootfs for the container", func() {
+ pool.Create(warden.ContainerSpec{})
+
+ Ω(defaultFakeRootFSProvider.CleanedUp()).Should(Equal([]string{
+ defaultFakeRootFSProvider.Provided()[0].ID,
+ }))
+ })
})
})
|
Remove container directory when create.sh fails
[#<I>]
|
cloudfoundry-attic_garden-linux
|
train
|
e8f067238584e86cf750ff5807be581dc65612e4
|
diff --git a/test/agent_test.rb b/test/agent_test.rb
index <HASH>..<HASH> 100644
--- a/test/agent_test.rb
+++ b/test/agent_test.rb
@@ -39,6 +39,12 @@ class AgentTest < Minitest::Test
end
def test_failed_entity_data_report
+ url = "http://#{::Instana.config[:agent_host]}:#{::Instana.config[:agent_port]}/com.instana.plugin.ruby.discovery"
+ json = { 'pid' => Process.pid, 'agentUuid' => 'abc' }.to_json
+ stub_request(:put, url).to_return(:body => json, :status => 200)
+
+ ::Instana.agent.announce_sensor
+
url = "http://#{::Instana.config[:agent_host]}:#{::Instana.config[:agent_port]}/com.instana.plugin.ruby.#{Process.pid}"
stub_request(:post, url).to_raise(Errno::ECONNREFUSED)
|
Call announce for a proper entity failure.
|
instana_ruby-sensor
|
train
|
f65ad78f73aaf0df3223f8cd4dc98fc927348b6c
|
diff --git a/lib/sfn/command/destroy.rb b/lib/sfn/command/destroy.rb
index <HASH>..<HASH> 100644
--- a/lib/sfn/command/destroy.rb
+++ b/lib/sfn/command/destroy.rb
@@ -45,12 +45,17 @@ module Sfn
end
if config[:poll]
if stacks.size == 1
+ pstack = stacks.first
begin
- poll_stack(stacks.first)
- rescue Miasma::Error::ApiError::RequestError => error
- unless error.response.code == 404
- raise error
+ poll_stack(pstack)
+ stack = provider.connection.stacks.get(pstack)
+ stack.reload
+ if stack.state.to_s.end_with?("failed")
+ ui.error("Stack #{ui.color(pstack, :bold)} still exists after polling complete.")
+ raise "Failed to successfully destroy stack!"
end
+ rescue Miasma::Error::ApiError::RequestError => error
+ # Ignore if stack cannot be reloaded
end
else
ui.error "Stack polling is not available when multiple stack deletion is requested!"
|
Validate stack is destroyed after destroy polling
|
sparkleformation_sfn
|
train
|
332ed6293166f07d81abb0689c1c9333b08acc6c
|
diff --git a/modules/backend/formwidgets/Repeater.php b/modules/backend/formwidgets/Repeater.php
index <HASH>..<HASH> 100644
--- a/modules/backend/formwidgets/Repeater.php
+++ b/modules/backend/formwidgets/Repeater.php
@@ -233,8 +233,8 @@ class Repeater extends FormWidgetBase
foreach ($items as $index => $groupCode) {
$this->makeItemFormWidget($index, $groupCode);
- $this->indexCount = max((int) $index, $this->indexCount);
}
+ $this->indexCount = max(count($items), $this->indexCount);
}
/**
@@ -291,8 +291,6 @@ class Repeater extends FormWidgetBase
{
self::$onAddItemCalled = true;
- $this->indexCount++;
-
$groupCode = post('_repeater_group');
$this->prepareVars();
@@ -300,7 +298,13 @@ class Repeater extends FormWidgetBase
$this->vars['indexValue'] = $this->indexCount;
$itemContainer = '@#'.$this->getId('items');
- return [$itemContainer => $this->makePartial('repeater_item')];
+
+ // Increase index count after item is created
+ ++$this->indexCount;
+
+ return [
+ $itemContainer => $this->makePartial('repeater_item')
+ ];
}
public function onRemoveItem()
|
Increment index count after new item is created
Effectively starts the repeater item indexes from 0
|
octobercms_october
|
train
|
0c16dc8650f7f0f149c4c2c5b315bd2b481f8073
|
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
index <HASH>..<HASH> 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
@@ -62,8 +62,10 @@ public final class HasContainer implements Serializable {
public boolean test(final Element element) {
if (null != this.value) {
+ // it is OK to evaluate equality of ids via toString() now given that the toString() the test suite
+ // enforces the value of id.()toString() to be a first class representation of the identifier
if (this.key.equals(T.id.getAccessor()))
- return this.predicate.test(element.id(), this.value);
+ return this.predicate.test(element.id().toString(), this.value.toString());
else if (this.key.equals(T.label.getAccessor()))
return this.predicate.test(element.label(), this.value);
else if (element instanceof VertexProperty && this.key.equals(T.value.getAccessor()))
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
index <HASH>..<HASH> 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
@@ -503,10 +503,13 @@ public final class ElementHelper {
public static boolean idExists(final Object id, final Object... providedIds) {
if (0 == providedIds.length) return true;
- if (1 == providedIds.length) return id.equals(providedIds[0]);
+
+ // it is OK to evaluate equality of ids via toString() now given that the toString() the test suite
+ // enforces the value of id.()toString() to be a first class representation of the identifier
+ if (1 == providedIds.length) return id.toString().equals(providedIds[0].toString());
else {
for (final Object temp : providedIds) {
- if (temp.equals(id))
+ if (temp.toString().equals(id.toString()))
return true;
}
return false;
diff --git a/gremlin-groovy-test/src/main/groovy/org/apache/tinkerpop/gremlin/process/traversal/step/map/GroovyVertexTest.groovy b/gremlin-groovy-test/src/main/groovy/org/apache/tinkerpop/gremlin/process/traversal/step/map/GroovyVertexTest.groovy
index <HASH>..<HASH> 100644
--- a/gremlin-groovy-test/src/main/groovy/org/apache/tinkerpop/gremlin/process/traversal/step/map/GroovyVertexTest.groovy
+++ b/gremlin-groovy-test/src/main/groovy/org/apache/tinkerpop/gremlin/process/traversal/step/map/GroovyVertexTest.groovy
@@ -62,7 +62,7 @@ public abstract class GroovyVertexTest {
}
@Override
- public Traversal<Edge, Edge> get_g_EX11X(Object e11Id) {
+ public Traversal<Edge, Edge> get_g_EX11X(final Object e11Id) {
g.E(e11Id);
}
@@ -196,7 +196,7 @@ public abstract class GroovyVertexTest {
}
@Override
- public Traversal<Edge, Edge> get_g_EX11X(Object e11Id) {
+ public Traversal<Edge, Edge> get_g_EX11X(final Object e11Id) {
ComputerTestHelper.compute("g.E($e11Id)", g)
}
|
Add tests for g.V/E where string values of the id are present as a filter.
|
apache_tinkerpop
|
train
|
3d653a7dd7b33ffaf7dc1ae65bfd624e6bcdd7ee
|
diff --git a/_updateversion.py b/_updateversion.py
index <HASH>..<HASH> 100644
--- a/_updateversion.py
+++ b/_updateversion.py
@@ -26,7 +26,7 @@ def updateversion(path=_HERE):
version_msg = "# Do not edit, pipeline versioning governed by git tags!"
with open(version_py,"w") as fh:
msg = "{0}__version__ = {1}{0}".format(os.linesep, version_git)
- fh.write((version_msg + msg)
+ fh.write(version_msg + msg)
return version_git
diff --git a/tofu/version.py b/tofu/version.py
index <HASH>..<HASH> 100644
--- a/tofu/version.py
+++ b/tofu/version.py
@@ -1,2 +1,2 @@
-# Do not edit this file, pipeline versioning is governed by git tags !
-__version__ = '1.4.1-45-gc925c33'
+# Do not edit, pipeline versioning governed by git tags!
+__version__ = 1.4.1-47-g52808ce
|
[Issue <I>] PEP8 compliance 4
|
ToFuProject_tofu
|
train
|
91fbd650289fc4afd88dd1df1485b9f45bdf0424
|
diff --git a/dopy/manager.py b/dopy/manager.py
index <HASH>..<HASH> 100755
--- a/dopy/manager.py
+++ b/dopy/manager.py
@@ -47,6 +47,9 @@ class DoManager(object):
ssh_key_ids[index] = str(ssh_key_ids[index])
params['ssh_keys'] = ssh_key_ids
json = self.request('/droplets', params=params, method='POST')
+ created_id = json['droplet']['id']
+ json = self.show_droplet(created_id)
+ return json
else:
params = {
'name': name,
@@ -61,7 +64,7 @@ class DoManager(object):
params['ssh_key_ids'] = ssh_key_ids
json = self.request('/droplets/new', params=params)
- return json['droplet']
+ return json['droplet']
def show_droplet(self, id):
json = self.request('/droplets/%s' % id)
|
Show full info on newly created droplet
|
Wiredcraft_dopy
|
train
|
bcbb2984ad854a3f1031b6d0d4994cc4265b82e8
|
diff --git a/src/Codesleeve/AssetPipeline/Commands/AssetsGenerateCommand.php b/src/Codesleeve/AssetPipeline/Commands/AssetsGenerateCommand.php
index <HASH>..<HASH> 100644
--- a/src/Codesleeve/AssetPipeline/Commands/AssetsGenerateCommand.php
+++ b/src/Codesleeve/AssetPipeline/Commands/AssetsGenerateCommand.php
@@ -29,14 +29,14 @@ class AssetsGenerateCommand extends Command
{
$asset = \App::make('asset');
- // we need to turn on concatenation
- // since we are spitting out assets
+ // we need to turn on concatenation
+ // since we are spitting out assets
$config = $asset->getConfig();
- $config['environment'] = $this->option('env');
- $asset->setConfig($config);
+ $config['environment'] = $this->option('env')?: 'production' ;
+ $asset->setConfig($config);
- $generator = new Codesleeve\Sprockets\StaticFileGenerator($asset->getGenerator());
+ $generator = new Codesleeve\Sprockets\StaticFileGenerator($asset->getGenerator());
$generated = $generator->generate(public_path() . '/' . $config['routing.prefix']);
@@ -47,16 +47,4 @@ class AssetsGenerateCommand extends Command
$this->line('Finished. Have a nice day! :)');
}
-
- /**
- * Get the console command options.
- *
- * @return array
- */
- protected function getOptions()
- {
- return array(
- array('env', 'e', InputOption::VALUE_OPTIONAL, 'What environment should we generate assets for? Default: production', 'production'),
- );
- }
}
|
Fix An option named 'env' already exists LogicException
|
CodeSleeve_asset-pipeline
|
train
|
cbc2f61d673dd38026473bd5dcf71b9370126dbc
|
diff --git a/src/main/php/Gomoob/Pushwoosh/Client/Pushwoosh.php b/src/main/php/Gomoob/Pushwoosh/Client/Pushwoosh.php
index <HASH>..<HASH> 100644
--- a/src/main/php/Gomoob/Pushwoosh/Client/Pushwoosh.php
+++ b/src/main/php/Gomoob/Pushwoosh/Client/Pushwoosh.php
@@ -76,20 +76,22 @@ class Pushwoosh implements IPushwoosh
/**
* Create a new instance of the Pushwoosh client.
+ * @param $url string - API server url
*/
- public function __construct()
+ public function __construct($url = '')
{
- $this->cURLClient = new CURLClient();
+ $this->cURLClient = new CURLClient($url);
}
/**
* Utility function used to create a new instance of the Pushwoosh client.
*
+ * @param $url string - API server url
* @return \Gomoob\Pushwoosh\Client\Pushwoosh the new created instance.
*/
- public static function create()
+ public static function create($url = '')
{
- return new Pushwoosh();
+ return new Pushwoosh($url);
}
/**
|
Allow to use own url for API server
|
gomoob_php-pushwoosh
|
train
|
625a1e3e187c411b5752433023f6d2c56bb25705
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,25 +1,37 @@
import io
import os
-import re
import sys
from setuptools import setup, find_packages
-THIS_DIR = os.path.dirname(__file__)
-sys.path.append(os.path.join(THIS_DIR, 'scripts'))
-import cosmic_ray_tooling as tooling
+def local_file(*name):
+ return os.path.join(
+ os.path.dirname(__file__),
+ *name)
-def read(*names, **kwargs):
+def read(name, **kwargs):
with io.open(
- os.path.join(THIS_DIR, *names),
+ name,
encoding=kwargs.get("encoding", "utf8")
) as handle:
return handle.read()
-LONG_DESCRIPTION = read('README.rst', mode='rt')
+# This is unfortunately duplicated from scripts/cosmic_ray_tooling.py. I
+# couldn't find a way to use the original version and still have tox
+# work...hmmm...
+def read_version():
+ "Read the `(version-string, version-info)` from `cosmic_ray/version.py`."
+ version_file = local_file('cosmic_ray', 'version.py')
+ vars = {}
+ with open(version_file) as f:
+ exec(f.read(), {}, vars)
+ return (vars['__version__'], vars['__version_info__'])
+
+
+LONG_DESCRIPTION = read(local_file('README.rst'), mode='rt')
OPERATORS = [
'number_replacer = '
@@ -76,7 +88,7 @@ if sys.version_info < (3, 4):
setup(
name='cosmic_ray',
- version=tooling.read_version(tooling.VERSION_FILE)[0],
+ version=read_version()[0],
packages=find_packages(),
author='Sixty North AS',
|
Fixed tox-related CI problems.
|
sixty-north_cosmic-ray
|
train
|
d372b539d0df9c3e851d87f07a5cebe7523d0394
|
diff --git a/tests/test_expectations.py b/tests/test_expectations.py
index <HASH>..<HASH> 100644
--- a/tests/test_expectations.py
+++ b/tests/test_expectations.py
@@ -35,10 +35,10 @@ num_ind = 4
D_in = 2
D_out = 2
-Xmu = rng.randn(num_data, D_in)
-Xmu_markov = rng.randn(num_data + 1, D_in) # (N+1)xD
+Xmu = ctt(rng.randn(num_data, D_in))
+Xmu_markov = ctt(rng.randn(num_data + 1, D_in)) # (N+1)xD
Xcov = rng.randn(num_data, D_in, D_in)
-Xcov = Xcov @ np.transpose(Xcov, (0, 2, 1))
+Xcov = ctt(Xcov @ np.transpose(Xcov, (0, 2, 1)))
Z = rng.randn(num_ind, D_in)
@@ -48,7 +48,7 @@ def markov_gauss():
Xcross = cov_params[:-1] @ np.transpose(cov_params[1:], (0, 2, 1)) # NxDxD
Xcross = np.concatenate((Xcross, np.zeros((1, D_in, D_in))), 0) # (N+1)xDxD
Xcov = np.stack([Xcov, Xcross]) # 2x(N+1)xDxD
- return MarkovGaussian(ctt(Xmu_markov), ctt(Xcov))
+ return MarkovGaussian(Xmu_markov, ctt(Xcov))
_means = {
@@ -60,12 +60,12 @@ _means = {
_distrs = {
- 'gauss': Gaussian(ctt(Xmu), ctt(Xcov)),
- 'dirac_gauss': Gaussian(ctt(Xmu), ctt(np.zeros((num_data, D_in, D_in)))),
- 'gauss_diag': DiagonalGaussian(ctt(Xmu), ctt(rng.rand(num_data, D_in))),
- 'dirac_diag': DiagonalGaussian(ctt(Xmu), ctt(np.zeros((num_data, D_in)))),
- 'dirac_markov_gauss': MarkovGaussian(ctt(Xmu_markov),
- ctt(np.zeros((2, num_data + 1, D_in, D_in)))),
+ 'gauss': Gaussian(Xmu, Xcov),
+ 'dirac_gauss': Gaussian(Xmu, np.zeros((num_data, D_in, D_in))),
+ 'gauss_diag': DiagonalGaussian(Xmu, rng.rand(num_data, D_in)),
+ 'dirac_diag': DiagonalGaussian(Xmu, np.zeros((num_data, D_in))),
+ 'dirac_markov_gauss': MarkovGaussian(Xmu_markov,
+ np.zeros((2, num_data + 1, D_in, D_in))),
'markov_gauss': markov_gauss()
}
|
Removing ctt from non-parameters
|
GPflow_GPflow
|
train
|
4277d40137a2729261ee00339dfbf2793159aacd
|
diff --git a/cephfs/cephfs_test.go b/cephfs/cephfs_test.go
index <HASH>..<HASH> 100644
--- a/cephfs/cephfs_test.go
+++ b/cephfs/cephfs_test.go
@@ -130,6 +130,11 @@ func TestChangeDir(t *testing.T) {
assert.NotEqual(t, dir1, dir2)
assert.Equal(t, dir1, "/")
assert.Equal(t, dir2, "/asdf")
+
+ err = mount.ChangeDir("/")
+ assert.NoError(t, err)
+ err = mount.RemoveDir("/asdf")
+ assert.NoError(t, err)
}
func TestRemoveDir(t *testing.T) {
|
cephfs: remove directory created in the ChangeDir test
The test function that exercises ChangeDir was creating a directory
and leaving it behind. Add some basic cleanup to the test to try
and avoid leaking stuff between test runs.
|
ceph_go-ceph
|
train
|
4f55b6a5992c62208b7ebc5981a713c0f06dc994
|
diff --git a/Command/SyncThumbsCommand.php b/Command/SyncThumbsCommand.php
index <HASH>..<HASH> 100644
--- a/Command/SyncThumbsCommand.php
+++ b/Command/SyncThumbsCommand.php
@@ -10,34 +10,48 @@
*/
namespace Sonata\MediaBundle\Command;
+use Symfony\Component\Console\Input\InputArgument;
+
use Sonata\MediaBundle\Provider\ImageProvider;
use Sonata\MediaBundle\Document\MediaManager;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+/**
+ * This command can be used to re-generate the thumbnails for all uploaded medias.
+ *
+ * Useful if you have existing media content and added new formats.
+ *
+ */
class SyncThumbsCommand extends ContainerAwareCommand
{
-
public function configure()
- {
- $this->setName('sonata:media:sync');
- $this->setDescription('Sync uploaded image thumbs with new media formats');
+ {
+ $this->setName('sonata:media:sync-thumbnails')
+ ->setDescription('Sync uploaded image thumbs with new media formats')
+ ->setDefinition(array(
+ new InputArgument('context', InputArgument::REQUIRED, 'The context'),
+ new InputArgument('providerName', InputArgument::REQUIRED, 'The provider'),
+ ));
}
public function execute(InputInterface $input, OutputInterface $output)
{
+ $context = $input->getArgument('context');
+ $provider = $input->getArgument('providerName');
+
$container = $this->getContainer();
$manager = $container->get('sonata.media.manager.media');
- $medias = $manager->findBy(array('providerName' => 'sonata.media.provider.image'));
+ $medias = $manager->findBy(array('providerName' => $provider));
- $output->writeln("Loaded " . count($medias) . " images for generating thumbs...");
+ $output->writeln(sprintf("Loaded %s images for generating thumbs (provider: %s)", count($medias), $provider));
foreach ($medias as $media) {
$provider = $manager->getPool()->getProvider($media->getProviderName());
$output->writeln("Generating thumbs for " . $media->getName());
+ $provider->removeThumbnails($media);
$provider->generateThumbnails($media);
-
}
}
}
diff --git a/Provider/BaseProvider.php b/Provider/BaseProvider.php
index <HASH>..<HASH> 100644
--- a/Provider/BaseProvider.php
+++ b/Provider/BaseProvider.php
@@ -99,6 +99,17 @@ abstract class BaseProvider implements MediaProviderInterface
}
/**
+ * remove all linked thumbnails
+ *
+ * @param MediaInterface $media
+ * @return void
+ */
+ public function removeThumbnails(MediaInterface $media)
+ {
+ $this->thumbnail->delete($this, $media);
+ }
+
+ /**
* return the correct format name : providerName_format
*
* @param \Sonata\MediaBundle\Model\MediaInterface $media
|
renamed command, added arguments, removing old thumbs
|
sonata-project_SonataMediaBundle
|
train
|
41944441367699bbfafcc023edffdae05e0875bf
|
diff --git a/cldoc/cmdgir.py b/cldoc/cmdgir.py
index <HASH>..<HASH> 100644
--- a/cldoc/cmdgir.py
+++ b/cldoc/cmdgir.py
@@ -344,7 +344,7 @@ class GirCursor:
def _extract_children(self):
children = []
- if self.typename in ['function', 'method', 'virtual-method']:
+ if self.typename in ['function', 'method', 'virtual-method', 'constructor']:
children = self.node.iterfind(nsgtk('parameters') + '/' + nsgtk('parameter'))
elif self.typename in ['enumeration', 'bitfield']:
children = self.node.iterfind(nsgtk('member'))
@@ -352,7 +352,7 @@ class GirCursor:
self.bases = []
def childgen():
- childtypes = ['function', 'method', 'virtual-method', 'property', 'signal', 'field']
+ childtypes = ['function', 'method', 'constructor', 'virtual-method', 'property', 'signal', 'field']
for child in self.node:
if stripns(child.tag) in childtypes:
@@ -380,7 +380,7 @@ class GirCursor:
@property
def spelling(self):
- if self.typename in ['function', 'method', 'member']:
+ if self.typename in ['function', 'method', 'member', 'constructor']:
n = nsc('identifier')
elif self.typename in ['parameter', 'field']:
n = 'name'
@@ -526,9 +526,8 @@ class GirTree:
return nodes.Field(cursor, GirComment(cursor))
- def parse_constructor(self, node):
- # TODO
- return None
+ def parse_constructor(self, cursor):
+ return nodes.Function(cursor, GirComment(cursor))
def parse_virtual_method(self, node):
# TODO
|
Added support for gobject constructors
|
jessevdk_cldoc
|
train
|
e496194e0d98b281d3e6e79105549ee1c0aa6dc1
|
diff --git a/tests/test_fandjango.py b/tests/test_fandjango.py
index <HASH>..<HASH> 100644
--- a/tests/test_fandjango.py
+++ b/tests/test_fandjango.py
@@ -551,4 +551,27 @@ class TestFacebookWebMiddleware(unittest.TestCase):
assert redirect_url == 'http://example.org/foo/bar/baz'
+ def test_querystring_removal(self):
+ """
+ Facebook related querystring parameters are removed upon successful authentication
+ """
+ client = Client()
+
+ with patch.object(GraphAPI, 'get') as graph_get:
+
+ def side_effect(*args, **kwargs):
+ if args[0] == 'oauth/access_token':
+ return TEST_GRAPH_ACCESS_TOKEN_RESPONSE
+ elif args[0] == 'me':
+ return TEST_GRAPH_ME_RESPONSE
+
+ graph_get.side_effect = side_effect
+
+ response = client.get(
+ path = reverse('home'),
+ data = {
+ 'code': TEST_AUTH_CODE
+ }
+ )
+
assert 'code=' not in response["Location"]
|
Added remove query param test.
|
jgorset_fandjango
|
train
|
af21d6c96860c407d968e74512b6d85dd633d77d
|
diff --git a/pkg/wireguard/agent/agent.go b/pkg/wireguard/agent/agent.go
index <HASH>..<HASH> 100644
--- a/pkg/wireguard/agent/agent.go
+++ b/pkg/wireguard/agent/agent.go
@@ -98,6 +98,17 @@ func (a *Agent) Close() error {
// Init creates and configures the local WireGuard tunnel device.
func (a *Agent) Init(mtuConfig mtu.Configuration) error {
+ addIPCacheListener := false
+ a.Lock()
+ defer func() {
+ // IPCache will call back into OnIPIdentityCacheChange which requires
+ // us to release a.mutex before we can add ourself as a listener.
+ a.Unlock()
+ if addIPCacheListener {
+ a.ipCache.AddListener(a)
+ }
+ }()
+
link := &netlink.Wireguard{LinkAttrs: netlink.LinkAttrs{Name: types.IfaceName}}
err := netlink.LinkAdd(link)
if err != nil && !errors.Is(err, unix.EEXIST) {
@@ -182,7 +193,8 @@ func (a *Agent) Init(mtuConfig mtu.Configuration) error {
}
}
- a.ipCache.AddListener(a)
+ // this is read by the defer statement above
+ addIPCacheListener = true
return nil
}
|
wireguard: Add mutex in Init function
Previously, the Init() function did not lock the WireGuard agent under
the assumption that there can be no concurrent calls into the agent.
That assumption however is false, both Close() (via signal handler
cleanup) and UpdatePeer() (via node manager) can be called concurrently
while Init() is being invoked.
|
cilium_cilium
|
train
|
25555d27f8224ae356fc4fef3dc34d21981b8f35
|
diff --git a/bids/layout/index.py b/bids/layout/index.py
index <HASH>..<HASH> 100644
--- a/bids/layout/index.py
+++ b/bids/layout/index.py
@@ -207,10 +207,10 @@ class BIDSLayoutIndexer(object):
with open(bf.path, 'r') as handle:
try:
payload = json.load(handle)
- except Exception as e:
+ except json.JSONDecodeError as e:
msg = ("Error occurred while trying to decode JSON"
" from file '{}'.".format(bf.path))
- raise Exception(msg) from e
+ raise IOError(msg) from e
else:
payload = None
|
Apply suggestions from code review
Use more specific exception classes.
|
bids-standard_pybids
|
train
|
2d6bfd1937581e6fc277e81b39f4e986380e62d1
|
diff --git a/src/Action/Controller.php b/src/Action/Controller.php
index <HASH>..<HASH> 100644
--- a/src/Action/Controller.php
+++ b/src/Action/Controller.php
@@ -43,7 +43,7 @@ class Controller
/**
* Name of the layout to render.
*/
- public $layout = 'default';
+ public $layout = 'default.phtml';
/**
* The view to be rendered.
|
Add file extension for default controller layout.
|
nirix_radium
|
train
|
4cf527e0b273d29196fac81347b25badb130ba18
|
diff --git a/tests/test_bugs.py b/tests/test_bugs.py
index <HASH>..<HASH> 100644
--- a/tests/test_bugs.py
+++ b/tests/test_bugs.py
@@ -1,3 +1,4 @@
+import copy
import datetime
import responses
import json
@@ -467,3 +468,27 @@ def test_adding_new_field_to_existing_bug():
bug.alias = 'foobar'
diff = bug.diff()
assert diff['alias'] == 'foobar'
+
+@responses.activate
+def test_bug_update_updates_copy_dict():
+ responses.add(responses.GET, 'https://bugzilla.mozilla.org/rest/login',
+ body='{"token": "foobar"}', status=200,
+ content_type='application/json', match_querystring=True)
+ bugzilla = Bugsy("foo", "bar")
+ bug = Bug(bugzilla, **example_return['bugs'][0])
+
+ bug.status = 'NEW'
+ diff = bug.diff()
+ bug_dict = copy.deepcopy(example_return)
+ bug_dict['bugs'][0]['status'] = 'NEW'
+ responses.add(responses.GET, 'https://bugzilla.mozilla.org/rest/bug/1017315',
+ body=json.dumps(bug_dict), status=200,
+ content_type='application/json')
+
+ responses.add(responses.PUT, 'https://bugzilla.mozilla.org/rest/bug/1017315',
+ body=json.dumps(diff), status=200,
+ content_type='application/json')
+
+ bugzilla.put(bug)
+ bug.update()
+ assert bug._copy['status'] == 'NEW'
|
Verify that bug._copy is updated after bug.update()
|
AutomatedTester_Bugsy
|
train
|
c2e23c442f9df310d94ff9b44835096a43257001
|
diff --git a/py3status/modules/pomodoro.py b/py3status/modules/pomodoro.py
index <HASH>..<HASH> 100644
--- a/py3status/modules/pomodoro.py
+++ b/py3status/modules/pomodoro.py
@@ -34,7 +34,10 @@ class Py3status:
self.run = False
elif event['button'] == 3:
- self.__setup('break')
+ if self.status == 'break':
+ self.__setup('start')
+ else:
+ self.__setup('break')
self.run = False
@property
|
A second right-click stops the ongoing break
In case a break is too long for you
|
ultrabug_py3status
|
train
|
39c964604298f9a74e12039c8b63a7ef0009b104
|
diff --git a/src/main/java/zmq/io/net/tcp/TcpUtils.java b/src/main/java/zmq/io/net/tcp/TcpUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/zmq/io/net/tcp/TcpUtils.java
+++ b/src/main/java/zmq/io/net/tcp/TcpUtils.java
@@ -1,11 +1,13 @@
package zmq.io.net.tcp;
import java.io.IOException;
+import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
-import java.nio.channels.NetworkChannel;
+import java.nio.channels.Channel;
import java.nio.channels.SelectableChannel;
+import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import zmq.ZError;
@@ -15,7 +17,18 @@ public class TcpUtils
{
private static interface OptionSetter
{
- void setOption(Socket socket) throws SocketException;
+ boolean setOption(Socket socket) throws SocketException;
+
+ boolean setOption(ServerSocket socket) throws SocketException;
+ }
+
+ private abstract static class SocketOptionSetter implements OptionSetter
+ {
+ @Override
+ public boolean setOption(ServerSocket socket) throws SocketException
+ {
+ return false;
+ }
}
private TcpUtils()
@@ -27,12 +40,13 @@ public class TcpUtils
// Disable Nagle's algorithm. We are doing data batching on 0MQ level,
// so using Nagle wouldn't improve throughput in anyway, but it would
// hurt latency.
- setOption(channel, new OptionSetter()
+ setOption(channel, new SocketOptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
{
socket.setTcpNoDelay(true);
+ return true;
}
});
}
@@ -42,75 +56,96 @@ public class TcpUtils
throws IOException
{
final boolean keepAlive = tcpKeepAlive == 1;
- setOption(channel, new OptionSetter()
+ setOption(channel, new SocketOptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
{
socket.setKeepAlive(keepAlive);
+ return true;
}
});
}
- public static boolean setTcpReceiveBuffer(NetworkChannel channel, final int rcvbuf)
+ public static boolean setTcpReceiveBuffer(Channel channel, final int rcvbuf)
{
return setOption(channel, new OptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
+ {
+ socket.setReceiveBufferSize(rcvbuf);
+ return true;
+ }
+
+ @Override
+ public boolean setOption(ServerSocket socket) throws SocketException
{
socket.setReceiveBufferSize(rcvbuf);
+ return true;
}
});
}
- public static boolean setTcpSendBuffer(NetworkChannel channel, final int sndbuf)
+ public static boolean setTcpSendBuffer(Channel channel, final int sndbuf)
{
- return setOption(channel, new OptionSetter()
+ return setOption(channel, new SocketOptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
{
socket.setSendBufferSize(sndbuf);
+ return true;
}
});
}
- public static boolean setIpTypeOfService(NetworkChannel channel, final int tos)
+ public static boolean setIpTypeOfService(Channel channel, final int tos)
{
- return setOption(channel, new OptionSetter()
+ return setOption(channel, new SocketOptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
{
socket.setTrafficClass(tos);
+ return true;
}
});
}
- public static boolean setReuseAddress(NetworkChannel channel, final boolean reuse)
+ public static boolean setReuseAddress(Channel channel, final boolean reuse)
{
return setOption(channel, new OptionSetter()
{
@Override
- public void setOption(Socket socket) throws SocketException
+ public boolean setOption(Socket socket) throws SocketException
+ {
+ socket.setReuseAddress(reuse);
+ return true;
+ }
+
+ @Override
+ public boolean setOption(ServerSocket socket) throws SocketException
{
socket.setReuseAddress(reuse);
+ return true;
}
});
}
- private static <T> boolean setOption(NetworkChannel channel, OptionSetter setter)
+ private static boolean setOption(Channel channel, OptionSetter setter)
{
- if (channel instanceof SocketChannel) {
- try {
- setter.setOption(((SocketChannel) channel).socket());
- return true;
+ try {
+ if (channel instanceof ServerSocketChannel) {
+ return setter.setOption(((ServerSocketChannel) channel).socket());
}
- catch (SocketException e) {
- throw new ZError.IOException(e);
+ else if (channel instanceof SocketChannel) {
+ return setter.setOption(((SocketChannel) channel).socket());
}
}
+ catch (SocketException e) {
+ throw new ZError.IOException(e);
+ }
return false;
}
|
Make lib usable with Android API < <I>
|
zeromq_jeromq
|
train
|
13375da89b658501ebcf3e0d69de434d0a8a868b
|
diff --git a/cirq/experiments/cross_entropy_benchmarking.py b/cirq/experiments/cross_entropy_benchmarking.py
index <HASH>..<HASH> 100644
--- a/cirq/experiments/cross_entropy_benchmarking.py
+++ b/cirq/experiments/cross_entropy_benchmarking.py
@@ -95,17 +95,17 @@ class CrossEntropyResult:
Attributes:
data: A sequence of NamedTuples, each of which contains two fields:
- num_cycle: the circuit depth as the number of cycles, where
- a cycle consists of a layer of single-qubit gates followed
- by a layer of two-qubit gates.
- xeb_fidelity: the XEB fidelity after the given cycle number.
+ num_cycle: the circuit depth as the number of cycles, where
+ a cycle consists of a layer of single-qubit gates followed
+ by a layer of two-qubit gates.
+ xeb_fidelity: the XEB fidelity after the given cycle number.
repetitions: The number of circuit repetitions used.
purity_data: A sequence of NamedTuples, each of which contains two
fields:
- num_cycle: the circuit depth as the number of cycles, where
- a cycle consists of a layer of single-qubit gates followed
- by a layer of two-qubit gates.
- purity: the purity after the given cycle number.
+ num_cycle: the circuit depth as the number of cycles, where
+ a cycle consists of a layer of single-qubit gates followed
+ by a layer of two-qubit gates.
+ purity: the purity after the given cycle number.
"""
data: List[CrossEntropyPair]
repetitions: int
diff --git a/cirq/ops/common_channels.py b/cirq/ops/common_channels.py
index <HASH>..<HASH> 100644
--- a/cirq/ops/common_channels.py
+++ b/cirq/ops/common_channels.py
@@ -206,9 +206,7 @@ def asymmetric_depolarize(
This channel evolves a density matrix via
- $$
- \sum_i p_i Pi \rho Pi
- $$
+ $ \sum_i p_i Pi \rho Pi $
where i varies from 0 to 4**n-1 and Pi represents n-qubit Pauli operator
(including identity). The input \rho is the density matrix before the
@@ -254,12 +252,9 @@ class DepolarizingChannel(gate_features.SingleQubitGate):
This channel evolves a density matrix via
- $$
- \rho \rightarrow (1 - p) \rho
- + 1 / (4**n - 1) \sum _i P_i X P_i
- $$
+ $ \rho \rightarrow (1 - p) \rho + 1 / (4**n - 1) \sum _i P_i X P_i $
- where P_i are the 4**n - 1 Pauli gates (excluding the identity).
+ where P_i are the $4^n - 1$ Pauli gates (excluding the identity).
Args:
p: The probability that one of the Pauli gates is applied. Each of
@@ -356,12 +351,9 @@ def depolarize(p: float, n_qubits: int = 1) -> DepolarizingChannel:
This channel evolves a density matrix via
- $$
- \rho \rightarrow (1 - p) \rho
- + 1 / (4**n - 1) \sum _i P_i X P_i
- $$
+ $ \rho \rightarrow (1 - p) \rho + 1 / (4**n - 1) \sum _i P_i X P_i $
- where P_i are the 4**n - 1 Pauli gates (excluding the identity).
+ where P_i are the $4^n - 1$ Pauli gates (excluding the identity).
Args:
p: The probability that one of the Pauli gates is applied. Each of
diff --git a/docs/google/devices.md b/docs/google/devices.md
index <HASH>..<HASH> 100644
--- a/docs/google/devices.md
+++ b/docs/google/devices.md
@@ -81,7 +81,13 @@ specific processors.
In addition, please note that all gates will have variations and
errors that vary from device to device and from qubit to qubit.
-This can include both inchorent as well as coherent error.
+This can include both incoherent as well as coherent error.
+
+Note: Gate durations are subject to change based on device or
+configuration. To get gates durations for a specific device, see the
+[Device specification](./specification.md#gate-durations) page. Also
+note that some gates (such as Z gates or Fsim gates) have multiple
+variations that can have different durations.
### One qubit gates
@@ -119,7 +125,7 @@ such as in the following example:
cirq.Z(cirq.GridQubit(5, 5)).with_tags(cirq.google.PhysicalZTag())
```
-Physical Z gates have a duration of 12 ns on most Google devices.
+Physical Z gates have a duration of 20 ns on most Google devices.
### Two Qubit Gates
|
Fix duration documentation for Physical Z (#<I>)
* Fix duration documentation for Physical Z
- Adjust duration of physical Z to <I>ns.
- Add disclaimer and pointer to gate duration docs
- Fix other random indenting that sphinx is complaining about.
Fixes: #<I>
* Change args back to attributes.
* Update cirq/experiments/cross_entropy_benchmarking.py
|
quantumlib_Cirq
|
train
|
be1978616c79cf69a4db56835687cc96f3c10ca8
|
diff --git a/install.js b/install.js
index <HASH>..<HASH> 100644
--- a/install.js
+++ b/install.js
@@ -1,7 +1,7 @@
var binwrap = require("binwrap");
var path = require("path");
-var binVersion = "0.0.6";
+var binVersion = "0.0.7";
var root =
"https://github.com/zwilias/elm-instrument/releases/download/" +
|
Bump elm-instrument version to <I>
|
zwilias_elm-coverage
|
train
|
245c682fdef0d68a11e22b57422c9a38e28cfcb1
|
diff --git a/GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/Throttler.java b/GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/Throttler.java
index <HASH>..<HASH> 100644
--- a/GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/Throttler.java
+++ b/GVRf/Framework/framework/src/main/java/org/gearvrf/asynchronous/Throttler.java
@@ -327,7 +327,7 @@ class Throttler implements Scheduler {
{
request.openStream();
}
- catch (IOException ex)
+ catch (Exception ex)
{
callback.failed(ex, request);
}
|
framework: propagate all exceptions openStream might throw
|
Samsung_GearVRf
|
train
|
067ad5244ef4ee35365cb157439a7bfa1c17978d
|
diff --git a/src/services/Terminal.js b/src/services/Terminal.js
index <HASH>..<HASH> 100644
--- a/src/services/Terminal.js
+++ b/src/services/Terminal.js
@@ -1,4 +1,4 @@
-const {yellow, red, blue} = require('chalk');
+const {gray, yellow, red, blue} = require('chalk');
const readline = require('../lib/readline/readline');
const EventEmitter = require('events');
const {Readable} = require('stream');
@@ -44,6 +44,11 @@ module.exports = class Terminal extends EventEmitter {
this.clearInput();
}
});
+ this._readline.input.prependListener('keypress', (_ev, key) => {
+ if (key.name === 'return') {
+ this._replacePromptInLineWith(gray('>> '));
+ }
+ });
this._readline.input.on('keypress', (ev, key) => {
if (!this._ignoreInput) {
this.emit('keypress', key);
@@ -115,6 +120,11 @@ module.exports = class Terminal extends EventEmitter {
this._restorePrompt();
}
+ _replacePromptInLineWith(prefix) {
+ this._clearLine();
+ this._readline.output.write(prefix + this._readline.line);
+ }
+
_hidePrompt() {
if (this._promptEnabled) {
if (this._line === null) {
|
Differentiate past commands prefix and prompt sequence
The blue command prompt sequence suggests interactivity. Past commands
should not be prefixed in the same way as the command prompt. Replace it
with a gray prompt sequence instead, similarly to browsers.
Change-Id: I1c<I>d<I>d<I>c<I>e6d<I>a4fb2c9a<I>
|
eclipsesource_tabris-js-cli
|
train
|
23aa65f8a0d986e7c3958c42006f2fec1c0be306
|
diff --git a/lib/stack_tracy/sinatra.rb b/lib/stack_tracy/sinatra.rb
index <HASH>..<HASH> 100644
--- a/lib/stack_tracy/sinatra.rb
+++ b/lib/stack_tracy/sinatra.rb
@@ -10,10 +10,9 @@ module StackTracy
def call(env)
request = ::Sinatra::Request.new env
- if request.path.match /^\/tracy-?(.*)?/
- return open($1)
+ if request.path.match /^\/tracy(-.*)?/
+ return open($1.to_s.gsub(/^-/, ""))
end
-
if @before_filter.nil? || !!@before_filter.call(request.path, request.params)
result = nil
stack_tracy @arg || Dir::tmpdir, @options do
@@ -28,7 +27,17 @@ module StackTracy
private
def open(match)
- StackTracy.open match.to_s.empty? ? nil : match, (match.to_s.empty? && @arg.to_s != "dump" && !StackTracy.stack_trace.empty?)
+ if match.empty?
+ if StackTracy.stack_trace.empty?
+ StackTracy.open
+ else
+ StackTracy.dump do |file|
+ StackTracy.open file, true
+ end
+ end
+ else
+ StackTracy.open match
+ end
[200, {"Content-Type" => "text/html;charset=utf-8", "Content-Length" => Rack::Utils.bytesize("").to_s}, ""]
end
|
Improved StackTracy::Sinatra middleware a bit regarding the `/tracy` route
|
archan937_stack_tracy
|
train
|
c75dc6580dd82f53dbd8b1e6565d1753805e4320
|
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100755
--- a/manifest.php
+++ b/manifest.php
@@ -35,7 +35,8 @@ return array(
'taoDeliveryRdf' => '>=1.0',
'taoLti' => '>=5.0.0',
'taoResultServer' => '>=5.0.0',
- 'taoDelivery' => '>=9.0.0'
+ 'taoDelivery' => '>=9.0.0',
+ 'taoOutcomeUi' => '>=5.3.1'
),
'models' => array(
'http://www.tao.lu/Ontologies/TAOLTI.rdf',
|
Added dependency for taoOutcomeUi extension
|
oat-sa_extension-tao-ltideliveryprovider
|
train
|
d8e8fb2be11f214406a2c952cc83e386c58192ae
|
diff --git a/tensor2tensor/rl/trainer_model_based_params.py b/tensor2tensor/rl/trainer_model_based_params.py
index <HASH>..<HASH> 100644
--- a/tensor2tensor/rl/trainer_model_based_params.py
+++ b/tensor2tensor/rl/trainer_model_based_params.py
@@ -325,6 +325,14 @@ def rlmb_base_stochastic_discrete():
@registry.register_hparams
+def rlmb_base_stochastic_discrete_75k_model_steps():
+ """Base setting with stochastic discrete model with 75k WM steps."""
+ hparams = rlmb_base_stochastic_discrete()
+ hparams.model_train_steps = 15000 * 5
+ return hparams
+
+
+@registry.register_hparams
def rlmb_base_stochastic_discrete_200k():
"""Base setting with stochastic discrete model with 200k steps."""
hparams = rlmb_base_stochastic_discrete()
|
Added longer model training option for RLMB
PiperOrigin-RevId: <I>
|
tensorflow_tensor2tensor
|
train
|
2e4c1c86ed59877cc029130bc4b826032a04e9a5
|
diff --git a/django_q/brokers/disque.py b/django_q/brokers/disque.py
index <HASH>..<HASH> 100644
--- a/django_q/brokers/disque.py
+++ b/django_q/brokers/disque.py
@@ -23,6 +23,8 @@ class Disque(Broker):
return self.connection.execute_command('ACKJOB {}'.format(task_id))
def ping(self):
+ if Conf.DISQUE_AUTH:
+ self.connection.execute_command('AUTH {}'.format(Conf.DISQUE_AUTH))
return self.connection.execute_command('HELLO')[0] > 0
def delete(self, task_id):
|
Adds extra AUTH before PING
|
Koed00_django-q
|
train
|
2263a76f4d97ef4f3d93e4b45a31e8c3e522e589
|
diff --git a/superset/utils/webdriver.py b/superset/utils/webdriver.py
index <HASH>..<HASH> 100644
--- a/superset/utils/webdriver.py
+++ b/superset/utils/webdriver.py
@@ -138,7 +138,6 @@ class WebDriverProxy:
img = element.screenshot_as_png
except TimeoutException:
logger.warning("Selenium timed out requesting url %s", url, exc_info=True)
- img = element.screenshot_as_png
except StaleElementReferenceException:
logger.error(
"Selenium got a stale element while requesting url %s",
|
remove eleement reference (#<I>)
|
apache_incubator-superset
|
train
|
921736e431c78c4e50ada1bbe67aaf0099a1f07a
|
diff --git a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
index <HASH>..<HASH> 100644
--- a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
+++ b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java
@@ -456,7 +456,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
final ReplaySession replaySession = replaySessionByIdMap.get(replaySessionId);
if (null == replaySession)
{
- final String errorMessage = "replay session not known: " + replaySessionId;
+ final String errorMessage = "replay session not known for " + replaySessionId;
controlSession.sendResponse(correlationId, ERROR, errorMessage, controlResponseProxy);
}
else
@@ -476,7 +476,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
{
if (recordingSessionByIdMap.size() >= maxConcurrentRecordings)
{
- final String errorMessage = "max concurrent recordings reached " + maxConcurrentRecordings;
+ final String errorMessage = "max concurrent recordings reached of " + maxConcurrentRecordings;
controlSession.sendResponse(correlationId, ERROR, errorMessage, controlResponseProxy);
return;
@@ -484,7 +484,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
if (!catalog.hasRecording(recordingId))
{
- final String errorMessage = "unknown recording " + recordingId;
+ final String errorMessage = "unknown recording id " + recordingId;
controlSession.sendResponse(correlationId, ERROR, errorMessage, controlResponseProxy);
return;
@@ -492,7 +492,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
if (recordingSessionByIdMap.containsKey(recordingId))
{
- final String errorMessage = "cannot extend active recording " + recordingId;
+ final String errorMessage = "cannot extend active recording for " + recordingId;
controlSession.sendResponse(correlationId, ERROR, errorMessage, controlResponseProxy);
return;
@@ -529,7 +529,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
}
else
{
- final String errorMessage = "recording already setup for subscription " + key;
+ final String errorMessage = "recording already setup for subscription to " + key;
controlSession.sendResponse(correlationId, ERROR, errorMessage, controlResponseProxy);
}
}
@@ -591,7 +591,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
dataHeaderFlyweight.termId() != termId ||
dataHeaderFlyweight.streamId() != summary.streamId)
{
- final String msg = "position " + position + " does not match header " + dataHeaderFlyweight;
+ final String msg = position + " position does not match header " + dataHeaderFlyweight;
controlSession.sendResponse(correlationId, ERROR, msg, controlResponseProxy);
return;
}
@@ -857,7 +857,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
{
if (image.joinPosition() != originalRecordingSummary.stopPosition)
{
- final String msg = "cannot extend recording: " + originalRecordingSummary.recordingId +
+ final String msg = "cannot extend recording " + originalRecordingSummary.recordingId +
" image joinPosition " + image.joinPosition() +
" not equal to recording stopPosition " + originalRecordingSummary.stopPosition;
@@ -867,7 +867,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
if (image.termBufferLength() != originalRecordingSummary.termBufferLength)
{
- final String msg = "cannot extend recording: " + originalRecordingSummary.recordingId +
+ final String msg = "cannot extend recording " + originalRecordingSummary.recordingId +
" image termBufferLength " + image.termBufferLength() +
" not equal to recording termBufferLength " + originalRecordingSummary.termBufferLength;
@@ -877,7 +877,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa
if (image.mtuLength() != originalRecordingSummary.mtuLength)
{
- final String msg = "cannot extend recording: " + originalRecordingSummary.recordingId +
+ final String msg = "cannot extend recording " + originalRecordingSummary.recordingId +
" image mtuLength " + image.mtuLength() +
" not equal to recording mtuLength " + originalRecordingSummary.mtuLength;
|
[Java] Error formatting.
|
real-logic_aeron
|
train
|
abb9bd853ff1b6c0a39953d0ab0a4defe7901032
|
diff --git a/dockerclient.go b/dockerclient.go
index <HASH>..<HASH> 100644
--- a/dockerclient.go
+++ b/dockerclient.go
@@ -441,15 +441,39 @@ func (client *DockerClient) MonitorEvents(options *MonitorEventsOptions, stopCha
}
if options.Filters != nil {
filterMap := make(map[string][]string)
- if len(options.Filters.Event) > 0 {
- filterMap["event"] = []string{options.Filters.Event}
+ events := []string{}
+ if options.Filters.Event != "" {
+ events = append(events, options.Filters.Event)
}
- if len(options.Filters.Image) > 0 {
- filterMap["image"] = []string{options.Filters.Image}
+ if len(options.Filters.Events) > 0 {
+ events = append(events, options.Filters.Events...)
}
- if len(options.Filters.Container) > 0 {
- filterMap["container"] = []string{options.Filters.Container}
+ if len(events) > 0 {
+ filterMap["event"] = events
}
+
+ images := []string{}
+ if options.Filters.Image != "" {
+ images = append(images, options.Filters.Image)
+ }
+ if len(options.Filters.Images) > 0 {
+ images = append(images, options.Filters.Images...)
+ }
+ if len(images) > 0 {
+ filterMap["image"] = images
+ }
+
+ containers := []string{}
+ if options.Filters.Container != "" {
+ containers = append(containers, options.Filters.Container)
+ }
+ if len(options.Filters.Containers) > 0 {
+ containers = append(containers, options.Filters.Containers...)
+ }
+ if len(containers) > 0 {
+ filterMap["container"] = containers
+ }
+
if len(filterMap) > 0 {
filterJSONBytes, err := json.Marshal(filterMap)
if err != nil {
diff --git a/types.go b/types.go
index <HASH>..<HASH> 100644
--- a/types.go
+++ b/types.go
@@ -121,9 +121,12 @@ type AttachOptions struct {
}
type MonitorEventsFilters struct {
- Event string `json:",omitempty"`
- Image string `json:",omitempty"`
- Container string `json:",omitempty"`
+ Event string `json:",omitempty"`
+ Events []string `json:",omitempty"`
+ Image string `json:",omitempty"`
+ Images []string `json:",omitempty"`
+ Container string `json:",omitempty"`
+ Containers []string `json:",omitempty"`
}
type MonitorEventsOptions struct {
|
Allow filtering events on multiple event/containers/images
|
samalba_dockerclient
|
train
|
329d98a28f2b1fb7305582df2dee5a31e380757a
|
diff --git a/src/math/observable_vector3.js b/src/math/observable_vector3.js
index <HASH>..<HASH> 100644
--- a/src/math/observable_vector3.js
+++ b/src/math/observable_vector3.js
@@ -424,7 +424,7 @@
var y = this._y;
return this._set(
x * Math.cos(angle) - y * Math.sin(angle),
- x * Math.sin(angle) + y * Math.cos(angle).
+ x * Math.sin(angle) + y * Math.cos(angle),
this._z
);
},
diff --git a/tests/spec/observableVect2d-spec.js b/tests/spec/observableVect2d-spec.js
index <HASH>..<HASH> 100644
--- a/tests/spec/observableVect2d-spec.js
+++ b/tests/spec/observableVect2d-spec.js
@@ -160,11 +160,13 @@ describe("me.ObservableVector2d", function () {
expect(a.angle(b) ).toEqual(Math.PI / 2);
});
- it("perp function", function () {
+ it("perp and rotate function", function () {
a.set(x, y);
b.copy(a).perp();
-
- expect(b.angle(a)).toEqual(Math.PI / 2);
+ // perp rotate the vector by 90 degree clockwise on the z axis
+ c.copy(a).rotate(Math.PI/2);
+
+ expect(a.angle(b)).toEqual(a.angle(c));
});
});
\ No newline at end of file
diff --git a/tests/spec/observableVect3d-spec.js b/tests/spec/observableVect3d-spec.js
index <HASH>..<HASH> 100644
--- a/tests/spec/observableVect3d-spec.js
+++ b/tests/spec/observableVect3d-spec.js
@@ -181,4 +181,14 @@ describe("me.ObservableVector3d", function () {
b.set(4*x, -y, 0);
expect(a.angle(b) ).toEqual(Math.PI / 2);
});
+
+ it("perp and rotate function", function () {
+ a.set(x, y, z);
+ b.copy(a).perp();
+ // perp rotate the vector by 90 degree clockwise on the z axis
+ c.copy(a).rotate(Math.PI/2);
+
+ expect(a.angle(b)).toEqual(a.angle(c));
+ });
+
});
\ No newline at end of file
diff --git a/tests/spec/vect2d-spec.js b/tests/spec/vect2d-spec.js
index <HASH>..<HASH> 100644
--- a/tests/spec/vect2d-spec.js
+++ b/tests/spec/vect2d-spec.js
@@ -148,11 +148,13 @@ describe("me.Vector2d", function () {
expect(a.angle(b) ).toEqual(Math.PI / 2);
});
- it("perp function", function () {
+ it("perp and rotate function", function () {
a.set(x, y);
b.copy(a).perp();
-
- expect(b.angle(a)).toEqual(Math.PI / 2);
+ // perp rotate the vector by 90 degree clockwise on the z axis
+ c.copy(a).rotate(Math.PI/2);
+
+ expect(a.angle(b)).toEqual(a.angle(c));
});
});
diff --git a/tests/spec/vect3d-spec.js b/tests/spec/vect3d-spec.js
index <HASH>..<HASH> 100644
--- a/tests/spec/vect3d-spec.js
+++ b/tests/spec/vect3d-spec.js
@@ -173,14 +173,15 @@ describe("me.Vector3d", function () {
expect(a.angle(b) ).toEqual(Math.PI / 2);
});
- /*
- HOMEWORK: perp function for 3d vectors
- it("perp function", function () {
+
+ it("perp and rotate function", function () {
a.set(x, y, z);
b.copy(a).perp();
+ // perp rotate the vector by 90 degree clockwise on the z axis
+ c.copy(a).rotate(Math.PI/2);
- expect(a.angle(b).radToDeg()).toEqual(90); //?
+ expect(a.angle(b)).toEqual(a.angle(c));
});
- */
+
});
|
[#<I>] fixed the `perp` function in `me.ObservableVector3d` and improved all test cases
|
melonjs_melonJS
|
train
|
9420d962a58f3399d82ebe9b9eee517638157be0
|
diff --git a/code/plugins/koowa/default.php b/code/plugins/koowa/default.php
index <HASH>..<HASH> 100644
--- a/code/plugins/koowa/default.php
+++ b/code/plugins/koowa/default.php
@@ -10,11 +10,48 @@
/**
* Default Koowa plugin
+ *
+ * Koowa plugins can handle a number of events that are dynamically generated. The following
+ * is a list of available events. This list is not meant to be exclusive.
+ *
+ * onApplicationBefore[Action]
+ * onApplicationAfte[Action]
+ * where [Action] is Initialise, Route, Dispatch, Render, Login, Logout, Redirect or Close
+ *
+ * onControllerBefore[Action]
+ * onControllerAfter[Action]
+ * where [Action] is Browse, Read, Edit, Add, Delete or any custom controller action
+ *
+ * onDatabaseBefore[Action]
+ * onDatabaseAfter[Action]
+ * where [Action] is Select, Insert, Update or Delete
+ *
+ * You can create your own Koowa plugins very easily :
+ *
+ * <code>
+ * <?php
+ * class plgKoowaFoo extends plgKoowaDefault
+ * {
+ * public function onApplicationBeforeRoute(KCommandcontext $context)
+ * {
+ * //The caller is a reference to the object that is triggering this event
+ * $caller = $context['caller'];
+ *
+ * //The result is the actual result of the event, if this is an after event
+ * //the result will contain the result of the action.
+ * $result = $context['result'];
+ *
+ * //The context object can also contain a number of custom properties
+ * print_r($content);
+ * }
+ * }
+}
+ * </code>
*
* @author Johan Janssens <johan@koowa.org>
- * @category Nooku
- * @package Nooku_Plugins
- * @subpackage System
+ * @category Koowa
+ * @package Koowa_Plugins
+ * @subpackage Koowa
*/
class plgKoowaDefault extends KEventHandler
{
@@ -63,12 +100,26 @@ class plgKoowaDefault extends KEventHandler
//Register the plugin with the dispatcher
$dispatcher->register($this);
+
+ //Force the identifier to NULL for now
+ $config['identifier'] = null;
- parent::__construct();
+ parent::__construct($config);
}
-
- public function onDatabaseBeforeDispatch(ArrayObject $args)
- {
- die;
+
+ /**
+ * Loads the plugin language file
+ *
+ * @param string $extension The extension for which a language file should be loaded
+ * @param string $basePath The basepath to use
+ * @return boolean True, if the file has successfully loaded.
+ */
+ public function loadLanguage($extension = '', $basePath = JPATH_BASE)
+ {
+ if(empty($extension)) {
+ $extension = 'plg_'.$this->_type.'_'.$this->_name;
+ }
+
+ return KFactory::get('lib.joomla.language')->load( strtolower($extension), $basePath);
}
}
\ No newline at end of file
|
Added documentation and loadLanguage function to offer same functionality as a Joomla plugin.
|
timble_kodekit
|
train
|
6e521f09980d23c718c9765473198bbd0a6a97c8
|
diff --git a/lib/puppet-lint/plugins.rb b/lib/puppet-lint/plugins.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet-lint/plugins.rb
+++ b/lib/puppet-lint/plugins.rb
@@ -28,13 +28,13 @@ class PuppetLint
def self.gem_directories
if has_rubygems?
if Gem::Specification.respond_to? :latest_specs
- Gem::Specification.latest_specs.map do |spec|
- Pathname.new(spec.full_gem_path) + 'lib'
- end
+ specs = Gem::Specification.latest_specs
else
- Gem.searcher.init_gemspecs.map do |spec|
- Pathname.new(spec.full_gem_path) + 'lib'
- end
+ specs = Gem.searcher.init_gemspecs
+ end
+
+ specs.reject { |spec| spec.name == 'puppet-lint' }.map do |spec|
+ Pathname.new(spec.full_gem_path) + 'lib'
end
else
[]
|
Remove other versions of puppet-lint from the plugin search path
|
rodjek_puppet-lint
|
train
|
dac8ec39e6a57cddf73010b7fe29624089c73f8f
|
diff --git a/lib/api_resources/root.js b/lib/api_resources/root.js
index <HASH>..<HASH> 100644
--- a/lib/api_resources/root.js
+++ b/lib/api_resources/root.js
@@ -31,7 +31,7 @@ RootResource.prototype.list = function(env, next) {
var peerQuery = {
match: function(obj) {
- return obj.direction === 'acceptor';
+ return (obj.direction === 'acceptor' && obj.status === 'connected');
}
};
diff --git a/lib/http_server.js b/lib/http_server.js
index <HASH>..<HASH> 100644
--- a/lib/http_server.js
+++ b/lib/http_server.js
@@ -91,6 +91,8 @@ ZettaHttpServer.prototype.init = function(cb) {
var peerId = match[1];
var peer = new PeerSocket(ws, peerId);
+ self.zetta.log.emit('log', 'http_server', 'Websocket connection for peer ' + peerId + ' established');
+
var requestOpts = { method: 'GET', path: '/', agent: peer.agent };
var peerRequest = http.request(requestOpts, function(res) {
var buffer = [];
@@ -120,15 +122,18 @@ ZettaHttpServer.prototype.init = function(cb) {
};
self.peerRegistry.add(peerItem, function(err, newPeer) {
- self.agents[newPeer.id] = peer.agent;
- self.router[newPeer.id] = peerId;
+ self.zetta.log.emit('log', 'http_server', 'Peer connection established ' + peerId + ' maped to ' + newPeer.id);
peer.serverId = newPeer.id; // set proxy peer id
- self.eventBroker.peer(peer);
- self.peers.push(peer);
+ self.agents[newPeer.id] = peer.agent;
self.agents[peerId] = peer.agent;
+ self.router[newPeer.id] = peerId;
+ self.peers.push(peer);
+ self.eventBroker.peer(peer);
ws.on('close', function() {
+ self.zetta.log.emit('log', 'http_server', 'Peer connection closed for ' + peerId + ' maped to ' + newPeer.id);
+
self.peerRegistry.get(newPeer.id, function(err, peer) {
peer = JSON.parse(peer);
if (peer) {
@@ -139,6 +144,7 @@ ZettaHttpServer.prototype.init = function(cb) {
});
ws.on('error', function(err) {
+ self.zetta.log.emit('log', 'http_server', 'Peer connection failed for ' + peerId + ' maped to ' + newPeer.id);
self.peerRegistry.get(newPeer.id, function(err, peer) {
peer = JSON.parse(peer);
if (peer) {
|
Only displaying connected peers in root of api. Added logging for peers connecting on the server side
|
zettajs_zetta
|
train
|
666d271d98dec24b4840401c9fe58fb3ea6503d8
|
diff --git a/src/gulpglob.js b/src/gulpglob.js
index <HASH>..<HASH> 100644
--- a/src/gulpglob.js
+++ b/src/gulpglob.js
@@ -107,9 +107,6 @@ const GulpGlob = SingletonFactory(SimpleGulpGlob, [
},
});
-GulpGlob.getDefaults = SimpleGulpGlob.getDefaults;
-GulpGlob.setDefaults = SimpleGulpGlob.setDefaults;
-
SimpleGulpGlob.Singleton = GulpGlob;
export default GulpGlob;
diff --git a/src/simple-gulpglob.js b/src/simple-gulpglob.js
index <HASH>..<HASH> 100644
--- a/src/simple-gulpglob.js
+++ b/src/simple-gulpglob.js
@@ -3,15 +3,10 @@ import isValidGlob from 'is-valid-glob';
import path from 'path';
import PolyPath, {Path} from 'polypath';
-let defaultOptions = {
- cwd: process.cwd(),
- base: process.cwd(),
-};
-
export const getOptions = (options = {}) => {
let {cwd, base, ready, exclude} = options;
- cwd = cwd && new Path(cwd).path || defaultOptions.cwd;
+ cwd = cwd && new Path(cwd).path || process.cwd();
base = base && new Path(base).path || cwd;
exclude = !!exclude;
@@ -148,13 +143,4 @@ class SimpleGulpGlob {
}
}
-SimpleGulpGlob.getDefaults = () => {
- return Object.assign({}, defaultOptions);
-};
-
-SimpleGulpGlob.setDefaults = ({cwd, base}) => {
- cwd && (defaultOptions.cwd = new Path(cwd).path);
- base && (defaultOptions.base = new Path(base).path);
-};
-
export default SimpleGulpGlob;
diff --git a/test/helpers.js b/test/helpers.js
index <HASH>..<HASH> 100644
--- a/test/helpers.js
+++ b/test/helpers.js
@@ -1,7 +1,5 @@
import path from 'path';
import gulp from 'gulp';
-import cleanupWrapper from 'cleanup-wrapper';
-import SimpleGulpGlob from '../src/simple-gulpglob';
import {equiv} from 'keyfunc';
import os from 'os';
@@ -32,15 +30,6 @@ export function fileSrc (glb) {
return gulp.src(glb);
}
-export const tmpOptions = func => cleanupWrapper(func, {
- before () {
- this.defaultOptions = SimpleGulpGlob.getDefaults();
- },
- after () {
- SimpleGulpGlob.setDefaults(this.defaultOptions);
- },
-});
-
export const eq = equiv({
type: 'option',
sub: {
diff --git a/test/options.test.js b/test/options.test.js
index <HASH>..<HASH> 100644
--- a/test/options.test.js
+++ b/test/options.test.js
@@ -1,7 +1,6 @@
import GulpGlob from '../src/gulpglob';
import gulp from 'gulp';
import equalStreamContents from 'equal-stream-contents';
-import {tmpOptions} from './helpers';
describe(`Testing options`, function () {
const options = {
@@ -23,14 +22,6 @@ describe(`Testing options`, function () {
options));
});
- it(`Setting global options`, tmpOptions(function () {
- GulpGlob.setDefaults(options);
-
- const ggSrc = new GulpGlob(['src/**/*.js']);
- return equalStreamContents(ggSrc.src(), gulp.src('src/**/*.js',
- options));
- }));
-
it(`src() options have priority over ctor options`, function () {
const ggSrc = new GulpGlob(['src/**/*.js', options]);
@@ -40,32 +31,4 @@ describe(`Testing options`, function () {
}, () => equalStreamContents(ggSrc.src(options2),
gulp.src('src/**/*.js', options2)));
});
-
- it(`src() options have priority over global options`, tmpOptions(function () {
- GulpGlob.setDefaults(options);
-
- const ggSrc = new GulpGlob(['src/**/*.js']);
-
- return Promise.all([
- equalStreamContents(ggSrc.src(), gulp.src('src/**/*.js', options)),
- equalStreamContents(ggSrc.src(options2),
- gulp.src('src/**/*.js', options)).then(() => {
- throw new Error('options2 should have had priority over options');
- }, () =>
- equalStreamContents(ggSrc.src(options2),
- gulp.src('src/**/*.js', options2))),
- ]);
- }));
-
- it(`ctor options have priority over global options`, tmpOptions(function () {
- GulpGlob.setDefaults(options);
-
- const ggSrc = new GulpGlob(['src/**/*.js', options2]);
-
- return equalStreamContents(ggSrc.src(), gulp.src('src/**/*.js', options))
- .then(() => {
- throw new Error('options2 should have had priority over options');
- }, () => equalStreamContents(ggSrc.src(),
- gulp.src('src/**/*.js', options2)));
- }));
});
|
Retired global options
Just use ctor and methods options
|
jlenoble_gulpglob
|
train
|
27a8ea637e29e78181d5b0259935ffc77c4e1832
|
diff --git a/gtm.go b/gtm.go
index <HASH>..<HASH> 100644
--- a/gtm.go
+++ b/gtm.go
@@ -810,11 +810,56 @@ func (this *Op) matchesDirectFilter(options *Options) bool {
return options.DirectReadFilter == nil || options.DirectReadFilter(this)
}
+func normalizeDocSlice(a []interface{}) []interface{} {
+ var avs []interface{}
+ for _, av := range a {
+ var avc interface{}
+ switch achild := av.(type) {
+ case map[string]interface{}:
+ avc = normalizeDocMap(achild)
+ case primitive.M:
+ avc = normalizeDocMap(map[string]interface{}(achild))
+ case primitive.D:
+ avc = normalizeDocMap(map[string]interface{}(achild.Map()))
+ case []interface{}:
+ avc = normalizeDocSlice(achild)
+ case primitive.A:
+ avc = normalizeDocSlice([]interface{}(achild))
+ default:
+ avc = av
+ }
+ avs = append(avs, avc)
+ }
+ return avs
+}
+
+func normalizeDocMap(m map[string]interface{}) map[string]interface{} {
+ o := map[string]interface{}{}
+ for k, v := range m {
+ switch child := v.(type) {
+ case map[string]interface{}:
+ o[k] = normalizeDocMap(child)
+ case primitive.M:
+ o[k] = normalizeDocMap(map[string]interface{}(child))
+ case primitive.D:
+ o[k] = normalizeDocMap(map[string]interface{}(child.Map()))
+ case []interface{}:
+ o[k] = normalizeDocSlice(child)
+ case primitive.A:
+ o[k] = normalizeDocSlice([]interface{}(child))
+ default:
+ o[k] = v
+ }
+ }
+ return o
+}
+
func (this *Op) processData(data interface{}) {
if data != nil {
this.Doc = data
if m, ok := data.(map[string]interface{}); ok {
- this.Data = m
+ this.Data = normalizeDocMap(m)
+ this.Doc = this.Data
}
}
}
@@ -1160,7 +1205,6 @@ func ConsumeChangeStream(ctx *OpCtx, client *mongo.Client, ns string, o *Options
var stream *mongo.ChangeStream
opts := options.ChangeStream()
opts.SetBatchSize(int32(o.ChannelSize))
- opts.SetMaxAwaitTime(time.Duration(o.MaxWaitSecs) * time.Second)
opts.SetFullDocument(options.UpdateLookup)
opts.SetStartAtOperationTime(startAt)
opts.SetResumeAfter(resumeAfter)
|
deep convert bson specific types to generic map and slice
|
rwynn_gtm
|
train
|
48efd438f4c00d6a4d36c5fc922fc0943fd37baf
|
diff --git a/base/app/models/channel.rb b/base/app/models/channel.rb
index <HASH>..<HASH> 100644
--- a/base/app/models/channel.rb
+++ b/base/app/models/channel.rb
@@ -57,4 +57,9 @@ class Channel < ActiveRecord::Base
def reflexive?
author_id == owner_id
end
+
+ # Is the author represented in this {Channel}?
+ def represented_author?
+ author_id != user_author_id
+ end
end
diff --git a/base/app/models/group.rb b/base/app/models/group.rb
index <HASH>..<HASH> 100644
--- a/base/app/models/group.rb
+++ b/base/app/models/group.rb
@@ -37,7 +37,8 @@ class Group < ActiveRecord::Base
:relation_ids => _relation_ids
if represented_author?
- # TODO: create tie with future representation relation
+ user_author.sent_contacts.create! :receiver_id => actor_id,
+ :relation_ids => _relation_ids
end
end
diff --git a/base/lib/social_stream/models/object.rb b/base/lib/social_stream/models/object.rb
index <HASH>..<HASH> 100644
--- a/base/lib/social_stream/models/object.rb
+++ b/base/lib/social_stream/models/object.rb
@@ -29,11 +29,6 @@ module SocialStream
}
end
- # Was the author represented with this {SocialStream::Models::Object object} was created?
- def represented_author?
- author_id == user_author_id
- end
-
# All the activities with this object
def activities
Activity.
diff --git a/base/spec/controllers/groups_controller_spec.rb b/base/spec/controllers/groups_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/base/spec/controllers/groups_controller_spec.rb
+++ b/base/spec/controllers/groups_controller_spec.rb
@@ -87,6 +87,7 @@ describe GroupsController do
Group.count.should eq(count + 1)
assigns(:current_subject).should eq(group)
response.should redirect_to(:home)
+ @user.receivers.should include(group.actor)
end
context "with participants" do
@@ -171,6 +172,8 @@ describe GroupsController do
Group.count.should eq(count + 1)
assigns(:current_subject).should eq(group)
response.should redirect_to(:home)
+ @user.receivers.should include(group.actor)
+ @group.receivers.should include(group.actor)
end
end
end
|
Add group to user_author contacts. Fixes #<I>
|
ging_social_stream
|
train
|
02134321aa8a265d1ac3bb08fced4190ae3e16de
|
diff --git a/QuickBooks/Callbacks/SQL/Callbacks.php b/QuickBooks/Callbacks/SQL/Callbacks.php
index <HASH>..<HASH> 100644
--- a/QuickBooks/Callbacks/SQL/Callbacks.php
+++ b/QuickBooks/Callbacks/SQL/Callbacks.php
@@ -5710,8 +5710,8 @@ class QuickBooks_Callbacks_SQL_Callbacks
<QBXML>
<QBXMLMsgsRq onError="' . QUICKBOOKS_SERVER_SQL_ON_ERROR . '">
<ItemSalesTaxQueryRq requestID="' . $requestID . '" ' . QuickBooks_Callbacks_SQL_Callbacks::_buildIterator($extra) . '>
- ' . QuickBooks_Callbacks_SQL_Callbacks::_buildFilter($user, $action, $extra) . '
<ActiveStatus>All</ActiveStatus>
+ ' . QuickBooks_Callbacks_SQL_Callbacks::_buildFilter($user, $action, $extra) . '
' . QuickBooks_Callbacks_SQL_Callbacks::_requiredVersionForElement(2.0, $version, '<OwnerID>0</OwnerID>') . '
</ItemSalesTaxQueryRq>
</QBXMLMsgsRq>
diff --git a/docs/example_mysql_mirror.php b/docs/example_mysql_mirror.php
index <HASH>..<HASH> 100755
--- a/docs/example_mysql_mirror.php
+++ b/docs/example_mysql_mirror.php
@@ -153,10 +153,12 @@ $handler_options = array();
$driver_options = array();
$ops = array(
- //QUICKBOOKS_OBJECT_CUSTOMER,
- //QUICKBOOKS_OBJECT_VENDOR,
- //QUICKBOOKS_OBJECT_CUSTOMERTYPE,
- //QUICKBOOKS_OBJECT_VENDORTYPE,
+ QUICKBOOKS_OBJECT_SALESTAXITEM,
+ QUICKBOOKS_OBJECT_SALESTAXCODE,
+ QUICKBOOKS_OBJECT_CUSTOMER,
+ QUICKBOOKS_OBJECT_VENDOR,
+ QUICKBOOKS_OBJECT_CUSTOMERTYPE,
+ QUICKBOOKS_OBJECT_VENDORTYPE,
QUICKBOOKS_OBJECT_ESTIMATE,
);
|
SQL mirror fix for sales tax items.
|
consolibyte_quickbooks-php
|
train
|
efde1d516e9dfcf71a1d2559d1ab4d1718936ef6
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -10,13 +10,13 @@ with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
setup(
name = 'AsyncUrban',
packages = ['AsyncUrban'],
- version = '0.1.3',
+ version = '0.1.4',
description = 'An asynchronous wrapper around the UrbanDictionary API.',
long_description = long_description,
author = 'James E',
author_email = 'naught0@github.com',
url = 'https://github.com/naught0/AsyncUrban',
- download_url = 'https://github.com/Naught0/AsyncUrban/archive/0.1.3.tar.gz',
+ download_url = 'https://github.com/Naught0/AsyncUrban/archive/0.1.4.tar.gz',
keywords = ('dictionary', 'urban', 'urbandictionary', 'define'),
classifiers = [],
)
\ No newline at end of file
|
fix setup.py to show proper version
|
Naught0_asyncurban
|
train
|
bb9419705dbf9222d29ecbbd866ca850af619330
|
diff --git a/src/config/config.php b/src/config/config.php
index <HASH>..<HASH> 100644
--- a/src/config/config.php
+++ b/src/config/config.php
@@ -33,7 +33,7 @@ return array(
// Switch to the stylesheets directory and require the "less" and "sass" directories.
// These directories both have a filter applied to them so that the built
// collection will contain valid CSS.
- $directory = $collection->directory('../app/assets/stylesheets', function($collection)
+ $directory = $collection->directory('assets/stylesheets', function($collection)
{
$collection->requireDirectory('less')->apply('Less');
$collection->requireDirectory('sass')->apply('Sass');
@@ -46,7 +46,7 @@ return array(
// Switch to the javascripts directory and require the "coffeescript" directory. As
// with the above directories we'll apply the CoffeeScript filter to the directory
// so the built collection contains valid JS.
- $directory = $collection->directory('../app/assets/javascripts', function($collection)
+ $directory = $collection->directory('assets/javascripts', function($collection)
{
$collection->requireDirectory('coffeescripts')->apply('CoffeeScript');
$collection->requireDirectory();
@@ -89,7 +89,7 @@ return array(
|
*/
- 'build_path' => 'assets',
+ 'build_path' => 'builds',
/*
|--------------------------------------------------------------------------
|
Adjusting the default config and application collection.
|
Marwelln_basset
|
train
|
7ecc7fbfe6971a1029c03b5ca3014e5bb93740fd
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -157,7 +157,9 @@
'new Boolean(' + recur(x.valueOf()) + ')' :
x.toString();
case 'Date':
- return 'new Date(' + quote(x.toISOString()) + ')';
+ return 'new Date(' +
+ (isNaN(x.valueOf()) ? recur(NaN) : quote(x.toISOString())) +
+ ')';
case 'Null':
return 'null';
case 'Number':
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"jscs": "2.7.x",
"jshint": "2.8.x",
"mocha": "2.x.x",
- "ramda": "0.18.x",
+ "ramda": "~0.19.1",
"xyz": "0.5.x"
},
"files": [
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -547,6 +547,7 @@ describe('def', function() {
(function() { return arguments; }(1, 2, 3)),
new Boolean(false),
new Date(0),
+ new Date('XXX'),
new Number(-0),
new String(''),
/x/.exec('xyz'),
|
handle "Invalid Date" in show
|
sanctuary-js_sanctuary-def
|
train
|
528f35b6ecc8bdcbe5f04274c31cce4cca8fe2a3
|
diff --git a/pymola/tree.py b/pymola/tree.py
index <HASH>..<HASH> 100644
--- a/pymola/tree.py
+++ b/pymola/tree.py
@@ -94,12 +94,66 @@ class TreeListener(object):
def exitClass(self, tree):
pass
+ def enterImportAsClause(self, tree):
+ pass
+
+ def exitImportAsClause(self, tree):
+ pass
+
+ def enterImportFromClause(self, tree):
+ pass
+
+ def exitImportFromClause(self, tree):
+ pass
+
+ def enterElementModification(self, tree):
+ pass
+
+ def exitElementModification(self, tree):
+ pass
+
+ def enterClassModification(self, tree):
+ pass
+
+ def exitClassModification(self, tree):
+ pass
+
+ def enterExtendsClause(self, tree):
+ pass
+
+ def exitExtendsClause(self, tree):
+ pass
+
+ def enterIfExpression(self, tree):
+ pass
+
+ def exitIfExpression(self, tree):
+ pass
+
def enterExpression(self, tree):
pass
def exitExpression(self, tree):
pass
+ def enterIfEquation(self, tree):
+ pass
+
+ def exitIfEquation(self, tree):
+ pass
+
+ def enterForIndex(self, tree):
+ pass
+
+ def exitForIndex(self, tree):
+ pass
+
+ def enterForEquation(self, tree):
+ pass
+
+ def exitForEquation(self, tree):
+ pass
+
def enterEquation(self, tree):
pass
@@ -124,6 +178,18 @@ class TreeListener(object):
def exitComponentClause(self, tree):
pass
+ def enterArray(self, tree):
+ pass
+
+ def exitArray(self, tree):
+ pass
+
+ def enterSlice(self, tree):
+ pass
+
+ def exitSlice(self, tree):
+ pass
+
def enterPrimary(self, tree):
pass
|
Add missing methods to TreeListener
|
pymoca_pymoca
|
train
|
73cf0dcace8887a26f92cb5f48510ecb6914d8bb
|
diff --git a/structr-core/src/main/java/org/structr/common/fulltext/Indexable.java b/structr-core/src/main/java/org/structr/common/fulltext/Indexable.java
index <HASH>..<HASH> 100644
--- a/structr-core/src/main/java/org/structr/common/fulltext/Indexable.java
+++ b/structr-core/src/main/java/org/structr/common/fulltext/Indexable.java
@@ -40,9 +40,13 @@ public interface Indexable extends NodeInterface {
public static final Property<String> extractedContent = new StringProperty("extractedContent");
public static final Property<String[]> indexedWords = new ArrayProperty("indexedWords", String.class).indexed(NodeService.NodeIndex.keyword);
+ /* CHM 16.06.2016: do not expose these fields in public view as they contain lots of data..
+
public static final org.structr.common.View publicView = new org.structr.common.View(Indexable.class, PropertyView.Public,
+
contentType, extractedContent, indexedWords
);
+ */
public static final org.structr.common.View uiView = new org.structr.common.View(Indexable.class, PropertyView.Ui,
contentType, extractedContent, indexedWords
diff --git a/structr-core/src/main/java/org/structr/core/graph/Tx.java b/structr-core/src/main/java/org/structr/core/graph/Tx.java
index <HASH>..<HASH> 100644
--- a/structr-core/src/main/java/org/structr/core/graph/Tx.java
+++ b/structr-core/src/main/java/org/structr/core/graph/Tx.java
@@ -84,8 +84,8 @@ public class Tx implements AutoCloseable {
modificationQueue.doOuterCallbacks(securityContext);
- // notify listeners if desired
- if ( (securityContext == null) ? doNotifications : securityContext.isDoTransactionNotifications() ) {
+ // notify listeners if desired, and allow this setting to be overriden locally AND remotely
+ if ( (securityContext == null) ? doNotifications : doNotifications && securityContext.isDoTransactionNotifications() ) {
final Collection<ModificationEvent> modificationEvents = modificationQueue.getModificationEvents();
for (final StructrTransactionListener listener : TransactionCommand.getTransactionListeners()) {
|
Modified internal transaction class to allow notifications to be disabled locally (using
App#tx()) AND remotely (using SecurityContext#setDoNotifications()), removed contentType,
extractedContent, indexedWords from public view of interface Indexable.
|
structr_structr
|
train
|
94f050f9e29ed3f9a7b6718c535523209c4fdf20
|
diff --git a/src/DB/Codeigniter4Adapter.php b/src/DB/Codeigniter4Adapter.php
index <HASH>..<HASH> 100644
--- a/src/DB/Codeigniter4Adapter.php
+++ b/src/DB/Codeigniter4Adapter.php
@@ -66,4 +66,17 @@ class Codeigniter4Adapter extends DBAdapter
return '?';
}
-}
\ No newline at end of file
+
+ /**
+ * @param $query
+ * @return string
+ */
+ public function getQueryString($query)
+ {
+ if ($query instanceof \CodeIgniter\Database\BaseBuilder) {
+ return $query->getCompiledSelect();
+ }
+
+ return $query;
+ }
+}
|
add ci4 builder class support
|
n1crack_datatables
|
train
|
888846a8ce7e25c3d80e5f0de7412e93331aaec2
|
diff --git a/lib/que/worker.rb b/lib/que/worker.rb
index <HASH>..<HASH> 100644
--- a/lib/que/worker.rb
+++ b/lib/que/worker.rb
@@ -37,7 +37,7 @@ module Que
begin
count = job[:error_count] + 1
- interval = (klass.retry_interval if klass) || Job.retry_interval
+ interval = (klass.retry_interval if klass && klass.respond_to?(:retry_interval)) || Job.retry_interval
delay = interval.respond_to?(:call) ? interval.call(count) : interval
message = "#{error.message}\n#{error.backtrace.join("\n")}"
Que.execute :set_error, [count, delay, message] + job.values_at(:queue, :priority, :run_at, :job_id)
diff --git a/spec/unit/worker_spec.rb b/spec/unit/worker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/worker_spec.rb
+++ b/spec/unit/worker_spec.rb
@@ -289,5 +289,21 @@ describe Que::Worker do
job[:last_error].should =~ /uninitialized constant:? NonexistentClass/
job[:run_at].should be_within(3).of Time.now + 4
end
+
+ it "should throw an error properly if the corresponding job class doesn't descend from Que::Job" do
+ class J
+ def run(*args)
+ end
+ end
+
+ Que.enqueue :job_class => "J"
+
+ run_jobs Que.execute("SELECT * FROM que_jobs")
+
+ DB[:que_jobs].count.should be 1
+ job = DB[:que_jobs].first
+ job[:error_count].should be 1
+ job[:run_at].should be_within(3).of Time.now + 4
+ end
end
end
|
Reimplement fix for issue #<I> with the new worker system.
|
chanks_que
|
train
|
7744ab63c79b3a86bdeb1ce37aff1d644ace02ae
|
diff --git a/lib/s3/object.rb b/lib/s3/object.rb
index <HASH>..<HASH> 100644
--- a/lib/s3/object.rb
+++ b/lib/s3/object.rb
@@ -9,7 +9,7 @@ module S3
attr_reader :last_modified, :etag, :size, :bucket, :key, :acl, :storage_class, :metadata
attr_writer :content
- def_instance_delegators :bucket, :name, :service, :bucket_request, :vhost?, :host, :path_prefix
+ def_instance_delegators :bucket, :name, :service, :vhost?, :host, :path_prefix
def_instance_delegators :service, :protocol, :port, :secret_access_key
private_class_method :new
@@ -230,7 +230,7 @@ module S3
end
def object_request(method, options = {})
- bucket_request(method, options.merge(:path => key))
+ bucket.send(:bucket_request, method, options.merge(:path => key))
end
def last_modified=(last_modified)
|
Trying to get rid of private method warning
|
qoobaa_s3
|
train
|
ff63e4300b847807e5d6f44ed0829870d472ec88
|
diff --git a/providers/discord/discord.go b/providers/discord/discord.go
index <HASH>..<HASH> 100644
--- a/providers/discord/discord.go
+++ b/providers/discord/discord.go
@@ -126,14 +126,8 @@ func userFromReader(r io.Reader, user *goth.User) error {
user.Name = u.Name
user.Email = u.Email
- user.NickName = "No nickname is provided by the Discord API"
- user.Location = "No location is provided by the Discord API"
user.AvatarURL = "https://discordapp.com/api/users/" + u.ID + "/avatars/" + u.AvatarID + ".jpg"
user.UserID = u.ID
- // user.Discriminator = u.Discriminator
- // user.MFAEnabled = u.MFAEnabled
- // user.Verified = u.Verified
- user.Description = "No description is provided by the Discord API"
return nil
}
|
Removed commented out code.
Remove unneeded fields.
|
markbates_goth
|
train
|
72d42eea006645895ca2928eb59df7754c731e61
|
diff --git a/lib/knife-solo/node_config_command.rb b/lib/knife-solo/node_config_command.rb
index <HASH>..<HASH> 100644
--- a/lib/knife-solo/node_config_command.rb
+++ b/lib/knife-solo/node_config_command.rb
@@ -2,6 +2,7 @@ module KnifeSolo
module NodeConfigCommand
def self.load_deps
+ require 'fileutils'
require 'pathname'
end
@@ -51,6 +52,7 @@ module KnifeSolo
Chef::Log.debug "Node config '#{node_config}' already exists"
else
ui.msg "Generating node config '#{node_config}'..."
+ FileUtils.mkdir_p(node_config.dirname)
File.open(node_config, 'w') do |f|
attributes = config[:json_attributes] || config[:first_boot_attributes] || {}
run_list = { :run_list => config[:run_list] || [] }
diff --git a/test/node_config_command_test.rb b/test/node_config_command_test.rb
index <HASH>..<HASH> 100644
--- a/test/node_config_command_test.rb
+++ b/test/node_config_command_test.rb
@@ -118,6 +118,14 @@ class NodeConfigCommandTest < TestCase
end
end
+ def test_creates_the_nodes_directory_if_needed
+ outside_kitchen do
+ cmd = command(@host, "--node-name=mynode")
+ cmd.generate_node_config
+ assert cmd.node_config.exist?
+ end
+ end
+
def command(*args)
knife_command(DummyNodeConfigCommand, *args)
end
|
Create the directory for node_config if it does not exist
|
matschaffer_knife-solo
|
train
|
df66d9f693473c2ddb1230432a15c691300479b2
|
diff --git a/lib/formulaic/inputs/checkbox_input.rb b/lib/formulaic/inputs/checkbox_input.rb
index <HASH>..<HASH> 100644
--- a/lib/formulaic/inputs/checkbox_input.rb
+++ b/lib/formulaic/inputs/checkbox_input.rb
@@ -28,8 +28,17 @@ module Formulaic
"input[type='checkbox'][name='#{label.model_name}[#{label.attribute}][]']"
end
+ def checkbox_name_selector_for_association
+ "input[type='checkbox'][name='#{label.model_name}[#{label.attribute.to_s.singularize}_ids][]']"
+ end
+
def checkbox_labels_selector
- "#{checkbox_name_selector} ~ label,label:has(#{checkbox_name_selector})"
+ [
+ "#{checkbox_name_selector} ~ label",
+ "label:has(#{checkbox_name_selector})",
+ "#{checkbox_name_selector_for_association} ~ label",
+ "label:has(#{checkbox_name_selector_for_association})",
+ ].join(",")
end
end
end
diff --git a/spec/features/fill_in_user_form_spec.rb b/spec/features/fill_in_user_form_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/features/fill_in_user_form_spec.rb
+++ b/spec/features/fill_in_user_form_spec.rb
@@ -206,4 +206,13 @@ describe 'Fill in user form' do
expect(page.find('#event_ends_on_3i').value).to eq('31')
end
+ it 'knows to use _ids for association fields' do
+ visit 'user_form'
+
+ form = Formulaic::Form.new(:user, :new, friends: ['Caleb'])
+
+ form.fill
+
+ expect(page.find('#user_friend_ids_1')).to be_checked
+ end
end
diff --git a/spec/fixtures/user_form.html b/spec/fixtures/user_form.html
index <HASH>..<HASH> 100644
--- a/spec/fixtures/user_form.html
+++ b/spec/fixtures/user_form.html
@@ -43,6 +43,17 @@
</span>
<input name="user[dislikes][]" type="hidden" value="">
</div>
+ <div class="input check_boxes optional user_friends">
+ <label class="check_boxes optional">Friends</label>
+ <span class="checkbox">
+ <label for="user_friend_ids_1">
+ <input class="check_boxes optional" type="checkbox" value="1" name="user[friend_ids][]" id="user_friend_ids_1">
+ Caleb
+ </label>
+ </span>
+ <input type="hidden" name="user[friend_ids][]" value="">
+ </div>
+
<div class="input text required user_bio"><label class="text required"
for="user_bio"><abbr title="required">*</abbr> Your Biography</label><textarea class="text required" cols="40" id="user_bio" name="user[bio]" rows="20" style="overflow: hidden; word-wrap: break-word; resize: horizontal; height: 464px;"></textarea></div>
<div class="input date required user_date_of_birth">
|
Allow assocation checkboxes to be filled
For an input such as `f.association :friends, as: :check_boxes`, we can
now `fill_form(:user, friends: ['Caleb', 'Rufino'])` and check the
appropriate boxes.
|
thoughtbot_formulaic
|
train
|
60925de5c4564a7df5b16255e33db4fa410a7ff1
|
diff --git a/src/rinoh/float.py b/src/rinoh/float.py
index <HASH>..<HASH> 100644
--- a/src/rinoh/float.py
+++ b/src/rinoh/float.py
@@ -40,8 +40,8 @@ class ImageState(HorizontallyAlignedFlowableState):
class ImageBase(Flowable):
def __init__(self, filename_or_file, scale=1.0, width=None, height=None,
- dpi=None, rotate=0, id=None, style=None, parent=None,
- **kwargs):
+ dpi=None, rotate=0, limit_width=None,
+ id=None, style=None, parent=None, **kwargs):
super().__init__(id=id, style=style, parent=parent, **kwargs)
self.filename_or_file = filename_or_file
if (width, height) != (None, None):
@@ -56,6 +56,7 @@ class ImageBase(Flowable):
self.height = height
self.dpi = dpi
self.rotate = rotate
+ self.limit_width = limit_width
@property
def filename(self):
@@ -94,18 +95,22 @@ class ImageBase(Flowable):
scale_width = scale_height
else:
scale_height = scale_width
- if scale_width is None:
+ if scale_width is None: # no width or height given
if self.scale in (FIT, FILL):
w_scale = float(container.width) / image.width
h_scale = float(container.remaining_height) / image.height
min_or_max = min if self.scale == FIT else max
- scale = min_or_max(w_scale, h_scale)
+ scale_width = scale_height = min_or_max(w_scale, h_scale)
else:
- scale = self.scale
- scale_width = scale_height = scale
+ scale_width = scale_height = self.scale
dpi_x, dpi_y = image.dpi
dpi_scale_x = (dpi_x / self.dpi) if self.dpi and dpi_x else 1
dpi_scale_y = (dpi_y / self.dpi) if self.dpi and dpi_y else 1
+ if (scale_width == scale_height == 1.0 # limit width if necessary
+ and self.limit_width is not None
+ and image.width * dpi_scale_x > container.width):
+ limit_width = self.limit_width.to_points(container.width)
+ scale_width = scale_height = limit_width / image.width
w, h = container.canvas.place_image(image, left, top,
container.document,
scale_width * dpi_scale_x,
@@ -134,11 +139,12 @@ class InlineImage(ImageBase, InlineFlowable):
class _Image(HorizontallyAlignedFlowable, ImageBase):
def __init__(self, filename_or_file, scale=1.0, width=None, height=None,
- dpi=None, rotate=0, align=None,
+ dpi=None, rotate=0, limit_width=None, align=None,
id=None, style=None, parent=None):
super().__init__(filename_or_file=filename_or_file, scale=scale,
width=width, height=height, dpi=dpi, rotate=rotate,
- align=align, id=id, style=style, parent=parent)
+ limit_width=limit_width, align=align,
+ id=id, style=style, parent=parent)
diff --git a/src/rinoh/frontend/rst/nodes.py b/src/rinoh/frontend/rst/nodes.py
index <HASH>..<HASH> 100644
--- a/src/rinoh/frontend/rst/nodes.py
+++ b/src/rinoh/frontend/rst/nodes.py
@@ -551,7 +551,8 @@ class Image(DocutilsBodyNode, DocutilsInlineNode):
width_string = self.get('width')
align = self.get('align')
return rt.Image(self.image_path, scale=self.get('scale', 100) / 100,
- width=convert_quantity(width_string), align=align)
+ width=convert_quantity(width_string), align=align,
+ limit_width=100*PERCENT)
ALIGN_TO_BASELINE = {'bottom': 0,
'middle': 50*PERCENT,
|
Image: optionally limit the width of large images
Make use of this in the rST/Sphinx frontends to simulate Sphinx's LaTeX
builder's behavior.
|
brechtm_rinohtype
|
train
|
276a40c1fc12a03ddb5dc53f65f365cb9cd8e5e8
|
diff --git a/simple_blobstore_server/lib/simple_blobstore_server.rb b/simple_blobstore_server/lib/simple_blobstore_server.rb
index <HASH>..<HASH> 100644
--- a/simple_blobstore_server/lib/simple_blobstore_server.rb
+++ b/simple_blobstore_server/lib/simple_blobstore_server.rb
@@ -59,38 +59,49 @@ module Bosh
@auth.provided? && @auth.basic? && @auth.credentials && @users.include?(@auth.credentials)
end
- before do
- protected!
- end
+ def create_file(object_id)
+ object_id ||= generate_object_id
+ file_name = get_file_name(object_id)
- post "/resources" do
- if params[:content] && params[:content][:tempfile]
- # Process uploads coming directly to the simple blobstore
- object_id = generate_object_id
- file_name = get_file_name(object_id)
+ error(409) if File.exist?(file_name)
- tempfile = params[:content][:tempfile]
+ FileUtils.mkdir_p(File.dirname(file_name))
- FileUtils.mkdir_p(File.dirname(file_name))
- FileUtils.copy_file(tempfile.path, file_name)
+ yield file_name
- status(200)
- content_type(:text)
- object_id
+ status(200)
+ content_type(:text)
+ object_id
+ end
+
+ def create(params)
+ if params[:content] && params[:content][:tempfile]
+ # Process uploads coming directly to the simple blobstore
+ create_file(params[:id]) do |file_name|
+ tempfile = params[:content][:tempfile]
+ FileUtils.copy_file(tempfile.path, file_name)
+ end
elsif params["content.name"] && params["content.path"]
# Process uploads arriving via nginx
- object_id = generate_object_id
- file_name = get_file_name(object_id)
-
- FileUtils.mkdir_p(File.dirname(file_name))
- FileUtils.mv(params["content.path"], file_name)
-
- status(200)
- content_type(:text)
- object_id
+ create_file(params[:id]) do |file_name|
+ FileUtils.mv(params["content.path"], file_name)
+ end
else
error(400)
end
+
+ end
+
+ before do
+ protected!
+ end
+
+ post "/resources/:id" do
+ create(params)
+ end
+
+ post "/resources" do
+ create(params)
end
get "/resources/:id" do
diff --git a/simple_blobstore_server/spec/functional/simple_blogstore_server_spec.rb b/simple_blobstore_server/spec/functional/simple_blogstore_server_spec.rb
index <HASH>..<HASH> 100644
--- a/simple_blobstore_server/spec/functional/simple_blogstore_server_spec.rb
+++ b/simple_blobstore_server/spec/functional/simple_blogstore_server_spec.rb
@@ -1,4 +1,4 @@
-require File.dirname(__FILE__) + '/../spec_helper'
+require 'spec_helper'
require "base64"
@@ -44,26 +44,49 @@ describe Bosh::Blobstore::SimpleBlobstoreServer do
describe "Creating resources" do
+ before(:each) do
+ @resource_file = Tempfile.new("resource")
+ @resource_file.write("test contents")
+ @resource_file.close
+ end
+
+ after(:each) do
+ @resource_file.delete
+ end
+
it "should create a token for a new resource" do
+ post "/resources", {"content" => Rack::Test::UploadedFile.new(@resource_file.path, "plain/text") },
+ {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 200
+ object_id = last_response.body
+
+ get "/resources/#{object_id}", {}, {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 200
+ last_response.body.should == "test contents"
+ end
- resource_file = Tempfile.new("resource")
- begin
- resource_file.write("test contents")
- resource_file.close
- post "/resources", {"content" => Rack::Test::UploadedFile.new(resource_file.path, "plain/text") },
- {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
- last_response.status.should == 200
- object_id = last_response.body
+ it 'should accept object id suggestion' do
+ post "/resources/foobar", {"content" => Rack::Test::UploadedFile.new(@resource_file.path, "plain/text") },
+ {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 200
+ object_id = last_response.body
- get "/resources/#{object_id}", {}, {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
- last_response.status.should == 200
- last_response.body.should == "test contents"
- ensure
- resource_file.delete
- end
+ object_id.should == "foobar"
+ get "/resources/#{object_id}", {}, {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 200
+ last_response.body.should == "test contents"
end
+ it 'should return a 409 error if the suggested id is taken' do
+ post "/resources/foobar", {"content" => Rack::Test::UploadedFile.new(@resource_file.path, "plain/text") },
+ {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 200
+
+ post "/resources/foobar", {"content" => Rack::Test::UploadedFile.new(@resource_file.path, "plain/text") },
+ {"HTTP_AUTHORIZATION" => encode_credentials("john", "doe")}
+ last_response.status.should == 409
+ end
end
describe "Fetching resources" do
|
support suggesting object id to blobstore server
|
cloudfoundry_bosh
|
train
|
552f7c20095cf25c91796243676c6fd5b780a291
|
diff --git a/model_utils/fields.py b/model_utils/fields.py
index <HASH>..<HASH> 100644
--- a/model_utils/fields.py
+++ b/model_utils/fields.py
@@ -195,7 +195,7 @@ class SplitField(models.TextField):
value = self._get_val_from_obj(obj)
return value.content
- def get_db_prep_value(self, value):
+ def get_prep_value(self, value):
try:
return value.content
except AttributeError:
|
Fixed #2 - Updated SplitField for <I>-style prep_value method.
|
jazzband_django-model-utils
|
train
|
58b3f3ac682c842c0963a3859c59ba50c32d840c
|
diff --git a/src/LiveControl/EloquentDataTable/DataTable.php b/src/LiveControl/EloquentDataTable/DataTable.php
index <HASH>..<HASH> 100644
--- a/src/LiveControl/EloquentDataTable/DataTable.php
+++ b/src/LiveControl/EloquentDataTable/DataTable.php
@@ -162,6 +162,12 @@ class DataTable
$names[] = $column->getName();
continue;
}
+
+ if(is_string($column) && strstr($column, '.'))
+ {
+ $column = explode('.', $column);
+ }
+
$names[] = (is_array($column) ? $this->arrayToCamelcase($column) : $column);
}
return $names;
|
Added fix for querying over multiple tables where columns are ambigious.
|
LiveControl_EloquentDataTable
|
train
|
bc261b8e5979bcaf512f798d39f5432e5833f9b8
|
diff --git a/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/ParallelScanTask.java b/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/ParallelScanTask.java
index <HASH>..<HASH> 100644
--- a/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/ParallelScanTask.java
+++ b/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/ParallelScanTask.java
@@ -163,6 +163,7 @@ public class ParallelScanTask {
synchronized(segmentScanStates) {
segmentScanStates.set(currentSegment, SegmentScanState.Failed);
segmentScanStates.notifyAll();
+ executorService.shutdown();
}
throw e;
}
|
Fix issue #<I> - Exception in Parallel Scan causes application to hang
|
aws_aws-sdk-java
|
train
|
b61c6f646fd89e4b13ccca21503a651e0bb8b692
|
diff --git a/survival/column.py b/survival/column.py
index <HASH>..<HASH> 100644
--- a/survival/column.py
+++ b/survival/column.py
@@ -126,8 +126,8 @@ def encode_categorical(table, **kwargs):
if series is None:
continue
- # join tables on index
- new_table = new_table.join(series)
+ # concat columns of tables
+ new_table = pandas.concat((new_table, series), axis=1, copy=False)
return new_table
diff --git a/tests/test_column.py b/tests/test_column.py
index <HASH>..<HASH> 100644
--- a/tests/test_column.py
+++ b/tests/test_column.py
@@ -148,6 +148,36 @@ class TestEncodeCategorical(TestCase):
self.assertTupleEqual(actual_df.shape, expected_df.shape)
tm.assert_frame_equal(actual_df, expected_df, check_exact=True)
+ def test_duplicate_index(self):
+ a = numpy.concatenate((
+ numpy.repeat(["large"], 10),
+ numpy.repeat(["small"], 6),
+ numpy.repeat(["tiny"], 13),
+ numpy.repeat(["medium"], 3)))
+ rnd = numpy.random.RandomState(0)
+ c = rnd.randn(len(a))
+
+ index = numpy.ceil(numpy.arange(0, len(a) // 2, 0.5))
+ df = pandas.DataFrame.from_items([("a_category", pandas.Series(a, index=index)),
+ ("a_number", pandas.Series(c, index=index, copy=True))])
+
+ actual_df = column.encode_categorical(df)
+
+ expected_df = pandas.DataFrame(numpy.zeros((32, 3), dtype=numpy.float_),
+ index=index,
+ columns=["a_category=medium", "a_category=small", "a_category=tiny"])
+ # tiny
+ expected_df.iloc[16:29, 2] = 1
+ # small
+ expected_df.iloc[10:16, 1] = 1
+ # medium
+ expected_df.iloc[-3:, 0] = 1
+
+ expected_df["a_number"] = c
+
+ self.assertTupleEqual(actual_df.shape, expected_df.shape)
+ tm.assert_frame_equal(actual_df, expected_df, check_exact=True)
+
def test_case_numeric(self):
a = numpy.array([0, 1, 1, 0, 1, 0, 0, 1, 0, 1], dtype=object)
b = numpy.array([1, 2, 1, 3, 2, 1, 3, 2, 3, 1], dtype=object)
|
BUG: encode_categorical creates additional rows if index contains duplicates
DataFrame.join performs a database-style join, which means it creates one row for each
combination. For instance, if there is one index that appears twice, the resulting DataFrame
will contain 4 rows with this key.
|
sebp_scikit-survival
|
train
|
4a2655eaf11997539d27567df3e0d0f105f77508
|
diff --git a/lib/endpoints/class-wp-rest-posts-controller.php b/lib/endpoints/class-wp-rest-posts-controller.php
index <HASH>..<HASH> 100755
--- a/lib/endpoints/class-wp-rest-posts-controller.php
+++ b/lib/endpoints/class-wp-rest-posts-controller.php
@@ -70,6 +70,8 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
public function get_items( $request ) {
$args = array();
$args['author'] = $request['author'];
+ $args['order'] = $request['order'];
+ $args['orderby'] = $request['orderby'];
$args['paged'] = $request['page'];
$args['posts_per_page'] = $request['per_page'];
$args['post_parent'] = $request['parent'];
@@ -1575,7 +1577,7 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
$params['order'] = array(
'description' => __( 'Order sort attribute ascending or descending.' ),
'type' => 'string',
- 'default' => 'asc',
+ 'default' => 'desc',
'enum' => array( 'asc', 'desc' ),
);
$params['orderby'] = array(
|
Ensure `GET /wp/v2/posts` respects `order` and `orderby` params
Also changes default to `orderby=>desc`, consistent with WP_Query
|
WP-API_WP-API
|
train
|
30b0c943a07059cdf8bed7eb4f2426100ef5d108
|
diff --git a/lib/cassandra_migrations/migration/table_operations.rb b/lib/cassandra_migrations/migration/table_operations.rb
index <HASH>..<HASH> 100644
--- a/lib/cassandra_migrations/migration/table_operations.rb
+++ b/lib/cassandra_migrations/migration/table_operations.rb
@@ -11,6 +11,12 @@ module CassandraMigrations
# - renaming tables
module TableOperations
+ # Creates a new table in the keyspace
+ #
+ # options:
+ # - :primary_keys: single value or array (for compound primary keys). If
+ # not defined, some column must be chosen as primary key in the table definition.
+
def create_table(table_name, options = {})
create_table_helper = CreateTableHelper.new
create_table_helper.define_primary_keys(options[:primary_keys]) if options[:primary_keys]
@@ -27,7 +33,14 @@ module CassandraMigrations
execute create_cql
end
+
+ def drop_table(table_name)
+ announce_operation "drop_table(#{table_name})"
+ drop_cql = "DROP TABLE #{table_name}"
+ announce_suboperation drop_cql
+ execute drop_cql
+ end
end
end
end
|
Added operations 'drop_table' to migrations.
|
hsgubert_cassandra_migrations
|
train
|
5c5d065e2eb3b19f1f45225d5950af6ddbc6892f
|
diff --git a/lib/rom/constants.rb b/lib/rom/constants.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/constants.rb
+++ b/lib/rom/constants.rb
@@ -22,6 +22,12 @@ module ROM
UnsupportedRelationError = Class.new(StandardError)
MissingAdapterIdentifierError = Class.new(StandardError)
+ MissingSchemaClassError = Class.new(StandardError) do
+ def initialize(klass)
+ super("#{klass.inspect} relation is missing schema_class")
+ end
+ end
+
DuplicateConfigurationError = Class.new(StandardError)
DuplicateContainerError = Class.new(StandardError)
diff --git a/lib/rom/relation/class_interface.rb b/lib/rom/relation/class_interface.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/relation/class_interface.rb
+++ b/lib/rom/relation/class_interface.rb
@@ -169,6 +169,11 @@ module ROM
name = Name[register_as, self.dataset]
inferrer = infer ? schema_inferrer : nil
+
+ unless schema_class
+ raise MissingSchemaClassError.new(self)
+ end
+
dsl = schema_dsl.new(name, schema_class: schema_class, inferrer: inferrer, &block)
@schema = dsl.call
diff --git a/spec/unit/rom/relation/schema_spec.rb b/spec/unit/rom/relation/schema_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/rom/relation/schema_spec.rb
+++ b/spec/unit/rom/relation/schema_spec.rb
@@ -85,6 +85,15 @@ RSpec.describe ROM::Relation, '.schema' do
expect(Test::Users.register_as).to be(:test_users)
end
+ it 'raises error when schema_class is missing' do
+ class Test::Users < ROM::Relation[:memory]
+ schema_class nil
+ end
+
+ expect { Test::Users.schema(:test) { } }.
+ to raise_error(ROM::MissingSchemaClassError, "Test::Users relation is missing schema_class")
+ end
+
describe '#schema' do
it 'returns defined schema' do
class Test::Users < ROM::Relation[:memory]
|
Raise a meaningful error when schema_class is not set
Closes #<I>
|
rom-rb_rom
|
train
|
af0e4bef5b14975685752869c5b8c20698229c6f
|
diff --git a/rejected/consumer.py b/rejected/consumer.py
index <HASH>..<HASH> 100644
--- a/rejected/consumer.py
+++ b/rejected/consumer.py
@@ -944,10 +944,8 @@ class Consumer(object):
:rtype: pika.BasicProperties
"""
- if not properties_in:
- return
properties = pika.BasicProperties()
- for key in properties_in:
+ for key in properties_in or {}:
if properties_in.get(key) is not None:
setattr(properties, key, properties_in.get(key))
return properties
|
Always return properties, even if None
|
gmr_rejected
|
train
|
f8a841bfb851474aa85401b85e45be52cc068843
|
diff --git a/components/tabs/dumb-tabs.js b/components/tabs/dumb-tabs.js
index <HASH>..<HASH> 100644
--- a/components/tabs/dumb-tabs.js
+++ b/components/tabs/dumb-tabs.js
@@ -60,7 +60,7 @@ export default class Tabs extends PureComponent {
innerClassName={titleClasses}
className={titleClasses}
disabled={disabled}
- onClick={this.handleSelect(key)}
+ onPlainLeftClick={this.handleSelect(key)}
>{() => this.getTabTitleCaption(title, isSelected)}</Link>
);
};
|
[RING-UI-CR-<I>] Tabs. Change onClick to onPlainLeftClick to prevent change the url inside the current opened window.
|
JetBrains_ring-ui
|
train
|
645ae4e411b35c5b20ae1bfd2debddbccfc9e9bd
|
diff --git a/src/Repository.php b/src/Repository.php
index <HASH>..<HASH> 100755
--- a/src/Repository.php
+++ b/src/Repository.php
@@ -50,23 +50,23 @@ class Repository {
}
/**
- * Delete an entity from the database
+ * Delete an entity or an entity collection from the database
*
- * @param \Analogue\ORM\Entity $entity
- * @return void
+ * @param Mappable|Collection $entity
+ * @return Mappable|Collection
*/
- public function delete(Mappable $entity)
+ public function delete($entity)
{
return $this->mapper->delete($entity);
}
/**
- * Persist an entity in the database.
+ * Persist an entity or an entity collection in the database.
*
- * @param \Analogue\ORM\Entity $entity
- * @return \Analogue\ORM\Entity
+ * @param Mappable|Collection $entity
+ * @return Mappable|Collection
*/
- public function store(Mappable $entity)
+ public function store($entity)
{
return $this->mapper->store($entity);
}
diff --git a/src/System/Mapper.php b/src/System/Mapper.php
index <HASH>..<HASH> 100755
--- a/src/System/Mapper.php
+++ b/src/System/Mapper.php
@@ -5,10 +5,12 @@ use Analogue\ORM\EntityMap;
use Analogue\ORM\Commands\Store;
use Analogue\ORM\Commands\Delete;
use Illuminate\Events\Dispatcher;
+use Illuminate\Support\Collection;
use Analogue\ORM\Commands\Command;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Analogue\ORM\Exceptions\MappingException;
+
/*
* The mapper provide all the interactions with the database layer
* and holds the states for the loaded entity. One instance is
@@ -87,12 +89,27 @@ class Mapper {
}
/**
- * Persist an entity into the database
+ * Persist an entity or an entity collection into the database
+ *
+ * @param Mappable|Collection $entity
+ * @return Mappable|Collection
+ */
+ public function store($entity)
+ {
+ if($entity instanceof Collection)
+ {
+ return $this->storeCollection($entity);
+ }
+ else return $this->storeEntity($entity);
+ }
+
+ /**
+ * Store a single entity into the database
*
- * @param $entity [description]
+ * @param Mappable $entity
* @return Entity
*/
- public function store(Mappable $entity)
+ protected function storeEntity(Mappable $entity)
{
$store = new Store($entity, $this, $this->newQueryBuilder() );
@@ -100,19 +117,74 @@ class Mapper {
}
/**
- * Delete an entity from the database
+ * Store an entity collection inside a single DB Transaction
+ *
+ * @param Collection $entities [description]
+ * @return Collection
+ */
+ protected function storeCollection(Collection $entities)
+ {
+ $thid->connection->beginTransaction();
+
+ foreach($entities as $entity)
+ {
+ $this->storeEntity($entity);
+ }
+
+ $thid->connection->commit();
+
+ return $entities;
+ }
+
+ /**
+ * Delete an entity or an entity collection from the database
*
- * @param object $entity
- * @return null
+ * @param Mappable|Collection
+ * @return Mappable|Collection
*/
public function delete(Mappable $entity)
{
+ if($entity instanceof Collection)
+ {
+ return $this->deleteCollection($entity);
+ }
+ else return $this->deleteEntity($entity);
+ }
+
+ /**
+ * Delete a single entity from the database.
+ *
+ * @param Mappable $entity
+ * @return Mappable
+ */
+ protected function deleteEntity(Mappable $entity)
+ {
$delete = new Delete($entity, $this, $this->newQueryBuilder() );
return $delete->execute();
}
/**
+ * Delete an Entity Collection inside a single db transaction
+ *
+ * @param Collection $entities
+ * @return Collection
+ */
+ protected function deleteCollection(Collection $entities)
+ {
+ $thid->connection->beginTransaction();
+
+ foreach($entities as $entity)
+ {
+ $this->deleteEntity($entity);
+ }
+
+ $thid->connection->commit();
+
+ return $entities;
+ }
+
+ /**
* Return the entity map for this mapper
*
* @return EntityMap
|
Support for Store/Delete on Collections
|
analogueorm_analogue
|
train
|
517a72808886e010624316b441c0b1439d9233ee
|
diff --git a/src/Util/Base64Serialize.php b/src/Util/Base64Serialize.php
index <HASH>..<HASH> 100644
--- a/src/Util/Base64Serialize.php
+++ b/src/Util/Base64Serialize.php
@@ -53,13 +53,12 @@ class Base64Serialize
}
/**
- * @param string $object
+ * @param string $objectData
* @param mixed $options
* @return mixed
*/
- public static function fromString($object, $options)
+ public static function fromString($objectData, $options)
{
- return Serialize::fromString(base64_decode($object), $options);
+ return Serialize::fromString(base64_decode($objectData), $options);
}
-
-}
\ No newline at end of file
+}
diff --git a/src/Util/Serialize.php b/src/Util/Serialize.php
index <HASH>..<HASH> 100644
--- a/src/Util/Serialize.php
+++ b/src/Util/Serialize.php
@@ -53,12 +53,12 @@ class Serialize
}
/**
- * @param string $object
+ * @param string $objectData
* @param mixed $options
* @return mixed
*/
- public static function fromString($object, $options)
+ public static function fromString($objectData, $options)
{
- return unserialize($object, $options);
+ return unserialize($objectData, $options);
}
}
|
Rename vars to be more descriptive
|
Nosto_nosto-php-sdk
|
train
|
b67a6d80a19b6976f6450bffafc12a0a590b2568
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -36,7 +36,7 @@ var namehash = ENS.prototype.namehash;
* var registrar = new Registrar(web3)
*
* // On Ropsten with the public ENS registry
- * registrar.initDefault();
+ * registrar.init();
* console.log(registrar.ens.registry.address); // '0x112234455c3a32fd11230c42e7bccd4a84e02010'
* console.log(registrar.rootNode); // '0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae'
*
@@ -84,30 +84,20 @@ function Registrar(web3){
this.web3 = web3;
}
-Registrar.prototype.init = function(ens, tld, min_length){
- // get registrar address from ens
- this.min_length = min_length;
- this.tld = tld;
- this.ens = ens;
- this.address = ens.owner(tld);
- this.contract = this.web3.eth.contract(interfaces.registrarInterface).at(this.address);
- // this isn't used yet, but I expect it will be handy
- this.rootNode = namehash(tld);
-}
-
var publicRegistryAddress = "0x112234455c3a32fd11230c42e7bccd4a84e02010";
-Registrar.prototype.initDefault = function(){
+Registrar.prototype.init = function(ens, tld, min_length){
// get registrar address from ens
- this.tld = 'eth';
- this.ens = this.web3.eth.contract(interfaces.registryInterface).at(publicRegistryAddress);
- this.address = this.ens.owner('eth');
+ this.ens = ens || new ENS(this.web3);
+ console.log(this.ens);
+ this.tld = tld || 'eth';
+ this.min_length = min_length || 7;
+ this.address = this.ens.owner(this.tld);
this.contract = this.web3.eth.contract(interfaces.registrarInterface).at(this.address);
// this isn't used yet, but I expect it will be handy
- this.rootNode = namehash('eth');
+ this.rootNode = namehash(this.tld);
}
-
Registrar.TooShort = Error("Name is too short");
function sha3(input) {
|
Simplify to a single constructor
variables will default to the ropsten deployment.
|
maurelian_eth-registrar-ens
|
train
|
aeb84e6fe9ae8b6045a509081e54340fa5ff1f70
|
diff --git a/Entities.js b/Entities.js
index <HASH>..<HASH> 100644
--- a/Entities.js
+++ b/Entities.js
@@ -212,7 +212,7 @@ class EntitiesFactory
{
return reservedKeys.indexOf(name) >= 0;
}
-
+ //Just creates the object, does not instanciate
create(name)
{
if (this.isReserved(name))
@@ -228,6 +228,18 @@ class EntitiesFactory
return result;
}
+ instanciate(name, params)
+ {
+ let _p = [];
+ let o = this.create(name);
+ //converts params object to a list of it's values
+ for (let p in params) {
+ _p.push(params[p])
+ }
+ //Will attempt to instanciate the object via rest parameters
+ return new o(..._p);
+ }
+
extend(newClasses)
{
for (let prop in newClasses) {
diff --git a/main.js b/main.js
index <HASH>..<HASH> 100644
--- a/main.js
+++ b/main.js
@@ -8,6 +8,18 @@ let fs = require('fs')
, Log = require('log')
, log = new Log('debug', fs.createWriteStream('t-motion-detector.' + (new Date().getTime()) + '.log'));
+//This function should stay internal to this module!
+function InternalAddEnvironment(env = new ent.Environment()){
+ if (env instanceof ent.Environment)
+ {
+ environment = env;
+ return true;
+ } else {
+ log.warning("'environment' object is not of type Environment");
+ }
+ return false;
+}
+
function AddNotifier(notifier, template){
if (notifier instanceof ent.BaseNotifier)
{
@@ -92,7 +104,8 @@ function Start(params, silent = false){
//Will set a default Environment if does not exist;
if(!environment){
- environment = new ent.Environment();
+ InternalAddEnvironment();
+ //environment = new ent.Environment();
}
if (!silent)
@@ -118,6 +131,7 @@ function StartWithConfig(configParams){
//Should now instanciate the objects if they exist in the default profile
config = configParams;
let profileObj = config.profile();
+
for(let p in profileObj)
{
if (profileObj.hasOwnProperty(p)) {
@@ -125,10 +139,13 @@ function StartWithConfig(configParams){
let f = new ent.EntitiesFactory();
if (!f.isReserved(p))
{
- let o = new (f.create(p))();
- if (!AddNotifier(o)){
- if(!AddDetector(o)){
- console.warn(`Object/class '${p}'' could not be added. Proceeding.`)
+ let o = f.instanciate(p, profileObj[p]);
+ //The way this is written, forces the environment to be created first
+ if(!InternalAddEnvironment(o)){
+ if (!AddNotifier(o)){
+ if(!AddDetector(o)){
+ console.warn(`Object/class '${p}'' could not be added. Proceeding.`)
+ }
}
}
}
diff --git a/test/internal-config-specs.js b/test/internal-config-specs.js
index <HASH>..<HASH> 100644
--- a/test/internal-config-specs.js
+++ b/test/internal-config-specs.js
@@ -189,16 +189,19 @@ describe("When a new t-motion-detector instance is started from main, ", functio
done();
});
- it('When starting with alternate config, the Notification Objects contained in the config file are automatically instanced as Notificators of main.', function (done) {
+ it('When starting with alternate config, the Notification Objects contained in the config file are automatically instanced as Notificators of main', function (done) {
+ //Main needs to be reset explicitely because it keeps objects from previous test
+ main.Reset();
let alternativeConfig = new main.Config("./test/config_test2.js");
main.StartWithConfig(alternativeConfig);
-
main.GetNotifiers().length.should.equal(1);
done();
});
- it('When starting with alternate config, the Environment Objects contained in the config file are automatically instanced as Environments of main.', function (done) {
+ it('When starting with alternate config, the Environment Objects contained in the config file are automatically instanced as Environments of main', function (done) {
+ //Main needs to be reset explicitely because it keeps objects from previous test
+ main.Reset();
let alternativeConfig = new main.Config("./test/config_test2.js");
main.StartWithConfig(alternativeConfig);
@@ -207,7 +210,7 @@ describe("When a new t-motion-detector instance is started from main, ", functio
done();
});
- it('When starting with alternate config, the MotionDetector Objects contained in the config file are automatically instanced as MotionDetectors of main.', function (done) {
+ it('When starting with alternate config, the MotionDetector Objects contained in the config file are automatically instanced as MotionDetectors of main', function (done) {
let alternativeConfig = new main.Config("./test/config_test2.js");
main.StartWithConfig(alternativeConfig);
@@ -290,6 +293,14 @@ describe("When using the EntitiesFactory function, ", function() {
let n = new slackNotifierObj("name", "some key");
(n instanceof ent.BaseNotifier).should.equal(true);
});
+ it('should be able to accept extensions such as SlackNotifier, with parameters directly from the config file', function () {
+ //Prepare
+ let slackNotifierFactory = new ent.EntitiesFactory();
+ n = slackNotifierFactory.instanciate("SlackNotifier", { name: "A", key: "K"});
+ (n instanceof ent.BaseNotifier).should.equal(true);
+ n.name.should.equal("A");
+ n.key.should.equal("K")
+ });
it('should throw an exception if object is not recognized', function () {
//Prepare
try{
|
first stable version for dependency injection, WIP on remaining tests
|
tcardoso2_vermon
|
train
|
bc470d9da2a2bac1e004389413feff7ed9d2f705
|
diff --git a/leveldb/db_compaction.go b/leveldb/db_compaction.go
index <HASH>..<HASH> 100644
--- a/leveldb/db_compaction.go
+++ b/leveldb/db_compaction.go
@@ -131,7 +131,13 @@ haserr:
}
}
-func (d *DB) compactionTransact(name string, exec, rollback func() error) {
+type compactionTransactCounter int
+
+func (cnt *compactionTransactCounter) incr() {
+ *cnt++
+}
+
+func (d *DB) compactionTransact(name string, exec func(cnt *compactionTransactCounter) error, rollback func() error) {
s := d.s
defer func() {
if x := recover(); x != nil {
@@ -143,25 +149,59 @@ func (d *DB) compactionTransact(name string, exec, rollback func() error) {
panic(x)
}
}()
+ const (
+ backoffMin = 1 * time.Second
+ backoffMax = 8 * time.Second
+ backoffMul = 2 * time.Second
+ )
+ backoff := backoffMin
+ backoffT := time.NewTimer(backoff)
+ lastCnt := compactionTransactCounter(0)
for n := 0; ; n++ {
+ // Check wether the DB is closed.
if d.isClosed() {
s.logf("%s exiting", name)
d.compactionExitTransact()
} else if n > 0 {
s.logf("%s retrying N·%d", name, n)
}
- err := exec()
+
+ // Execute.
+ cnt := compactionTransactCounter(0)
+ err := exec(&cnt)
+
+ // Set compaction error status.
select {
+ case d.compErrSetC <- err:
case _, _ = <-d.closeC:
s.logf("%s exiting", name)
d.compactionExitTransact()
- case d.compErrSetC <- err:
}
if err == nil {
return
}
- s.logf("%s error %q", name, err)
- time.Sleep(time.Second)
+ s.logf("%s error I·%d %q", name, cnt, err)
+
+ // Reset backoff duration if counter is advancing.
+ if cnt > lastCnt {
+ backoff = backoffMin
+ lastCnt = cnt
+ }
+
+ // Backoff.
+ backoffT.Reset(backoff)
+ if backoff < backoffMax {
+ backoff *= backoffMul
+ if backoff > backoffMax {
+ backoff = backoffMax
+ }
+ }
+ select {
+ case <-backoffT.C:
+ case _, _ = <-d.closeC:
+ s.logf("%s exiting", name)
+ d.compactionExitTransact()
+ }
}
}
@@ -197,7 +237,7 @@ func (d *DB) memCompaction() {
return
}
- d.compactionTransact("mem@flush", func() (err error) {
+ d.compactionTransact("mem@flush", func(cnt *compactionTransactCounter) (err error) {
stats.startTimer()
defer stats.stopTimer()
return c.flush(mem, -1)
@@ -212,7 +252,7 @@ func (d *DB) memCompaction() {
return nil
})
- d.compactionTransact("mem@commit", func() (err error) {
+ d.compactionTransact("mem@commit", func(cnt *compactionTransactCounter) (err error) {
stats.startTimer()
defer stats.stopTimer()
return c.commit(d.journalFile.Num(), d.frozenSeq)
@@ -251,7 +291,7 @@ func (d *DB) tableCompaction(c *compaction, noTrivial bool) {
s.logf("table@move L%d@%d -> L%d", c.level, t.file.Num(), c.level+1)
rec.deleteTable(c.level, t.file.Num())
rec.addTableFile(c.level+1, t)
- d.compactionTransact("table@move", func() (err error) {
+ d.compactionTransact("table@move", func(cnt *compactionTransactCounter) (err error) {
return s.commit(rec)
}, nil)
return
@@ -275,7 +315,7 @@ func (d *DB) tableCompaction(c *compaction, noTrivial bool) {
var snapIter int
var snapDropCnt int
var dropCnt int
- d.compactionTransact("table@build", func() (err error) {
+ d.compactionTransact("table@build", func(cnt *compactionTransactCounter) (err error) {
ukey := append([]byte{}, snapUkey...)
hasUkey := snapHasUkey
lseq := snapSeq
@@ -306,6 +346,9 @@ func (d *DB) tableCompaction(c *compaction, noTrivial bool) {
iter := c.newIterator()
defer iter.Release()
for i := 0; iter.Next(); i++ {
+ // Incr transact counter.
+ cnt.incr()
+
// Skip until last state.
if i < snapIter {
continue
@@ -429,7 +472,7 @@ func (d *DB) tableCompaction(c *compaction, noTrivial bool) {
})
// Commit changes
- d.compactionTransact("table@commit", func() (err error) {
+ d.compactionTransact("table@commit", func(cnt *compactionTransactCounter) (err error) {
stats[1].startTimer()
defer stats[1].stopTimer()
return s.commit(rec)
|
levledb: Add exponential backoff to compaction transact
|
FactomProject_goleveldb
|
train
|
f0b4218f59abe7d68350ddf350179fe9d686b7ca
|
diff --git a/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java b/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java
index <HASH>..<HASH> 100644
--- a/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java
+++ b/simulator/src/main/java/com/hazelcast/simulator/worker/tasks/AbstractWorker.java
@@ -42,16 +42,15 @@ public abstract class AbstractWorker<O extends Enum<O>> implements IWorker {
protected static final ILogger LOGGER = Logger.getLogger(AbstractWorker.class);
- private final Random random = new Random();
-
final OperationSelector<O> selector;
- // these fields will be injected by the TestContainer
@InjectTestContext
TestContext testContext;
@InjectProbe(useForThroughput = true)
Probe workerProbe;
+ private final Random random = new Random();
+
private long iteration;
private boolean isWorkerStopped;
diff --git a/tests/src/main/java/com/hazelcast/simulator/tests/synthetic/SyntheticTest.java b/tests/src/main/java/com/hazelcast/simulator/tests/synthetic/SyntheticTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/main/java/com/hazelcast/simulator/tests/synthetic/SyntheticTest.java
+++ b/tests/src/main/java/com/hazelcast/simulator/tests/synthetic/SyntheticTest.java
@@ -94,7 +94,7 @@ public class SyntheticTest {
@InjectHazelcastInstance
private HazelcastInstance targetInstance;
@InjectProbe(useForThroughput = true)
- public Probe probe;
+ private Probe probe;
@Teardown
public void teardown() {
|
Fixed CheckStyle issues in AbstractWorker and SyntheticTest.
|
hazelcast_hazelcast-simulator
|
train
|
38575e0f18343752ccdbc656e232211328b601cf
|
diff --git a/www/src/py_int.js b/www/src/py_int.js
index <HASH>..<HASH> 100644
--- a/www/src/py_int.js
+++ b/www/src/py_int.js
@@ -697,9 +697,7 @@ int.$factory = function(value, base){
if(_pre == "0X"){base = 16}
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
else if(_pre == "0O" && base != 8){invalid(_value, base)}
- else if(_pre == "0B" && base != 2){invalid(_value, base)
- }
- if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
+ if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
_value = _value.substr(2)
while(_value.startsWith("_")){
_value = _value.substr(1)
|
Fix bug in int(s, <I>) when s starts with 0B, eg int("0BFE", <I>)
|
brython-dev_brython
|
train
|
731d5dda4361ea8ca0f33ddd4bb60ca79fb4ec4a
|
diff --git a/pyhsmm/internals/hmm_states.py b/pyhsmm/internals/hmm_states.py
index <HASH>..<HASH> 100644
--- a/pyhsmm/internals/hmm_states.py
+++ b/pyhsmm/internals/hmm_states.py
@@ -471,14 +471,20 @@ class HMMStatesPython(_StatesBase):
if most_recently_updated:
return self._normalizer
else:
- mf_params = self.mf_trans_matrix, self.mf_pi_0, \
- self.mf_aBl, self._normalizer
- expected_stats = self.expected_transcounts, \
- self.expected_states[0], self.expected_states, 1.
-
- return self._normalizer + \
- sum(np.dot(np.ravel(a-b), np.ravel(c)) for a, b, c in zip(
- mf_params, self._mf_param_snapshot, expected_stats))
+ new_params = self.mf_trans_matrix, self.mf_pi_0, self.mf_aBl
+ _, _, new_normalizer = self._expected_statistics(*new_params)
+
+ old_params, old_normalizer = self._mf_param_snapshot[:3], \
+ self._mf_param_snapshot[-1]
+
+ E_stats = self.expected_transcounts, \
+ self.expected_states[0], self.expected_states
+
+ linear_term = \
+ sum(np.dot(np.ravel(a-b), np.ravel(c))
+ for a, b, c in zip(new_params, old_params, E_stats))
+
+ return linear_term - (new_normalizer - old_normalizer)
def _expected_statistics(self,trans_potential,init_potential,likelihood_log_potential):
alphal = self._messages_forwards_log(trans_potential,init_potential,
|
fix up vlb calculation when state factor is out of date
|
mattjj_pyhsmm
|
train
|
a1d22606fb3232f21c99813d14e0892202901581
|
diff --git a/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/fs/DedicatedFileSystem.java b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/fs/DedicatedFileSystem.java
index <HASH>..<HASH> 100644
--- a/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/fs/DedicatedFileSystem.java
+++ b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/fs/DedicatedFileSystem.java
@@ -25,6 +25,7 @@ import java.nio.file.ClosedWatchServiceException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
+import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Collection;
import java.util.Iterator;
@@ -34,7 +35,7 @@ import java.util.concurrent.ConcurrentMap;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
-import static java.nio.file.Files.getLastModifiedTime;
+import static java.nio.file.Files.readAttributes;
import static java.nio.file.StandardWatchEventKinds.*;
import static org.slf4j.LoggerFactory.getLogger;
@@ -209,28 +210,28 @@ public class DedicatedFileSystem implements Closeable, Runnable {
LOG.info("Ready for receiving events");
}
- private boolean hasChanged(final Path pPath) {
- boolean changed = false;
- try {
- final FileTime current = getLastModifiedTime(pPath);
- final FileTime cachedOrNull = timestamps.putIfAbsent(pPath, current);
- changed = !current.equals(cachedOrNull);
+ private boolean hasChanged(final Path pPath, final BasicFileAttributes pCurrentAttrs) throws IOException {
+ final FileTime current = pCurrentAttrs.lastModifiedTime();
+ final FileTime cachedOrNull = timestamps.putIfAbsent(pPath, current);
+ final boolean changed = !current.equals(cachedOrNull);
- if (cachedOrNull != null && changed) {
- timestamps.replace(pPath, cachedOrNull, current);
- }
- } catch (final IOException e) {
- LOG.warn("Modification time could not be determined!", e);
+ if (cachedOrNull != null && changed) {
+ timestamps.replace(pPath, cachedOrNull, current);
}
return changed;
}
private void processPath(final WatchEvent.Kind<?> pKind, final Path child) {
try {
- // The filename is the
- // context of the event.
- if ((ENTRY_CREATE == pKind || ENTRY_MODIFY == pKind) && hasChanged(child)) {
- virtualRoot.pathModified(child);
+ if (ENTRY_CREATE == pKind) {
+ final BasicFileAttributes currentAttrs = readAttributes(child, BasicFileAttributes.class);
+ if (currentAttrs.size() > 0 && hasChanged(child, currentAttrs)) {
+ virtualRoot.pathModified(child);
+ }
+ } else if (ENTRY_MODIFY == pKind) {
+ if (hasChanged(child, readAttributes(child, BasicFileAttributes.class))) {
+ virtualRoot.pathModified(child);
+ }
} else if (ENTRY_DELETE == pKind) {
try {
virtualRoot.pathDiscarded(child);
@@ -238,6 +239,8 @@ public class DedicatedFileSystem implements Closeable, Runnable {
timestamps.remove(child);
}
}
+ } catch (final IOException e) {
+ LOG.warn(format("FileAttributes could not be read for %s", child), e);
} catch (final RuntimeException e) {
LOG.error(e.getMessage(), e);
}
|
Check attributes of newly created files that it is not empty before continuing processing
|
SourcePond_fileobserver
|
train
|
06a9cb5d0f568eb5e04b3b87e1352630a07db646
|
diff --git a/client/dispatch.go b/client/dispatch.go
index <HASH>..<HASH> 100644
--- a/client/dispatch.go
+++ b/client/dispatch.go
@@ -122,7 +122,7 @@ func (hs *hSet) dispatch(conn *Conn, line *Line) {
return
}
for hn := list.start; hn != nil; hn = hn.next {
- go hn.Handle(conn, line)
+ go hn.Handle(conn, line.Copy())
}
}
|
Give each handler its own copy of *Line.
Thanks to Kevin Ballard for the suggestion.
|
fluffle_goirc
|
train
|
19c4ef1d44ca8044f402a30225cd0d1fa0030164
|
diff --git a/test/resolve-sass-paths.js b/test/resolve-sass-paths.js
index <HASH>..<HASH> 100644
--- a/test/resolve-sass-paths.js
+++ b/test/resolve-sass-paths.js
@@ -14,19 +14,17 @@ function subdir(dir) {
return dir.slice(fixtures.length);
}
-
test('\nresolving sass paths starting in the fixtures main directory', function (t) {
resolveSassPaths(path.join(__dirname, 'fixtures'), function (err, res) {
if (err) return console.error(err);
+ var dirs = res.map(subdir);
- t.deepEqual(
- res.map(subdir)
- , [ '/node_modules/foo/sass/index.scss',
- '/node_modules/foo/node_modules/fooz/sass/index.scss',
- '/node_modules/bar/node_modules/baz/sass/index.scss',
- '/sass/index.scss' ]
- , 'resolves all sass files of main package and its dependencies'
- )
+ [ '/node_modules/foo/sass/index.scss',
+ '/node_modules/foo/node_modules/fooz/sass/index.scss',
+ '/node_modules/bar/node_modules/baz/sass/index.scss',
+ '/sass/index.scss' ].forEach(function (dir) {
+ t.ok(~dirs.indexOf(dir), 'resolves ' + dir)
+ });
t.end()
})
})
|
fixing resolve tests to work independent of order
|
thlorenz_sass-resolve
|
train
|
79407432647c88b66932bae8cf5e227a21a3a572
|
diff --git a/policyuniverse/tests/test_policy.py b/policyuniverse/tests/test_policy.py
index <HASH>..<HASH> 100644
--- a/policyuniverse/tests/test_policy.py
+++ b/policyuniverse/tests/test_policy.py
@@ -138,7 +138,7 @@ class PolicyTestCase(unittest.TestCase):
self.assertEqual(
summary,
{
- "ec2": {"List", "Write", "Read", "Tagging"},
+ "ec2": {"List", "Write", "Read", "Tagging", "Permissions"},
"s3": {"Write", "Read", "List", "Permissions", "Tagging"},
},
)
|
Added permissions to EC2
|
Netflix-Skunkworks_policyuniverse
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.