hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
8904d36befa0cbb86b8089d6367ac19683338406 | diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100644
--- a/src/core.js
+++ b/src/core.js
@@ -986,7 +986,7 @@ Crafty.extend({
init: function () {
// When first called, set the gametime one frame before now!
if (typeof gameTime === "undefined")
- gameTime = (+new Date()) - milliSecPerFrame;
+ gameTime = (new Date().getTime()) - milliSecPerFrame;
var onFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
@@ -1071,7 +1071,7 @@ Crafty.extend({
step: function () {
var drawTimeStart, dt, lastFrameTime, loops = 0;
- currentTime = +new Date();
+ currentTime = new Date().getTime();
if (endTime > 0)
Crafty.trigger("MeasureWaitTime", currentTime - endTime);
@@ -1117,7 +1117,7 @@ Crafty.extend({
gameTime: gameTime
});
gameTime += dt;
- currentTime = +new Date();
+ currentTime = new Date().getTime();
Crafty.trigger("MeasureFrameTime", currentTime - lastFrameTime);
}
@@ -1127,7 +1127,7 @@ Crafty.extend({
Crafty.trigger("RenderScene");
// Post-render cleanup opportunity
Crafty.trigger("PostRender");
- currentTime = +new Date();
+ currentTime = new Date().getTime();
Crafty.trigger("MeasureRenderTime", currentTime - drawTimeStart);
} | Use getTime method instead of implicit conversion
This doesn't change anything in the behaviour, but it encourages good js
practices.
See also performances <URL> | craftyjs_Crafty | train |
bf4dbb6a34e49e9668c5938dda6d64a0419cea5d | diff --git a/lib/fdk/version.rb b/lib/fdk/version.rb
index <HASH>..<HASH> 100644
--- a/lib/fdk/version.rb
+++ b/lib/fdk/version.rb
@@ -17,5 +17,5 @@
#
module FDK
- VERSION = "0.0.30"
+ VERSION = "0.0.31"
end | Releasing version <I> | fnproject_fdk-ruby | train |
1f600cbd17f7de0f3dff09e51297763c7a57ac38 | diff --git a/dataviews/dataviews.py b/dataviews/dataviews.py
index <HASH>..<HASH> 100644
--- a/dataviews/dataviews.py
+++ b/dataviews/dataviews.py
@@ -70,6 +70,21 @@ class DataCurves(DataLayer):
+class DataHistogram(DataLayer):
+
+ bin_labels = param.List(default=[])
+
+ def __init__(self, hist, edges, **kwargs):
+ self.hist = hist
+ self.edges = edges
+ super(DataHistogram, self).__init__(None, **kwargs)
+
+ @property
+ def ndims(self):
+ return len(self.edges)
+
+
+
class DataOverlay(DataLayer, Overlay):
"""
A DataOverlay can contain a number of DataLayer objects, which are to be | Added DataHistogram to dataviews | pyviz_holoviews | train |
20fdfa0ff78c82a0a19be6ad7a82f6b3dea1587d | diff --git a/lib/fog/aws/requests/ses/send_raw_email.rb b/lib/fog/aws/requests/ses/send_raw_email.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/aws/requests/ses/send_raw_email.rb
+++ b/lib/fog/aws/requests/ses/send_raw_email.rb
@@ -11,10 +11,7 @@ module Fog
# * RawMessage <~String> - The message to be sent.
# * Options <~Hash>
# * Source <~String> - The sender's email address. Takes precenence over Return-Path if specified in RawMessage
- # * Destination <~Hash> - The destination for this email, composed of To:, From:, and CC: fields.
- # * BccAddresses <~Array> - The BCC: field(s) of the message.
- # * CcAddresses <~Array> - The CC: field(s) of the message.
- # * ToAddresses <~Array> - The To: field(s) of the message.
+ # * Destinations <~Array> - All destinations for this email.
#
# ==== Returns
# * response<~Excon::Response>:
@@ -25,9 +22,7 @@ module Fog
def send_raw_email(raw_message, options = {})
params = {}
if options.has_key?('Destinations')
- for key, values in options['Destinations']
- params.merge!(AWS.indexed_param("Destination.#{key}.member", [*values]))
- end
+ params.merge!(AWS.indexed_param('Destinations.member', [*options['Destinations']]))
end
if options.has_key?('Source')
params['Source'] = options['Source'] | Make specifying Destinations for send_raw_email work and match amazon docs | fog_fog | train |
411732e45ec6817e6eddc90e348702fe7a3b5a03 | diff --git a/client/extensions/woocommerce/components/address-view/index.js b/client/extensions/woocommerce/components/address-view/index.js
index <HASH>..<HASH> 100644
--- a/client/extensions/woocommerce/components/address-view/index.js
+++ b/client/extensions/woocommerce/components/address-view/index.js
@@ -115,6 +115,9 @@ class AddressView extends Component {
<option key={ option.code } value={ option.code }>{ option.name }</option>
);
} ) }
+ <option key="XX" value="XX" disabled="disabled">
+ { translate( 'More countries coming soon' ) }
+ </option>
</FormSelect>
</FormFieldSet>
</div> | Add a more-countries-coming-soon unselectable option to address view (#<I>) | Automattic_wp-calypso | train |
661583d11e112145a50963c369748c3d5dbee6a1 | diff --git a/LiSE/LiSE/character.py b/LiSE/LiSE/character.py
index <HASH>..<HASH> 100644
--- a/LiSE/LiSE/character.py
+++ b/LiSE/LiSE/character.py
@@ -352,17 +352,13 @@ class AbstractCharacter(MutableMapping):
n += 1
renamed[ok] = k
self.place[k] = v
- if type(g) is nx.MultiDiGraph:
- g = nx.DiGraph(g)
- elif type(g) is nx.MultiGraph:
- g = nx.Graph(g)
- if type(g) is nx.DiGraph:
- for u, v in g.edges:
- self.edge[renamed[u]][renamed[v]] = g.adj[u][v]
- else:
- assert type(g) is nx.Graph
- for u, v, d in g.edges.data():
- self.add_portal(renamed[u], renamed[v], symmetrical=True, **d)
+ for u in g.adj:
+ for v in g.adj[u]:
+ if isinstance(g, nx.MultiGraph) or\
+ isinstance(g, nx.MultiDiGraph):
+ self.edge[renamed[u]][renamed[v]] = g.adj[u][v][0]
+ else:
+ self.edge[renamed[u]][renamed[v]] = g.adj[u][v]
return self
def become(self, g):
@@ -399,22 +395,19 @@ class AbstractCharacter(MutableMapping):
def grid_2d_8graph(self, m, n):
"""Make a 2d graph that's connected 8 ways, enabling diagonal movement"""
- me = nx.Graph()
- node = me.node
- add_node = me.add_node
- add_edge = me.add_edge
+ place = self.place
+ new_place = self.new_place
for i in range(m):
for j in range(n):
- add_node((i, j))
+ new = new_place((i, j))
if i > 0:
- add_edge((i, j), (i-1, j))
+ new.two_way(place[i - 1, j])
if j > 0:
- add_edge((i, j), (i-1, j-1))
+ new.two_way(place[i - 1, j - 1])
if j > 0:
- add_edge((i, j), (i, j-1))
- if (i - 1, j + 1) in node:
- add_edge((i, j), (i-1, j+1))
- return self.copy_from(me)
+ new.two_way(place[i, j - 1])
+ if (i - 1, j + 1) in place:
+ new.two_way(place[i - 1, j + 1])
def grid_graph(self, dim, periodic=False):
return self.copy_from(nx.grid_graph(dim, periodic))
diff --git a/allegedb/allegedb/cache.py b/allegedb/allegedb/cache.py
index <HASH>..<HASH> 100644
--- a/allegedb/allegedb/cache.py
+++ b/allegedb/allegedb/cache.py
@@ -302,10 +302,15 @@ class Cache(object):
else:
for (parbranch, parturn, partick) in self.db._iter_parent_btt(branch, turn, tick):
par_kc_key = parentity + (parbranch,)
- if par_kc_key in keycache and keycache[par_kc_key].rev_gettable(parturn) \
- and keycache[par_kc_key][parturn].rev_gettable(partick):
- parkeys = keycache[par_kc_key][parturn][partick]
- break
+ if par_kc_key in keycache:
+ kcpkc = keycache[par_kc_key]
+ if parturn in kcpkc and kcpkc[parturn].rev_gettable(partick):
+ parkeys = kcpkc[parturn][partick]
+ break
+ elif kcpkc.rev_gettable(parturn-1):
+ partkeys = kcpkc[parturn-1]
+ parkeys = partkeys[partkeys.end]
+ break
else:
parkeys = frozenset()
kc = SettingsTurnDict() | Fix a keycache problem that might've never come up | LogicalDash_LiSE | train |
448bd578d8e74f823c83b360ae174db9ae36e31e | diff --git a/version.php b/version.php
index <HASH>..<HASH> 100644
--- a/version.php
+++ b/version.php
@@ -29,11 +29,11 @@
defined('MOODLE_INTERNAL') || die();
-$version = 2018102300.02; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2018102700.00; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
-$release = '3.6dev+ (Build: 20181023)'; // Human-friendly version name
+$release = '3.6dev+ (Build: 20181027)'; // Human-friendly version name
$branch = '36'; // This version's branch.
$maturity = MATURITY_ALPHA; // This version's maturity level. | on-demand release <I>dev+ | moodle_moodle | train |
87a19fe8b236e9514a3983e48d4b49ebcc0329da | diff --git a/lib/data_mapper/finalizer.rb b/lib/data_mapper/finalizer.rb
index <HASH>..<HASH> 100644
--- a/lib/data_mapper/finalizer.rb
+++ b/lib/data_mapper/finalizer.rb
@@ -65,6 +65,10 @@ module DataMapper
mapper_registry.register(mapper, connector.relationship)
end
end
+
+ @base_relation_mappers.each do |mapper|
+ mapper.relations.freeze unless mapper.relations.frozen?
+ end
end
end # class Finalizer
end # module DataMapper
diff --git a/lib/data_mapper/relation_registry.rb b/lib/data_mapper/relation_registry.rb
index <HASH>..<HASH> 100644
--- a/lib/data_mapper/relation_registry.rb
+++ b/lib/data_mapper/relation_registry.rb
@@ -3,17 +3,24 @@ module DataMapper
# Graph representation of finalized relations
#
class RelationRegistry < Graph
+ attr_reader :engine
attr_reader :node_class
attr_reader :edge_class
attr_reader :connectors
def initialize(engine)
super()
+ @engine = engine
@node_class = engine.relation_node_class
@edge_class = engine.relation_edge_class
@connectors = {}
end
+ # @api private
+ def reset
+ self.class.new(engine)
+ end
+
# Add new relation node to the graph
#
# @return [self]
diff --git a/spec/spec_helper_integration.rb b/spec/spec_helper_integration.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper_integration.rb
+++ b/spec/spec_helper_integration.rb
@@ -68,10 +68,8 @@ RSpec.configure do |config|
end
config.before do
- DataMapper.mapper_registry.each do |id, mapper|
- mapper.class.relations.instance_variable_set(:@nodes, Set.new)
- mapper.class.relations.instance_variable_set(:@edges, Set.new)
- mapper.class.relations.instance_variable_set(:@connectors, {})
+ DataMapper.engines.each do |name, engine|
+ engine.instance_variable_set(:@relations, engine.relations.reset)
end
DataMapper.mapper_registry.instance_variable_set(:@mappers, {}) | Freeze the relation graph after finalization | rom-rb_rom | train |
2f69bdc05962cf42c74bbc7a0544adc3d229a957 | diff --git a/aiortc/codecs/vpx.py b/aiortc/codecs/vpx.py
index <HASH>..<HASH> 100644
--- a/aiortc/codecs/vpx.py
+++ b/aiortc/codecs/vpx.py
@@ -149,7 +149,7 @@ class VpxDecoder:
div = p and 2 or 1
o_stride = img.d_w // div
for r in range(0, img.d_h // div):
- o_buf[o_pos:o_pos + o_stride] = i_buf[i_pos:i_pos + i_stride]
+ o_buf[o_pos:o_pos + o_stride] = i_buf[i_pos:i_pos + o_stride]
i_pos += i_stride
o_pos += o_stride | don't resize o_buf in VpXDecoder (fixes #<I>) | aiortc_aiortc | train |
523910c6b5532b8372c91fe6771e5aaf5a1d841e | diff --git a/versions/models.py b/versions/models.py
index <HASH>..<HASH> 100644
--- a/versions/models.py
+++ b/versions/models.py
@@ -1078,19 +1078,24 @@ class Versionable(models.Model):
# retrieve all current m2m relations pointing the newly created clone
# filter for source_id
m2m_rels = list(source.through.objects.filter(**{source.source_field.attname: clone.id}))
- later = []
+ later_current = []
+ later_non_current = []
for rel in m2m_rels:
# Only clone the relationship, if it is the current one; Simply adjust the older ones to point the old entry
# Otherwise, the number of pointers pointing an entry will grow exponentially
if rel.is_current:
- later.append(rel.clone(forced_version_date=self.version_end_date, in_bulk=True))
- # On rel, set the source ID to self.id
- setattr(rel, source.source_field_name, self)
- if not hasattr(rel, '_not_created') or not rel._not_created:
- rel.save()
+ later_current.append(rel.clone(forced_version_date=self.version_end_date, in_bulk=True))
+ # On rel, which is no more 'current', set the source ID to self.id
+ setattr(rel, source.source_field_name, self)
+ else:
+ later_non_current.append(rel)
# Perform the bulk changes rel.clone() did not perform because of the in_bulk parameter
- # This saves a huge bunch of SQL queries
- source.through.objects.filter(id__in=[l.id for l in later]).update(**{'version_start_date': forced_version_date})
+ # This saves a huge bunch of SQL queries:
+ # - update current version entries
+ source.through.objects.filter(id__in=[l.id for l in later_current]).update(**{'version_start_date': forced_version_date})
+ # - update entries that have been pointing the current object, but have never been 'current'
+ source.through.objects.filter(id__in=[l.id for l in later_non_current]).update(**{source.source_field.attname: self.id})
+ # - create entries that were 'current', but which have been relieved in this method run
source.through.objects.bulk_create([r for r in m2m_rels if hasattr(r, '_not_created') and r._not_created])
@staticmethod
diff --git a/versions_tests/tests/test_models.py b/versions_tests/tests/test_models.py
index <HASH>..<HASH> 100644
--- a/versions_tests/tests/test_models.py
+++ b/versions_tests/tests/test_models.py
@@ -1083,6 +1083,41 @@ class MultiM2MTest(TestCase):
# to restrict the records according to the desired as_of time.
self.assertEqual(3, len(Student.objects.current.annotate(num_teachers=Count('professors')).all()))
+ def test_constant_number_of_queries_when_cloning_m2m_related_object(self):
+ """
+ This test aims to verify whether the number of queries against the DB remains constant,
+ even if the number of M2M relations has grown.
+ This test was necessary in order to verify changes from PR #44
+ """
+ annika = Student.objects.current.get(name='Annika')
+ nb_professors = annika.professors.count()
+ nb_classrooms = annika.classrooms.count()
+ # Annika, at this point, has:
+ # - 3 professors
+ # - 3 classrooms
+
+ # There are 12 queries against the DB:
+ # - 3 for writing the new version of the object itself
+ # o 1 attempt to update the earlier version
+ # o 1 insert of the earlier version
+ # o 1 update of the later version
+ # - 5 for the professors relationship
+ # o 1 for selecting all concerned professor objects
+ # o 1 for selecting all concerned intermediate table entries (student_professor)
+ # o 1 for updating current intermediate entry versions
+ # o 1 for non-current rel-entries pointing the annika-object
+ # (there's 1 originating from the clone-operation on mr_biggs)
+ # o 1 for inserting new versions
+ # - 4 for the classrooms M2M relationship
+ # o 1 for selecting all concerned classroom objects
+ # o 1 for selecting all concerned intermediate table entries (student_classroom)
+ # o 1 for updating current intermediate entry versions
+ # o 0 for non-current rel-entries pointing the annika-object
+ # o 1 for inserting new versions
+
+ with self.assertNumQueries(12):
+ annika.clone()
+
class MultiM2MToSameTest(TestCase):
""" | Added a test case for @raphaelm's suggestion and also fixed the number of queries for non-current relations | swisscom_cleanerversion | train |
397863f93e5ae8ce800da67fe78064b56845de83 | diff --git a/tests/test_adres_api.py b/tests/test_adres_api.py
index <HASH>..<HASH> 100644
--- a/tests/test_adres_api.py
+++ b/tests/test_adres_api.py
@@ -1,9 +1,16 @@
"""Adres API tests."""
import unittest
import postcodepy
+from postcodepy import typedefs
from postcodepy import PostcodeError
from . import unittestsetup
+try:
+ from nose_parameterized import parameterized, param
+except:
+ print("*** Please install 'nose_parameterized' to run these tests ***")
+ exit(0)
+
import os
import sys
@@ -12,6 +19,13 @@ access_secret = None
api = None
[email protected]_addresstype
[email protected]_purposes
+def parse_response(r, pc):
+ """manipulate the response."""
+ return r
+
+
class Test_Adres_API(unittest.TestCase):
"""Tests for Adres API."""
@@ -34,6 +48,68 @@ class Test_Adres_API(unittest.TestCase):
access_key=access_key,
access_secret=access_secret)
+ @parameterized.expand([
+ ("Rijksmuseum",
+ ('1071XX', 1),
+ 'verblijfsobject',
+ ["bijeenkomstfunctie"],
+ "Amsterdam",
+ "Museumstraat",
+ ),
+ ("Sportschool",
+ ('8431NJ', 23),
+ 'verblijfsobject',
+ ["overige gebruiksfunctie"],
+ "Oosterwolde",
+ "Veengang",
+ ),
+ ("Gamma",
+ ('8431NJ', 8),
+ 'verblijfsobject',
+ ["kantoorfunctie", "winkelfunctie"],
+ "Oosterwolde",
+ "Veengang",
+ ),
+ ("Industrieterrein Douwe Egberts Joure",
+ ('8501ZD', 1),
+ 'verblijfsobject',
+ ["industriefunctie", "kantoorfunctie", "overige gebruiksfunctie"],
+ "Joure",
+ "Leeuwarderweg",
+ ),
+ ("Ziekenhuis Tjongerschans Heerenveen",
+ ('8441PW', 44),
+ 'verblijfsobject',
+ ["gezondheidszorgfunctie"],
+ "Heerenveen",
+ "Thialfweg",
+ ),
+ ("De Marwei te Leeuwarden",
+ ('8936AS', 7),
+ 'verblijfsobject',
+ ["celfunctie"],
+ "Leeuwarden",
+ "Holstmeerweg",
+ ),
+ ("Hotel de Zon Oosterwolde",
+ ('8431ET', 1),
+ 'verblijfsobject',
+ ["overige gebruiksfunctie"],
+ "Oosterwolde",
+ "Stationsstraat",
+ ),
+ ])
+ def test_Postcode_and_translation(self, description,
+ pc, addressType,
+ purpose, city, street):
+ """verify response data."""
+ retValue = api.get_postcodedata(*pc)
+ retValue = parse_response(retValue, pc)
+ self.assertTrue(retValue['addressType'] == addressType and
+ retValue['purposes'].sort() == purpose.sort() and
+ retValue['city'] == city and
+ retValue['street'] == street)
+
def test_PostcodeDataOK(self):
"""TEST: retrieval of data. | translation decorator tests added and bundled with existing response tests | hootnot_postcode-api-wrapper | train |
e42a7e9a657a4c9f515143ab7f86dc57319b735c | diff --git a/src/de/lmu/ifi/dbs/elki/result/outlier/OutlierResult.java b/src/de/lmu/ifi/dbs/elki/result/outlier/OutlierResult.java
index <HASH>..<HASH> 100644
--- a/src/de/lmu/ifi/dbs/elki/result/outlier/OutlierResult.java
+++ b/src/de/lmu/ifi/dbs/elki/result/outlier/OutlierResult.java
@@ -51,7 +51,7 @@ public class OutlierResult extends MultiResult {
* Get the outlier score meta data
* @return the outlier meta information
*/
- protected OutlierScoreMeta getOutlierMeta() {
+ public OutlierScoreMeta getOutlierMeta() {
return meta;
}
@@ -59,7 +59,7 @@ public class OutlierResult extends MultiResult {
* Get the outlier scores association.
* @return the scores
*/
- protected AnnotationResult<Double> getScores() {
+ public AnnotationResult<Double> getScores() {
return scores;
}
@@ -67,7 +67,7 @@ public class OutlierResult extends MultiResult {
* Get the outlier ordering
* @return the ordering
*/
- protected OrderingResult getOrdering() {
+ public OrderingResult getOrdering() {
return ordering;
}
} | Getters were meant to be public. | elki-project_elki | train |
fa11129a7b1a075981afa391d469fbb0e9f18179 | diff --git a/packages/react-ui-components/src/Button/index.story.js b/packages/react-ui-components/src/Button/index.story.js
index <HASH>..<HASH> 100644
--- a/packages/react-ui-components/src/Button/index.story.js
+++ b/packages/react-ui-components/src/Button/index.story.js
@@ -6,6 +6,7 @@ import Button from './index.js';
const validStyleKeys = ['clean', 'brand', 'lighter', 'transparent'];
const validHoverStyleKeys = ['clean', 'brand', 'darken'];
+const validSizes = ['small', 'regular'];
storiesOf('Button', module)
.addDecorator(withKnobs)
@@ -19,6 +20,7 @@ storiesOf('Button', module)
isDisabled={boolean('Disabled', false)}
isFocused={boolean('Focused', false)}
style={select('Style', validStyleKeys, 'clean')}
+ size={select('Size', validSizes, 'regular')}
hoverStyle={select('Hover style', validHoverStyleKeys, 'clean')}
onClick={action('onClick')}
onMouseEnter={action('onMouseEnter')}
diff --git a/packages/react-ui-components/src/IconButton/iconButton.js b/packages/react-ui-components/src/IconButton/iconButton.js
index <HASH>..<HASH> 100644
--- a/packages/react-ui-components/src/IconButton/iconButton.js
+++ b/packages/react-ui-components/src/IconButton/iconButton.js
@@ -8,12 +8,17 @@ const IconButton = props => {
className,
theme,
icon,
+ size,
...rest
} = props;
- const finalClassName = mergeClassNames(theme.iconButton, className);
+ const finalClassName = mergeClassNames({
+ [className]: className && className.length,
+ [theme.iconButton]: true,
+ [theme[`size-${size}`]]: true
+ });
return (
- <ButtonComponent {...rest} className={finalClassName}>
+ <ButtonComponent {...rest} size={size} className={finalClassName}>
<IconComponent icon={icon}/>
</ButtonComponent>
);
@@ -30,6 +35,11 @@ IconButton.propTypes = {
className: PropTypes.string,
/**
+ * Defines the size of the icon button.
+ */
+ size: PropTypes.oneOf(['small', 'regular']),
+
+ /**
* An optional css theme to be injected.
*/
theme: PropTypes.shape({/* eslint-disable quote-props */
@@ -43,6 +53,7 @@ IconButton.propTypes = {
ButtonComponent: PropTypes.any.isRequired
};
IconButton.defaultProps = {
+ size: 'regular',
style: 'transparent',
hoverStyle: 'brand'
};
diff --git a/packages/react-ui-components/src/IconButton/index.story.js b/packages/react-ui-components/src/IconButton/index.story.js
index <HASH>..<HASH> 100644
--- a/packages/react-ui-components/src/IconButton/index.story.js
+++ b/packages/react-ui-components/src/IconButton/index.story.js
@@ -6,6 +6,7 @@ import IconButton from './index.js';
const validStyleKeys = ['clean', 'brand', 'lighter', 'transparent'];
const validHoverStyleKeys = ['clean', 'brand', 'darken'];
+const validSizes = ['small', 'regular'];
storiesOf('IconButton', module)
.addDecorator(withKnobs)
@@ -17,6 +18,7 @@ storiesOf('IconButton', module)
icon={text('Icon', 'close')}
onClick={action('onClick')}
style={select('Style', validStyleKeys, 'clean')}
+ size={select('Size', validSizes, 'regular')}
hoverStyle={select('Hover style', validHoverStyleKeys, 'clean')}
/>
</StoryWrapper>
diff --git a/packages/react-ui-components/src/IconButton/style.css b/packages/react-ui-components/src/IconButton/style.css
index <HASH>..<HASH> 100644
--- a/packages/react-ui-components/src/IconButton/style.css
+++ b/packages/react-ui-components/src/IconButton/style.css
@@ -5,3 +5,8 @@
padding-left: 0;
padding-right: 0;
}
+
+.size-small {
+ width: 32px;
+ min-width: 32px;
+} | TASK: add small size to IconButton | neos_neos-ui | train |
e655d7af24aa89f71884d5948560dc87d81d5358 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -238,6 +238,12 @@ config.set('name', 'New Name');
### merge(obj)
This method allows you to merge configuration options into your local configuration. Convenient if you want to load some configuration options from the server and then use them with the configuration plugin. Use this to merge in options you might get via an AJAX request into the local cached configuration options.
+### lazyMerge(obj)
+Similar to `merge`, however, this method applies the configuration changes during `loadConfig`, rather than immediately.
+
+### mergeConfigFile(path)
+Similar to `merge`, but takes a file path instead of a configuration object.
+
### setAll(obj)
A method used by the plugin itself. Will set the configration object. Not advisable to use as it will delete any existing changes if not in the new obj value.
diff --git a/src/configure.js b/src/configure.js
index <HASH>..<HASH> 100644
--- a/src/configure.js
+++ b/src/configure.js
@@ -264,6 +264,24 @@ export class Configure {
this._config_object = merged;
}
+
+ /**
+ * Lazy Merge
+ *
+ * Allows you to merge in configuration options.
+ * This method might be used to merge in server-loaded
+ * configuration options with local ones. The merge
+ * occurs after the config has been loaded.
+ *
+ * @param obj
+ *
+ */
+ lazyMerge(obj) {
+ let currentMergeConfig = (this._config_merge_object || {});
+ let merged = deepExtend(currentMergeConfig, obj);
+
+ this._config_merge_object = merged;
+ }
/**
* Set All
@@ -289,15 +307,50 @@ export class Configure {
/**
* Load Config
- * Loads the configuration file from specified location
- * and then returns a Promise
+ * Loads the configuration file from specified location,
+ * merges in any overrides, then returns a Promise.
*
* @returns {Promise}
*/
loadConfig() {
- return this.loader.loadText(join(this.directory, this.config))
+ return this.loadConfigFile(join(this.directory, this.config), data => this.setAll(data))
+ .then(() => {
+ if (this._config_merge_object) {
+ this.merge(this._config_merge_object);
+ this._config_merge_object = null;
+ }
+ });
+ }
+
+ /**
+ * Load Config File
+ * Loads the configuration file from the specified location
+ * and then returns a Promise.
+ *
+ * @returns {Promise}
+ */
+ loadConfigFile(path, action) {
+ return this.loader.loadText(path)
+ .then(data => {
+ data = JSON.parse(data);
+ action(data);
+ })
.catch(() => {
throw new Error('Configuration file could not be found or loaded.')
});
}
+
+ /**
+ * Merge Config File
+ *
+ * Allows you to merge in configuration options from a file.
+ * This method might be used to merge in server-loaded
+ * configuration options with local ones.
+ *
+ * @param path
+ *
+ */
+ mergeConfigFile(path) {
+ return this.loadConfigFile(path, data => this.merge(data));
+ }
}
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -9,13 +9,11 @@ export function configure(aurelia, configCallback) {
}
return new Promise((resolve, reject) => {
- instance.loadConfig().then(data => {
- data = JSON.parse(data);
- instance.setAll(data);
- resolve();
- }).catch(() => {
- reject(new Error('Configuration file could not be loaded'));
- });
+ instance.loadConfig()
+ .then(() => resolve())
+ .catch(() => {
+ reject(new Error('Configuration file could not be loaded'));
+ });
})
} | Added functionality to make merging of config settings easier. | Vheissu_aurelia-configuration | train |
2fbceb4ad46e6b03c6e0f3d50c73a40206b859a4 | diff --git a/addon/routes/list-form.js b/addon/routes/list-form.js
index <HASH>..<HASH> 100644
--- a/addon/routes/list-form.js
+++ b/addon/routes/list-form.js
@@ -138,15 +138,22 @@ FlexberryObjectlistviewHierarchicalRouteMixin, {
hierarchicalAttribute: hierarchicalAttribute,
};
+ this.onModelLoadingStarted(queryParameters);
+
// Find by query is always fetching.
// TODO: support getting from cache with "store.all->filterByProjection".
// TODO: move includeSorting to setupController mixins?
return this.reloadList(queryParameters);
}).then((records) => {
this.get('formLoadTimeTracker').set('endLoadTime', performance.now());
+ this.onModelLoadingFulfilled(records);
this.includeSorting(records, this.sorting);
this.get('controller').set('model', records);
return records;
+ }).catch((errorData) => {
+ this.onModelLoadingRejected(errorData);
+ }).finally((data) => {
+ this.onModelLoadingAlways(data);
});
if (this.get('controller') === undefined) {
@@ -164,6 +171,73 @@ FlexberryObjectlistviewHierarchicalRouteMixin, {
},
/**
+ This method will be invoked before model loading operation will be called.
+ Override this method to add some custom logic on model loading operation start.
+
+ @example
+ ```javascript
+ onModelLoadingStarted(queryParameters) {
+ alert('Model loading operation started!');
+ }
+ ```
+ @method onModelLoadingStarted.
+ @param {Object} queryParameters Query parameters used for model loading operation.
+ */
+ onModelLoadingStarted(queryParameters) {
+ },
+
+ /**
+ This method will be invoked when model loading operation successfully completed.
+ Override this method to add some custom logic on model loading operation success.
+
+ @example
+ ```javascript
+ onModelLoadingFulfilled() {
+ alert('Model loading operation succeed!');
+ }
+ ```
+ @method onModelLoadingFulfilled.
+ @param {Object} model Loaded model data.
+ */
+ onModelLoadingFulfilled(model) {
+ },
+
+ /**
+ This method will be invoked when model loading operation completed, but failed.
+ Override this method to add some custom logic on model loading operation fail.
+
+ @example
+ ```javascript
+ onModelLoadingRejected() {
+ alert('Model loading operation failed!');
+ }
+ ```
+ @method onModelLoadingRejected.
+ @param {Object} errorData Data about model loading operation fail.
+ */
+ onModelLoadingRejected(errorData) {
+ // TODO: Provide information about error to user.
+ },
+
+ /**
+ This method will be invoked always when model loading operation completed,
+ regardless of model loading promise's state (was it fulfilled or rejected).
+ Override this method to add some custom logic on model loading operation completion.
+
+ @example
+ ```js
+ onModelLoadingAlways(data) {
+ alert('Model loading operation completed!');
+ }
+ ```
+
+ @method onModelLoadingAlways.
+ @param {Object} data Data about completed model loading operation.
+ */
+ onModelLoadingAlways(data) {
+ },
+
+ /**
A hook you can use to setup the controller for the current route.
[More info](http://emberjs.com/api/classes/Ember.Route.html#method_setupController). | Add model loading events for list-form route | Flexberry_ember-flexberry | train |
e08e21880a666bb9beca31c9e96c319d35f8c8c0 | diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index <HASH>..<HASH> 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -287,6 +287,8 @@ def test_output_redirection(base_app):
os.remove(filename)
[email protected](sys.platform == 'linux',
+ reason="Unit test passes on Ubuntu 16.04 and Debian 8.7, but fails on TravisCI Linux containers")
def test_input_redirection(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'redirect.txt') | Marked one test to skip on Linux because it fails on the TravisCI Linux containers.
But it works on both Ubuntu <I> and Debian <I>. | python-cmd2_cmd2 | train |
f80cc110624b78cd3488a6b84bd7d4275ec8d387 | diff --git a/src/com/mebigfatguy/fbcontrib/detect/PresizeCollections.java b/src/com/mebigfatguy/fbcontrib/detect/PresizeCollections.java
index <HASH>..<HASH> 100644
--- a/src/com/mebigfatguy/fbcontrib/detect/PresizeCollections.java
+++ b/src/com/mebigfatguy/fbcontrib/detect/PresizeCollections.java
@@ -60,6 +60,7 @@ public class PresizeCollections extends BytecodeScanningDetector {
private OpcodeStack stack;
private int allocNumber;
private Map<Integer, List<Integer>> allocToAddPCs;
+ private List<DownBranch> downBranches;
public PresizeCollections(BugReporter bugReporter) {
this.bugReporter = bugReporter;
@@ -74,10 +75,12 @@ public class PresizeCollections extends BytecodeScanningDetector {
try {
stack = new OpcodeStack();
allocToAddPCs = new HashMap<Integer, List<Integer>>();
+ downBranches = new ArrayList<DownBranch>();
super.visitClassContext(classContext);
} finally {
stack = null;
allocToAddPCs = null;
+ downBranches = null;
}
}
@@ -90,6 +93,7 @@ public class PresizeCollections extends BytecodeScanningDetector {
stack.resetForMethodEntry(this);
allocNumber = 0;
allocToAddPCs.clear();
+ downBranches.clear();
super.visitCode(obj);
for (List<Integer> pcs : allocToAddPCs.values()) {
@@ -146,6 +150,20 @@ public class PresizeCollections extends BytecodeScanningDetector {
}
break;
+ case IFEQ:
+ case IFNE:
+ case IFLT:
+ case IFGE:
+ case IFGT:
+ case IFLE:
+ case IF_ICMPEQ:
+ case IF_ICMPNE:
+ case IF_ICMPLT:
+ case IF_ICMPGE:
+ case IF_ICMPGT:
+ case IF_ICMPLE:
+ case IF_ACMPEQ:
+ case IF_ACMPNE:
case GOTO:
case GOTO_W:
if (getBranchOffset() < 0) {
@@ -155,15 +173,21 @@ public class PresizeCollections extends BytecodeScanningDetector {
List<Integer> pcs = it.next();
for (Integer pc : pcs) {
if (pc > target) {
- bugReporter.reportBug(new BugInstance(this, "PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY)
- .addClass(this)
- .addMethod(this)
- .addSourceLine(this, pc));
- it.remove();
+ int numDownBranches = countDownBranches(target, pc);
+ if (numDownBranches <= 1) {
+ bugReporter.reportBug(new BugInstance(this, "PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY)
+ .addClass(this)
+ .addMethod(this)
+ .addSourceLine(this, pc));
+ it.remove();
+ }
break;
}
}
}
+ } else {
+ DownBranch db = new DownBranch(getPC(), getBranchTarget());
+ downBranches.add(db);
}
}
} finally {
@@ -176,4 +200,30 @@ public class PresizeCollections extends BytecodeScanningDetector {
}
}
}
+
+ private int countDownBranches(int loopTop, int addPC) {
+ int numDownBranches = 0;
+ for (DownBranch db : downBranches) {
+ if ((db.fromPC > loopTop) && (db.toPC > addPC)) {
+ numDownBranches++;
+ }
+ }
+
+ return numDownBranches;
+ }
+
+ static class DownBranch {
+ public int fromPC;
+ public int toPC;
+
+ public DownBranch(int from, int to) {
+ fromPC = from;
+ toPC = to;
+ }
+
+ @Override
+ public String toString() {
+ return "DownBranch[From: " + fromPC + " To: " + toPC + "]";
+ }
+ }
} | fix fp for conditional add in a loop for PSC | mebigfatguy_fb-contrib | train |
66f795f5b6ce8f75d30469041cababd6e9deb6ee | diff --git a/packages/cozy-client/src/store/queries.js b/packages/cozy-client/src/store/queries.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/store/queries.js
+++ b/packages/cozy-client/src/store/queries.js
@@ -175,7 +175,8 @@ const queries = (state = {}, action, documents = {}) => {
return updater(queryState)
}
})
- } else if (isReceivingMutationResult(action) || isReceivingData(action)) {
+ }
+ if (isReceivingMutationResult(action)) {
const updater = action.updateQueries
? manualQueryUpdater(action, documents)
: autoQueryUpdater(action) | refactor: Removed unreachable condition | cozy_cozy-client | train |
a737eff06d0605e34601dee7d3a4e6ba80cbcde4 | diff --git a/docs/app/Components/ComponentDoc/ComponentExample/ComponentExample.js b/docs/app/Components/ComponentDoc/ComponentExample/ComponentExample.js
index <HASH>..<HASH> 100644
--- a/docs/app/Components/ComponentDoc/ComponentExample/ComponentExample.js
+++ b/docs/app/Components/ComponentDoc/ComponentExample/ComponentExample.js
@@ -200,7 +200,7 @@ class ComponentExample extends Component {
// which can be rendered in this ComponentExample's render() method
// rewrite imports to const statements against the UPPERCASE module names
- const imports = _.get(/(^import[\s\S]*from[\s\S]*['"]\n)/.exec(sourceCode), '[1]', '')
+ const imports = _.get(/(^[\s\S])*import[\s\S]*from[\s\S]*['"]\n/.exec(sourceCode), '[0]', '')
.replace(/[\s\n]+/g, ' ') // normalize spaces and make one line
.replace(/ import/g, '\nimport') // one import per line
.split('\n') // split lines | fix(docs): fix import regex (#<I>) (#<I>) | Semantic-Org_Semantic-UI-React | train |
244b78f4321f3c19434e6f1d60767ae85a472d66 | diff --git a/tests/postgres.py b/tests/postgres.py
index <HASH>..<HASH> 100644
--- a/tests/postgres.py
+++ b/tests/postgres.py
@@ -121,6 +121,16 @@ class TestTZField(ModelTestCase):
tzq2 = TZModel.get(TZModel.dt == dt2)
self.assertEqual(tzq2.id, tz2.id)
+ # Change the connection timezone?
+ self.database.execute_sql('set time zone "us/central";')
+ tz_db = TZModel[tz.id]
+ self.assertEqual(tz_db.dt.timetuple()[:4], (2019, 1, 1, 11))
+ self.assertEqual(tz_db.dt.utctimetuple()[:4], (2019, 1, 1, 17))
+
+ tz2_db = TZModel[tz2.id]
+ self.assertEqual(tz2_db.dt.timetuple()[:4], (2019, 1, 1, 6))
+ self.assertEqual(tz2_db.dt.utctimetuple()[:4], (2019, 1, 1, 12))
+
class TestHStoreField(ModelTestCase):
database = db_loader('postgres', db_class=PostgresqlExtDatabase, | Additional assertions re: changing connection tz. | coleifer_peewee | train |
995b57d8485b66ef81f2d48fde69cd54f3e37547 | diff --git a/Resources/public/js/form.js b/Resources/public/js/form.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/form.js
+++ b/Resources/public/js/form.js
@@ -4,6 +4,9 @@ require(['jquery'], function($){
'form',
function(){
var $form = $(this);
+ var $submitBtn = $form.find('button[type=submit]');
+ $submitBtn.addClass('disabled').find('span.glyphicon').hide();
+ $submitBtn.prepend('<span class="glyphicon glyphicon-refresh icon-refresh-animate"></span>');
$.ajax({
'type': 'POST',
'url':$(this).attr('action'), | METH-<I> throbber in submit button | CanalTP_MttBundle | train |
ae136a09d3c4db7e1765fb33466d80abec3c6bb1 | diff --git a/sendsms/api.py b/sendsms/api.py
index <HASH>..<HASH> 100644
--- a/sendsms/api.py
+++ b/sendsms/api.py
@@ -2,8 +2,6 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
-from sendsms.utils import load_object
-
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
diff --git a/sendsms/backends/esendex.py b/sendsms/backends/esendex.py
index <HASH>..<HASH> 100644
--- a/sendsms/backends/esendex.py
+++ b/sendsms/backends/esendex.py
@@ -25,7 +25,6 @@ Usage::
"""
from django.conf import settings
-from django.core.exceptions import ImproperlyConfigured
import requests
@@ -39,11 +38,11 @@ ESENDEX_SANDBOX = getattr(settings, "ESENDEX_SANDBOX", False)
class SmsBackend(BaseSmsBackend):
- """
+ """
SMS Backend for esendex.es provider.
- The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private
- project in the access data are dynamic, and are stored in the database. A child
+ The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private
+ project in the access data are dynamic, and are stored in the database. A child
class overrides the method "get_xxxx" to return data stored in the database.
"""
diff --git a/sendsms/backends/nexmo.py b/sendsms/backends/nexmo.py
index <HASH>..<HASH> 100644
--- a/sendsms/backends/nexmo.py
+++ b/sendsms/backends/nexmo.py
@@ -7,11 +7,9 @@ Author: Alican Toprak ([email protected])
~~~~~~~~~~~~~~~~~~~~~~
"""
-import base64
import logging
from django.conf import settings
-from django.core.exceptions import ImproperlyConfigured
import requests
diff --git a/sendsms/backends/smsglobal.py b/sendsms/backends/smsglobal.py
index <HASH>..<HASH> 100644
--- a/sendsms/backends/smsglobal.py
+++ b/sendsms/backends/smsglobal.py
@@ -4,7 +4,6 @@ import math
import re
import urllib
import urllib2
-from decimal import Decimal
from django.conf import settings
diff --git a/sendsms/backends/smspubli.py b/sendsms/backends/smspubli.py
index <HASH>..<HASH> 100644
--- a/sendsms/backends/smspubli.py
+++ b/sendsms/backends/smspubli.py
@@ -25,10 +25,7 @@ Usage::
message.send()
"""
-import logging
-
from django.conf import settings
-from django.core.exceptions import ImproperlyConfigured
import requests
@@ -46,11 +43,11 @@ SMSPUBLI_ALLOW_LONG_SMS = getattr(settings, "SMSPUBLI_ALLOW_LONG_SMS", False)
class SmsBackend(BaseSmsBackend):
- """
+ """
SMS Backend smspubli.com provider.
- The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private
- project in the access data are dynamic, and are stored in the database. A child
+ The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private
+ project in the access data are dynamic, and are stored in the database. A child
class overrides the method "get_xxxx" to return data stored in the database.
"""
diff --git a/setup.cfg b/setup.cfg
index <HASH>..<HASH> 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -10,6 +10,7 @@ exclude_lines =
if __name__ == .__main__.:
[flake8]
+ignore = E203, E266, E501, W503, W293
exclude = build,dist,env,.env,.tox,.eggs
max-line-length = 88
max-complexity = 18 | Remove unused imports and other formatting fixes | stefanfoulis_django-sendsms | train |
29c6478fafa551ed746757802edfb3d91885a7b9 | diff --git a/lib/serif/site.rb b/lib/serif/site.rb
index <HASH>..<HASH> 100644
--- a/lib/serif/site.rb
+++ b/lib/serif/site.rb
@@ -208,16 +208,12 @@ class Site
file = file_with_headers
end
- if layout_option
- if layout_option == "none"
- f.puts Liquid::Template.parse(file.to_s).render!("site" => self)
- else
- layout_file = File.join(self.directory, "_layouts", "#{layout_option}.html")
- layout = Liquid::Template.parse(File.read(layout_file))
- f.puts layout.render!("page" => { "title" => [title].compact }, "content" => Liquid::Template.parse(file.to_s).render!("site" => self))
- end
+ if layout_option == "none"
+ f.puts Liquid::Template.parse(file.to_s).render!("site" => self)
else
- f.puts default_layout.render!("page" => { "title" => [title].compact }, "content" => Liquid::Template.parse(file.to_s).render!("site" => self))
+ layout_file = File.join(self.directory, "_layouts", "#{layout_option}.html")
+ layout = Liquid::Template.parse(File.read(layout_file))
+ f.puts layout.render!("page" => { "title" => [title].compact }, "content" => Liquid::Template.parse(file.to_s).render!("site" => self))
end
end
end | Simplify layout_option logic.
layout_option is always truthy here, and defaults to :default, which
will give default.html as the file to use, so we can cut out the use of
default_layout for this non-post processing. | aprescott_serif | train |
c341b5eeacfdd1a2534e689743a04371fee0f904 | diff --git a/lib/shared/getBlacklist.js b/lib/shared/getBlacklist.js
index <HASH>..<HASH> 100644
--- a/lib/shared/getBlacklist.js
+++ b/lib/shared/getBlacklist.js
@@ -2,7 +2,7 @@
var wreck = require('wreck');
-var url = 'http://gulpjs.com/plugins/blackList.json';
+var url = 'https://gulpjs.com/plugins/blackList.json';
function getBlacklist(cb) {
wreck.get(url, { json: true }, function(err, res, blacklist) { | Fix: Blacklist redirect (#<I>) | gulpjs_gulp-cli | train |
f56d97f3f33c03bc3dd087469e1604aa0d90a94e | diff --git a/src/Themosis/Core/Application.php b/src/Themosis/Core/Application.php
index <HASH>..<HASH> 100644
--- a/src/Themosis/Core/Application.php
+++ b/src/Themosis/Core/Application.php
@@ -184,6 +184,10 @@ class Application extends Container implements ApplicationContract, HttpKernelIn
\Illuminate\Contracts\Routing\Registrar::class,
\Illuminate\Contracts\Routing\BindingRegistrar::class
],
+ 'url' => [
+ \Illuminate\Routing\UrlGenerator::class,
+ \Illuminate\Contracts\Routing\UrlGenerator::class
+ ],
'view' => [
\Illuminate\View\Factory::class,
\Illuminate\Contracts\View\Factory::class
@@ -586,7 +590,7 @@ class Application extends Container implements ApplicationContract, HttpKernelIn
*/
public function boot()
{
- if (! $this->booted) {
+ if ($this->booted) {
return;
} | Allow boot callbacks on providers. | themosis_framework | train |
2b7b9b26d6a22e09eb4d6e5b491f602635d84e56 | diff --git a/saltcloud/cloud.py b/saltcloud/cloud.py
index <HASH>..<HASH> 100644
--- a/saltcloud/cloud.py
+++ b/saltcloud/cloud.py
@@ -233,7 +233,7 @@ class Cloud(object):
)
continue
- if alias not in locations:
+ if alias not in data:
data[alias] = {}
try:
@@ -272,7 +272,7 @@ class Cloud(object):
)
continue
- if alias not in locations:
+ if alias not in data:
data[alias] = {}
try:
@@ -311,7 +311,7 @@ class Cloud(object):
)
continue
- if alias not in locations:
+ if alias not in data:
data[alias] = {}
try: | Fix bad reference to renamed variable. | saltstack_salt | train |
cf37c28e470113b980c4c5d3d0104054ae2750d8 | diff --git a/lib/tower_cli/resources/credential.py b/lib/tower_cli/resources/credential.py
index <HASH>..<HASH> 100644
--- a/lib/tower_cli/resources/credential.py
+++ b/lib/tower_cli/resources/credential.py
@@ -47,8 +47,16 @@ class Resource(models.Resource):
)
# SSH and SCM fields.
- username = models.Field(required=False)
- password = models.Field(password=True, required=False)
+ username = models.Field(
+ help_text='The username. For AWS credentials, the access key.',
+ required=False,
+ )
+ password = models.Field(
+ help_text='The password. For AWS credentials, the secret key. '
+ 'For Rackspace credentials, the API key.',
+ password=True,
+ required=False,
+ )
private_key = models.Field('ssh_key_data',
display=False,
help_text="The full path to the SSH private key to store. "
@@ -63,10 +71,3 @@ class Resource(models.Resource):
sudo_username = models.Field(required=False, display=False)
sudo_password = models.Field(password=True, required=False)
vault_password = models.Field(password=True, required=False)
-
- # AWS fields.
- access_key = models.Field(required=False, display=False)
- secret_key = models.Field(required=False, display=False)
-
- # Rackspace fields.
- api_key = models.Field(required=False, display=False) | Removing options that do not work.
...and documenting the correct ones. | ansible_tower-cli | train |
31e31fd5c2762102a847842255b6d440910e1431 | diff --git a/src/Auditable.php b/src/Auditable.php
index <HASH>..<HASH> 100644
--- a/src/Auditable.php
+++ b/src/Auditable.php
@@ -581,6 +581,14 @@ trait Auditable
));
}
+ // Redacted data should not be used when transitioning states
+ if ($auditRedactors = $this->getAuditRedactors()) {
+ throw new AuditableTransitionException(
+ 'Cannot transition states when Audit redactors are set',
+ $auditRedactors
+ );
+ }
+
// The attribute compatibility between the Audit and the Auditable model must be met
$modified = $audit->getModified(); | fix(Auditable): prevent transitioning states when redactors are set | owen-it_laravel-auditing | train |
c811c8d67244224708bf82ef8d676f980700c2fb | diff --git a/src/Http/Controllers/Frontendauth/FrontendAuthController.php b/src/Http/Controllers/Frontendauth/FrontendAuthController.php
index <HASH>..<HASH> 100644
--- a/src/Http/Controllers/Frontendauth/FrontendAuthController.php
+++ b/src/Http/Controllers/Frontendauth/FrontendAuthController.php
@@ -43,7 +43,9 @@ use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
// Laravel classes
-use Illuminate\Foundation\Auth\AuthenticatesUsers;
+//use Illuminate\Foundation\Auth\AuthenticatesUsers;
+use Lasallecms\Usermanagement\Http\Controllers\AdminAuth\AuthenticatesUsers;
+
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Validator; | Use replicated trait in FrontendAuthController.php. #<I> | lasallecms_lasallecms-l5-usermanagement-pkg | train |
0c6a8f1635dfed9e8793d12fdbc695388e00f86c | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,7 @@ Features
- Network information (local & WAN IPs, MAC address, online status)
- Currently active schedule (by day)
- Next scheduled event
+ - Last 10 days energy report
- Setters:
- Target temperatures (single, or range)
- Target temperature mode: cool, heat, range
diff --git a/examples.php b/examples.php
index <HASH>..<HASH> 100644
--- a/examples.php
+++ b/examples.php
@@ -98,6 +98,11 @@ $next_event = $nest->getNextScheduledEvent();
jlog($next_event);
echo "----------\n\n";
+echo "Last 10 days energy report:\n";
+$energy_report = $nest->getEnergyLatest();
+jlog($energy_report);
+echo "----------\n\n";
+
/* Helper functions */
function json_format($json) {
diff --git a/nest.class.php b/nest.class.php
index <HASH>..<HASH> 100644
--- a/nest.class.php
+++ b/nest.class.php
@@ -40,7 +40,6 @@ class Nest {
private $cache_file;
private $cache_expiration;
private $last_status;
- private $sessionID = null;
function __construct() {
$this->cookie_file = sys_get_temp_dir() . '/nest_php_cookies';
@@ -50,7 +49,6 @@ class Nest {
}
// Log in, if needed
$this->login();
- $this->sessionID = (time() * 1000) . '' . rand() * 100000000;
}
/* Getters and setters */
@@ -176,26 +174,21 @@ class Nest {
public function getEnergyLatest($serial_number=null) {
$serial_number = $this->getDefaultSerial($serial_number);
+
+ $payload = array(
+ 'keys' => array(
+ array('key' => "energy_latest.$serial_number")
+ )
+ );
+
+ $data = array(
+ 'payload=' . urlencode(json_encode($payload)),
+ '_method=POST',
+ );
- $payload = array(
- 'keys' => array(
- array('key' => 'energy_latest' . '.' . $serial_number) //energy_latest.01AA02AB2012002C
- )
- );
-
- $data = array(
- 'payload=' . urlencode(json_encode($payload)),
- 'X-nl-subscribe-timeout=8',
- '_method=POST',
- 'X-nl-client-timestamp=' . (time() * 1000),
- 'X-nl-session-id=' . $this->sessionID,
- 'X-nl-protocol-version=1',
- 'Authorization=Basic+' . $this->access_token
- );
-
- $url = '/v2/subscribe?' . (implode('&', $data));
+ $url = '/v2/subscribe?' . (implode('&', $data));
- return $this->doGET($url);
+ return $this->doGET($url);
}
public function setTargetTemperatureMode($mode, $temperature, $serial_number=null) { | Simplified & documented getEnergyLatest() | gboudreau_nest-api | train |
de5453415425627e89cd13ee2b55f39cc6751f6f | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -78,7 +78,6 @@ setup(
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9', | Drop support for python <I> | modlinltd_django-advanced-filters | train |
142de518bf28298b9807a1d05713e454d00998a1 | diff --git a/Tests/ApcUniversalClassLoaderTest.php b/Tests/ApcUniversalClassLoaderTest.php
index <HASH>..<HASH> 100644
--- a/Tests/ApcUniversalClassLoaderTest.php
+++ b/Tests/ApcUniversalClassLoaderTest.php
@@ -58,10 +58,8 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
public function getLoadClassTests()
{
return array(
- array('\\Apc\\Namespaced\\Foo', '\\Apc\\Namespaced\\Foo', '->loadClass() loads Apc\Namespaced\Foo class'),
+ array('\\Apc\\Namespaced\\Foo', 'Apc\\Namespaced\\Foo', '->loadClass() loads Apc\Namespaced\Foo class'),
array('Apc_Pearlike_Foo', 'Apc_Pearlike_Foo', '->loadClass() loads Apc_Pearlike_Foo class'),
- array('\\Apc\\Namespaced\\Bar', '\\Apc\\Namespaced\\Bar', '->loadClass() loads Apc\Namespaced\Bar class with a leading slash'),
- array('Apc_Pearlike_Bar', '\\Apc_Pearlike_Bar', '->loadClass() loads Apc_Pearlike_Bar class with a leading slash'),
);
}
@@ -82,9 +80,9 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
public function getLoadClassFromFallbackTests()
{
return array(
- array('\\Apc\\Namespaced\\Baz', '\\Apc\\Namespaced\\Baz', '->loadClass() loads Apc\Namespaced\Baz class'),
+ array('\\Apc\\Namespaced\\Baz', 'Apc\\Namespaced\\Baz', '->loadClass() loads Apc\Namespaced\Baz class'),
array('Apc_Pearlike_Baz', 'Apc_Pearlike_Baz', '->loadClass() loads Apc_Pearlike_Baz class'),
- array('\\Apc\\Namespaced\\FooBar', '\\Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'),
+ array('\\Apc\\Namespaced\\FooBar', 'Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'),
array('Apc_Pearlike_FooBar', 'Apc_Pearlike_FooBar', '->loadClass() loads Apc_Pearlike_Baz class from fallback dir'),
);
}
@@ -110,7 +108,7 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
),
- '\Apc\NamespaceCollision\A\Foo',
+ 'Apc\NamespaceCollision\A\Foo',
'->loadClass() loads NamespaceCollision\A\Foo from alpha.',
),
array(
@@ -118,7 +116,7 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
),
- '\Apc\NamespaceCollision\A\Bar',
+ 'Apc\NamespaceCollision\A\Bar',
'->loadClass() loads NamespaceCollision\A\Bar from alpha.',
),
array(
@@ -126,7 +124,7 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
),
- '\Apc\NamespaceCollision\A\B\Foo',
+ 'Apc\NamespaceCollision\A\B\Foo',
'->loadClass() loads NamespaceCollision\A\B\Foo from beta.',
),
array(
@@ -134,7 +132,7 @@ class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
),
- '\Apc\NamespaceCollision\A\B\Bar',
+ 'Apc\NamespaceCollision\A\B\Bar',
'->loadClass() loads NamespaceCollision\A\B\Bar from beta.',
),
); | Fix class names in ApcUniversalClassLoader tests. | symfony_class-loader | train |
66146f631f98d904caa622d407a69438e5d14d8b | diff --git a/go/vt/vtctl/vtctl.go b/go/vt/vtctl/vtctl.go
index <HASH>..<HASH> 100644
--- a/go/vt/vtctl/vtctl.go
+++ b/go/vt/vtctl/vtctl.go
@@ -911,7 +911,7 @@ func commandRunHealthCheck(ctx context.Context, wr *wrangler.Wrangler, subFlags
if err != nil {
return err
}
- servedType, err := parseTabletType(subFlags.Arg(1), []pb.TabletType{pb.TabletType_MASTER, pb.TabletType_REPLICA, pb.TabletType_RDONLY})
+ servedType, err := parseTabletType(subFlags.Arg(1), []pb.TabletType{pb.TabletType_REPLICA, pb.TabletType_RDONLY})
if err != nil {
return err
}
diff --git a/test/resharding.py b/test/resharding.py
index <HASH>..<HASH> 100755
--- a/test/resharding.py
+++ b/test/resharding.py
@@ -407,7 +407,7 @@ primary key (name)
def _check_stream_health_equals_binlog_player_vars(self, tablet):
blp_stats = utils.get_vars(tablet.port)
# Enforce health check because it's not running by default as tablets are not started with it.
- utils.run_vtctl(["RunHealthCheck", tablet.tablet_alias, 'master'])
+ utils.run_vtctl(["RunHealthCheck", tablet.tablet_alias, 'replica'])
stream_health, _ = utils.run_vtctl(['VtTabletStreamHealth',
'-count', '1',
tablet.tablet_alias], | vtctl: Revert that "master" is allowed as type for RunHealthCheck.
A tablet is never started with -tablet_type master and therefore the manual health check shouldn't support this as well. Nonetheless, any "replica" can become a "master". | vitessio_vitess | train |
99aa18808fd7f88cb8e97ec9a74ca6a0b2b4922f | diff --git a/mod/quiz/lib.php b/mod/quiz/lib.php
index <HASH>..<HASH> 100644
--- a/mod/quiz/lib.php
+++ b/mod/quiz/lib.php
@@ -518,7 +518,7 @@ function quiz_process_options(&$quiz) {
$boundary = trim($quiz->feedbackboundaries[$i]);
if (!is_numeric($boundary)) {
if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
- $boundary = substr($boundary, 0, -1);
+ $boundary = trim(substr($boundary, 0, -1));
if (is_numeric($boundary)) {
$boundary = $boundary * $quiz->grade / 100.0;
} else { | Make General feedback more tolerant of whitespace. Merged from MOODLE_<I>_STABLE. | moodle_moodle | train |
06794b371c640d577a020dc50e3628a5219abc81 | diff --git a/src/main/java/org/jdbdt/JDBDT.java b/src/main/java/org/jdbdt/JDBDT.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jdbdt/JDBDT.java
+++ b/src/main/java/org/jdbdt/JDBDT.java
@@ -538,7 +538,6 @@ public final class JDBDT {
* @param out Output stream.
*/
public void debug(DataSource source, PrintStream out) {
- CallInfo callInfo = CallInfo.create();
- new Log(out).write(callInfo, executeQuery(source));
+ new Log(out).write(CallInfo.create(), executeQuery(source));
}
} | JDBDT: simplified variant of debug method | JDBDT_jdbdt | train |
ef514d51bb84cfcb0ff1dd14e1e556e1f68a5862 | diff --git a/service/windows/service_windows_test.go b/service/windows/service_windows_test.go
index <HASH>..<HASH> 100644
--- a/service/windows/service_windows_test.go
+++ b/service/windows/service_windows_test.go
@@ -47,9 +47,9 @@ func (s *serviceManagerSuite) SetUpTest(c *gc.C) {
s.passwdStub = &testing.Stub{}
s.conn = windows.PatchMgrConnect(s, s.stub)
s.getPasswd = windows.PatchGetPassword(s, s.passwdStub)
- s.PatchValue(&windows.WinChangeServiceConfig2, func(win.Handle, uint32, *byte) error {
+ windows.WinChangeServiceConfig2 = func(win.Handle, uint32, *byte) error {
return nil
- })
+ }
// Set up the service.
s.name = "machine-1"
@@ -202,6 +202,31 @@ func (s *serviceManagerSuite) TestStop(c *gc.C) {
c.Assert(running, jc.IsFalse)
}
+func (s *serviceManagerSuite) TestEnsureRestartOnFailure(c *gc.C) {
+ windows.WinChangeServiceConfig2 = func(win.Handle, uint32, *byte) error {
+ return errors.New("ChangeServiceConfig2: zoinks")
+ }
+ err := s.mgr.Create(s.name, s.conf)
+ c.Assert(err, gc.ErrorMatches, "ChangeServiceConfig2: zoinks")
+}
+
+func (s *serviceManagerSuite) TestEnsureRestartOnFailureCloseHandleDoesNotOverwritePreviousError(c *gc.C) {
+ windows.WinChangeServiceConfig2 = func(win.Handle, uint32, *byte) error {
+ return errors.New("ChangeServiceConfig2: zoinks")
+ }
+ s.stub.SetErrors(nil, nil, errors.New("CloseHandle: floosh"))
+ err := s.mgr.Create(s.name, s.conf)
+ c.Assert(err, gc.ErrorMatches, "ChangeServiceConfig2: zoinks")
+ s.stub.CheckCallNames(c, "CreateService", "GetHandle", "CloseHandle", "Close")
+}
+
+func (s *serviceManagerSuite) TestEnsureRestartOnFailureCloseHandleReturnsErrorSuccessfully(c *gc.C) {
+ s.stub.SetErrors(nil, nil, errors.New("CloseHandle: floosh"))
+ err := s.mgr.Create(s.name, s.conf)
+ c.Assert(err, gc.ErrorMatches, "could not close "+s.name+"'s handle: CloseHandle: floosh")
+ s.stub.CheckCallNames(c, "CreateService", "GetHandle", "CloseHandle", "Close")
+}
+
func (s *serviceManagerSuite) TestChangePassword(c *gc.C) {
s.getPasswd.SetPasswd("fake")
err := s.mgr.Create(s.name, s.conf) | Add tests to ensure CloseHandle get called correctly | juju_juju | train |
5e286e5bab59328aedc29f5b766999af57aad2fe | diff --git a/src/java/com/threerings/media/sprite/ImageSprite.java b/src/java/com/threerings/media/sprite/ImageSprite.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/media/sprite/ImageSprite.java
+++ b/src/java/com/threerings/media/sprite/ImageSprite.java
@@ -1,5 +1,5 @@
//
-// $Id: ImageSprite.java,v 1.10 2002/07/08 21:15:35 mdb Exp $
+// $Id: ImageSprite.java,v 1.11 2002/09/17 02:34:05 ray Exp $
package com.threerings.media.sprite;
@@ -38,6 +38,11 @@ public class ImageSprite extends Sprite
/** Animation mode indicating time based animation. */
public static final int TIME_BASED = 2;
+ /** Animation mode indicating sequential progressive animation.
+ * Frame 0 is guaranteed to be shown first for the full duration, and
+ * so on. */
+ public static final int TIME_SEQUENTIAL = 3;
+
/**
* Constructs an image sprite without any associated frames and with
* an invalid default initial location. The sprite should be populated
@@ -221,7 +226,7 @@ public class ImageSprite extends Sprite
if (_frames == null) {
return;
}
-
+
int fcount = _frames.getFrameCount();
boolean moved = false;
@@ -241,6 +246,13 @@ public class ImageSprite extends Sprite
nfidx = (int)((timestamp/_frameDelay) % fcount);
break;
+ case TIME_SEQUENTIAL:
+ if (_firstStamp == 0L) {
+ _firstStamp = timestamp;
+ }
+ nfidx = (int) (((timestamp - _firstStamp) / _frameDelay) % fcount);
+ break;
+
case MOVEMENT_CUED:
// update the frame if the sprite moved
if (moved) {
@@ -273,6 +285,9 @@ public class ImageSprite extends Sprite
/** For how many milliseconds to display an animation frame. */
protected long _frameDelay;
+ /** The first timestamp seen (in TIME_SEQUENTIAL mode). */
+ protected long _firstStamp = 0L;
+
// /** DEBUG: The alpha level used when rendering our bounds. */
// protected static final Composite ALPHA_BOUNDS =
// AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f); | added TIME_SEQUENTIAL animation mode which shows frame 0 first, and
for the full duration.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1 | threerings_narya | train |
4c2459a017345a13a57b32f847fa17534bce3dfa | diff --git a/Services/Twilio.php b/Services/Twilio.php
index <HASH>..<HASH> 100644
--- a/Services/Twilio.php
+++ b/Services/Twilio.php
@@ -102,12 +102,10 @@ class Services_Twilio extends Services_Twilio_Resource
if ($headers['content-type'] == 'application/json') {
$object = json_decode($body);
return $object;
- } else {
- throw new ErrorException('not json');
}
- } else {
- throw new ErrorException("$status: $body");
+ throw new ErrorException('not json');
}
+ throw new ErrorException("$status: $body");
}
}
// vim: ai ts=2 sw=2 noet sta | * simplify if/else statements | twilio_twilio-php | train |
de1768cf7db3b6fa6dfafcee5556af9fd2dabbbb | diff --git a/saltobserver/redis_stream.py b/saltobserver/redis_stream.py
index <HASH>..<HASH> 100644
--- a/saltobserver/redis_stream.py
+++ b/saltobserver/redis_stream.py
@@ -16,7 +16,7 @@ class RedisStream(object):
minimum_version = StrictVersion("2.8.0")
if actual_version < minimum_version:
raise NotImplementedError
- self.redis.config_set('notify-keyspace-events', 'Kls')
+ self.redis.config_set('notify-keyspace-events', 'Ks')
self.pubsub = self.redis.pubsub()
# TODO: update subscription on newcomer minions
self.pubsub.psubscribe(["__keyspace@0__:{0}:*.*".format(minion) for minion in self.redis.smembers('minions')]) | we do not need the list events from redis, remove them | debugloop_saltobserver | train |
8da0034ba9000b83a66af3438219577902fb6acc | diff --git a/lib/coin.rb b/lib/coin.rb
index <HASH>..<HASH> 100644
--- a/lib/coin.rb
+++ b/lib/coin.rb
@@ -9,7 +9,7 @@ end
module Coin
class << self
extend Forwardable
- def_delegators :server, :delete, :clear, :length
+ def_delegators :server, :read_and_delete, :delete, :clear, :length
def read(key, lifetime=300)
value = server.read(key)
diff --git a/lib/coin/vault.rb b/lib/coin/vault.rb
index <HASH>..<HASH> 100644
--- a/lib/coin/vault.rb
+++ b/lib/coin/vault.rb
@@ -36,7 +36,7 @@ module Coin
end
def clear
- @dict = {}
+ @mutex.synchronize { @dict = {} }
end
def ok?
diff --git a/test/vault_test.rb b/test/vault_test.rb
index <HASH>..<HASH> 100644
--- a/test/vault_test.rb
+++ b/test/vault_test.rb
@@ -18,4 +18,12 @@ class VaultTest < MicroTest::Test
assert @vault.read(@key) == value
end
+ test "read_and_delete" do
+ value = rand(999999999)
+ @vault.write(@key, value)
+ val = @vault.read_and_delete(@key)
+ assert @vault.read(@key).nil?
+ assert val == value
+ end
+
end | Added test for read_and_delete. | hopsoft_coin | train |
4263889a97a4d922048997555330e1cbe3e83904 | diff --git a/hamster_lib/objects.py b/hamster_lib/objects.py
index <HASH>..<HASH> 100644
--- a/hamster_lib/objects.py
+++ b/hamster_lib/objects.py
@@ -664,10 +664,10 @@ class Fact(object):
# self.description or "")
if self.start:
- start = self.start.strftime("%d-%m-%Y %H:%M")
+ start = self.start.strftime("%Y-%m-%d %H:%M")
if self.end:
- end = self.end.strftime("%d-%m-%Y %H:%M")
+ end = self.end.strftime("%Y-%m-%d %H:%M")
if self.start and self.end:
result = '{} to {} {}'.format(start, end, result)
@@ -690,10 +690,10 @@ class Fact(object):
# self.description or "")
if self.start:
- start = repr(self.start.strftime("%d-%m-%Y %H:%M"))
+ start = repr(self.start.strftime("%Y-%m-%d %H:%M"))
if self.end:
- end = repr(self.end.strftime("%d-%m-%Y %H:%M"))
+ end = repr(self.end.strftime("%Y-%m-%d %H:%M"))
if self.start and self.end:
result = '{} to {} {}'.format(start, end, result)
diff --git a/tests/hamster_lib/test_objects.py b/tests/hamster_lib/test_objects.py
index <HASH>..<HASH> 100644
--- a/tests/hamster_lib/test_objects.py
+++ b/tests/hamster_lib/test_objects.py
@@ -435,8 +435,8 @@ class TestFact(object):
def test__str__(self, fact):
expectation = '{start} to {end} {activity}@{category}, {description}'.format(
- start=fact.start.strftime('%d-%m-%Y %H:%M'),
- end=fact.end.strftime('%d-%m-%Y %H:%M'),
+ start=fact.start.strftime('%Y-%m-%d %H:%M'),
+ end=fact.end.strftime('%Y-%m-%d %H:%M'),
activity=fact.activity.name,
category=fact.category.name,
description=fact.description
@@ -446,7 +446,7 @@ class TestFact(object):
def test__str__no_end(self, fact):
fact.end = None
expectation = '{start} {activity}@{category}, {description}'.format(
- start=fact.start.strftime('%d-%m-%Y %H:%M'),
+ start=fact.start.strftime('%Y-%m-%d %H:%M'),
activity=fact.activity.name,
category=fact.category.name,
description=fact.description
@@ -466,8 +466,8 @@ class TestFact(object):
def test__repr__(self, fact):
"""Make sure our debugging representation matches our expectations."""
expectation = '{start} to {end} {activity}@{category}, {description}'.format(
- start=repr(fact.start.strftime('%d-%m-%Y %H:%M')),
- end=repr(fact.end.strftime('%d-%m-%Y %H:%M')),
+ start=repr(fact.start.strftime('%Y-%m-%d %H:%M')),
+ end=repr(fact.end.strftime('%Y-%m-%d %H:%M')),
activity=repr(fact.activity.name),
category=repr(fact.category.name),
description=repr(fact.description)
@@ -482,7 +482,7 @@ class TestFact(object):
assert isinstance(result, str)
fact.end = None
expectation = '{start} {activity}@{category}, {description}'.format(
- start=repr(fact.start.strftime('%d-%m-%Y %H:%M')),
+ start=repr(fact.start.strftime('%Y-%m-%d %H:%M')),
activity=repr(fact.activity.name),
category=repr(fact.category.name),
description=repr(fact.description) | Change dateformat for str/repr(fact) to iso
This should be more in line with the format used by ``parse_raw_fact``.
Please note that still start and end are seperated by ``to`` here while
``parse_raw_fact`` uses ``-``.
Closes: LIB-<I> | projecthamster_hamster-lib | train |
1c0c24fe69a778a51971c2eddbe0896d5473a253 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index <HASH>..<HASH> 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -4,7 +4,9 @@ Changelog
1.2.0 (unreleased)
------------------
-- Nothing changed yet.
+**Bug fixes**
+
+- Fix invalid request when attaching a file on non UUID record id (fixes #122)
1.1.1 (2017-02-01)
diff --git a/kinto_attachment/tests/test_views_attachment.py b/kinto_attachment/tests/test_views_attachment.py
index <HASH>..<HASH> 100644
--- a/kinto_attachment/tests/test_views_attachment.py
+++ b/kinto_attachment/tests/test_views_attachment.py
@@ -17,6 +17,12 @@ class UploadTest(object):
resp = self.app.get(self.record_uri, headers=self.headers)
self.assertIn(self.file_field, resp.json['data'])
+ def test_record_is_created_with_valid_id(self):
+ self.record_uri = self.get_record_uri('fennec', 'fonts', 'logo')
+ self.endpoint_uri = self.record_uri + '/attachment'
+ self.app.put_json(self.record_uri, {}, headers=self.headers)
+ self.upload(status=200)
+
def test_returns_200_if_record_already_exists(self):
self.app.put_json(self.record_uri, {}, headers=self.headers)
self.upload(status=200)
diff --git a/kinto_attachment/utils.py b/kinto_attachment/utils.py
index <HASH>..<HASH> 100644
--- a/kinto_attachment/utils.py
+++ b/kinto_attachment/utils.py
@@ -83,6 +83,7 @@ def patch_record(record, request):
# Instantiate record resource with current request.
context = RouteFactory(request)
+ context.resource_name = 'record'
context.get_permission_object_id = lambda r, i: record_uri(r)
record_pattern = request.matched_route.pattern.replace('/attachment', '')
request.matched_route.pattern = record_pattern
@@ -92,7 +93,6 @@ def patch_record(record, request):
request.body = json.dumps(record).encode('utf-8')
resource = Record(request, context=context)
- request.current_resource_name = 'record'
setattr(request, '_attachment_auto_save', True) # Flag in update listener.
try: | Fix invalid request when attaching a file on non UUID record id (fixes #<I>) | Kinto_kinto-attachment | train |
acbab05acdc23e00a5f53ec6b8217b2790b747b8 | diff --git a/lib/writeexcel/workbook.rb b/lib/writeexcel/workbook.rb
index <HASH>..<HASH> 100644
--- a/lib/writeexcel/workbook.rb
+++ b/lib/writeexcel/workbook.rb
@@ -25,11 +25,24 @@ class Workbook < BIFFWriter
require 'writeexcel/properties'
require 'writeexcel/helper'
+ class Worksheets < Array
+ attr_accessor :activesheet
+
+ def initialize
+ @activesheet = nil
+ end
+
+ def activesheet_index
+ index(@activesheet)
+ end
+ end
+
attr_reader :url_format, :parser, :tempdir, :date_1904
attr_reader :compatibility, :palette
attr_reader :ext_refs
attr_reader :str_table
- attr_accessor :firstsheet, :activesheet
+ attr_reader :worksheets
+ attr_accessor :firstsheet
BOF = 12 # :nodoc:
EOF = 4 # :nodoc:
@@ -86,7 +99,7 @@ class Workbook < BIFFWriter
@chart_count = 0
@codepage = 0x04E4
@country = 1
- @worksheets = []
+ @worksheets = Worksheets.new
@formats = []
@palette = []
@biff_only = 0
@@ -94,7 +107,6 @@ class Workbook < BIFFWriter
@internal_fh = 0
@fh_out = ""
- @activesheet = nil
@firstsheet = 0
@str_total = 0
@str_unique = 0
@@ -1122,9 +1134,9 @@ class Workbook < BIFFWriter
calc_mso_sizes
# Ensure that at least one worksheet has been selected.
- unless @activesheet
- @activesheet = @worksheets.first
- @activesheet.select
+ unless @worksheets.activesheet
+ @worksheets.activesheet = @worksheets.first
+ @worksheets.activesheet.select
end
# Calculate the number of selected sheet tabs and set the active sheet.
@@ -1686,7 +1698,7 @@ class Workbook < BIFFWriter
ctabsel = @selected # Number of workbook tabs selected
tab_ratio = 0x0258 # Tab to scrollbar ratio
- tab_cur = @worksheets.index(@activesheet) # Active worksheet
+ tab_cur = @worksheets.activesheet_index # Active worksheet
tab_first = @firstsheet # 1st displayed worksheet
header = [record, length].pack("vv")
data = [
diff --git a/lib/writeexcel/worksheet.rb b/lib/writeexcel/worksheet.rb
index <HASH>..<HASH> 100644
--- a/lib/writeexcel/worksheet.rb
+++ b/lib/writeexcel/worksheet.rb
@@ -627,7 +627,7 @@ class Worksheet < BIFFWriter
def activate
@hidden = false # Active worksheet can't be hidden.
@selected = true
- @workbook.activesheet = self
+ @workbook.worksheets.activesheet = self
end
@@ -654,7 +654,7 @@ class Worksheet < BIFFWriter
# A hidden worksheet shouldn't be active or selected.
@selected = false
- @workbook.activesheet = nil
+ @workbook.worksheets.activesheet = nil
@workbook.firstsheet = 0
end
@@ -5028,7 +5028,7 @@ class Worksheet < BIFFWriter
end
def active?
- self == @workbook.activesheet
+ self == @workbook.worksheets.activesheet
end
def frozen? | * use Worksheets, and delete instance var @activesheet of Workbook | cxn03651_writeexcel | train |
f0f51940603ac99ae76a6abf3b24de50b8f82631 | diff --git a/src/FluxBB/Models/User.php b/src/FluxBB/Models/User.php
index <HASH>..<HASH> 100644
--- a/src/FluxBB/Models/User.php
+++ b/src/FluxBB/Models/User.php
@@ -25,10 +25,11 @@
namespace FluxBB\Models;
-use Auth,
+use Illuminate\Auth\UserInterface,
+ Auth,
Hash;
-class User extends Base
+class User extends Base implements UserInterface
{
protected $table = 'users';
@@ -223,4 +224,15 @@ class User extends Base
// TODO: Maybe reset some attributes like confirmation code here?
}
+
+ public function getAuthIdentifier()
+ {
+ return $this->getKey();
+ }
+
+ public function getAuthPassword()
+ {
+ return $this->password;
+ }
+
} | The User model should implement Illuminate's UserInterface. | fluxbb_core | train |
30dfe5e8b5143cee0b55f6970c666e2bd6537339 | diff --git a/templates/Angular2Spa/project.json b/templates/Angular2Spa/project.json
index <HASH>..<HASH> 100755
--- a/templates/Angular2Spa/project.json
+++ b/templates/Angular2Spa/project.json
@@ -67,8 +67,8 @@
"scripts": {
"prepublish": [
"npm install",
- "node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js",
- "node node_modules/webpack/bin/webpack.js"
+ "node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod",
+ "node node_modules/webpack/bin/webpack.js --env.prod"
],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
},
diff --git a/templates/Angular2Spa/webpack.config.js b/templates/Angular2Spa/webpack.config.js
index <HASH>..<HASH> 100644
--- a/templates/Angular2Spa/webpack.config.js
+++ b/templates/Angular2Spa/webpack.config.js
@@ -1,8 +1,7 @@
+var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
-var isDevBuild = process.env.ASPNETCORE_ENVIRONMENT === 'Development';
-
module.exports = {
devtool: isDevBuild ? 'inline-source-map' : null,
resolve: { extensions: [ '', '.js', '.ts' ] },
diff --git a/templates/Angular2Spa/webpack.config.vendor.js b/templates/Angular2Spa/webpack.config.vendor.js
index <HASH>..<HASH> 100644
--- a/templates/Angular2Spa/webpack.config.vendor.js
+++ b/templates/Angular2Spa/webpack.config.vendor.js
@@ -1,8 +1,8 @@
+var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
-var isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';
module.exports = {
resolve: {
@@ -47,7 +47,7 @@ module.exports = {
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
- ].concat(isDevelopment ? [] : [
+ ].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
}; | In Angular2Spa webpack config, use "--env.prod" arg to trigger prod builds instead of ASPNETCORE_ENVIRONMENT env var. This is to guarantee production mode when publishing. | aspnet_JavaScriptServices | train |
b9f9bed800e5605af566a828b4cf94ee24dad1b8 | diff --git a/gsh/console.py b/gsh/console.py
index <HASH>..<HASH> 100644
--- a/gsh/console.py
+++ b/gsh/console.py
@@ -49,33 +49,41 @@ def set_blocking_stdin(blocking):
# We remember the last printed status in order to clear it with ' ' characters
last_status = None
+stdout_is_terminal = sys.stdout.isatty()
+
def console_output(msg, output=sys.stdout):
"""Use instead of print, to clear the status information before printing"""
- global last_status
- if last_status:
- status_length = len(last_status)
- else:
- status_length = 0
+ if stdout_is_terminal:
+ global last_status
+ if last_status:
+ status_length = len(last_status)
+ else:
+ status_length = 0
set_blocking_stdin(True)
try:
- print >> output, '\r', status_length * ' ', '\r', msg,
+ if stdout_is_terminal:
+ print >> output, '\r', status_length * ' ', '\r', msg,
+ else:
+ print >> output, msg,
finally:
set_blocking_stdin(False)
- last_status = None
+ if stdout_is_terminal:
+ last_status = None
def show_status(completed, total):
"""The status is '[available shells/alive shells]>'"""
- status = '\r[%d/%d]> ' % (completed, total)
- global last_status
- if last_status != status:
- console_output(status)
- last_status = status
- set_blocking_stdin(True)
- try:
- # We flush because there is no '\n' but a '\r'
- sys.stdout.flush()
- finally:
- set_blocking_stdin(False)
+ if stdout_is_terminal:
+ status = '[%d/%d]> ' % (completed, total)
+ global last_status
+ if last_status != status:
+ console_output(status)
+ last_status = status
+ set_blocking_stdin(True)
+ try:
+ # We flush because there is no '\n' but a '\r'
+ sys.stdout.flush()
+ finally:
+ set_blocking_stdin(False)
def watch_window_size():
"""Detect when the window size changes, and propagate the new size to the
diff --git a/gsh/remote_dispatcher.py b/gsh/remote_dispatcher.py
index <HASH>..<HASH> 100644
--- a/gsh/remote_dispatcher.py
+++ b/gsh/remote_dispatcher.py
@@ -246,7 +246,7 @@ class remote_dispatcher(buffered_dispatcher):
lf_pos = limit
while lf_pos >= 0:
# For each line in the buffer
- line = self.read_buffer[:lf_pos]
+ line = self.read_buffer[:lf_pos - 1]
if self.prompt in line:
if self.options.interactive:
self.change_state(STATE_IDLE) | Avoid printing control characters ('\r') especially if stdout is not a tty | innogames_polysh | train |
ae2023e94c6f84905524f0e67aa2a9ed973d7980 | diff --git a/lib/uaa/cli/client_reg.rb b/lib/uaa/cli/client_reg.rb
index <HASH>..<HASH> 100644
--- a/lib/uaa/cli/client_reg.rb
+++ b/lib/uaa/cli/client_reg.rb
@@ -28,6 +28,7 @@ class ClientCli < CommonCli
:refresh_token_validity => 'seconds',
:redirect_uri => 'list',
:autoapprove => 'list',
+ :allowpublic => 'list',
:allowedproviders => 'list',
:'signup_redirect_url' => 'url'
}
@@ -46,7 +47,7 @@ class ClientCli < CommonCli
info[k] = opts[:interact] ?
info[k] = askd("#{k.to_s.gsub('_', ' ')} (#{p})", default): default
end
- if k == :autoapprove && (info[k] == 'true' || info[k] == 'false')
+ if (k == :autoapprove || k == :allowpublic) && (info[k] == 'true' || info[k] == 'false')
info[k] = !!(info[k] == 'true')
else
info[k] = Util.arglist(info[k]) if p == 'list' | add allowpublic option to client (#<I>) | cloudfoundry_cf-uaac | train |
a030df20b37b19319d351cf696c9945129987e92 | diff --git a/cmd3/__init__.py b/cmd3/__init__.py
index <HASH>..<HASH> 100644
--- a/cmd3/__init__.py
+++ b/cmd3/__init__.py
@@ -1,5 +1 @@
-from cmd3.version import version as cmd3_version
-
-version = cmd3_version
-
-__version__ = tuple(version.split('.'))
\ No newline at end of file
+version = "1.9.7"
\ No newline at end of file
diff --git a/cmd3/version.py b/cmd3/version.py
index <HASH>..<HASH> 100644
--- a/cmd3/version.py
+++ b/cmd3/version.py
@@ -1 +1 @@
-version = "1.9.5"
\ No newline at end of file
+version = "1.9.7"
\ No newline at end of file
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,7 +16,7 @@
# limitations under the License. #
# ------------------------------------------------------------------------#
-version = "1.9.5"
+version = "1.9.7"
from setuptools.command.test import test as TestCommand
from setuptools.command.install import install
@@ -70,6 +70,12 @@ class SetupYaml(install):
+def os_execute(commands):
+ for command in commands.split("\n"):
+ command = command.strip()
+ print (command)
+ os.system(command)
+
class UploadToPypi(install):
"""Upload the package to pypi. -- only for Maintainers."""
@@ -78,10 +84,12 @@ class UploadToPypi(install):
def run(self):
auto_create_version("cmd3", version)
os.system("make clean")
- os.system("python setup.py install")
- os.system("python setup.py bdist_wheel")
- banner("Build Distribution")
- os.system("python setup.py sdist --format=bztar,zip upload")
+ commands = """
+ python setup.py install
+ python setup.py bdist_wheel
+ python setup.py sdist --format=bztar,zip upload
+ """
+ os_execute(commands)
class InstallBase(install):
"""Install the cmd3 package."""
@@ -145,9 +153,9 @@ APP = ['cmd3/shell.py']
OPTIONS = {'argv_emulation': True}
setup(
- setup_requires=['py2app'],
- options={'py2app': OPTIONS},
- app=APP,
+# setup_requires=['py2app'],
+# options={'py2app': OPTIONS},
+# app=APP,
version=version,
name="cmd3",
description="cmd3 - A dynamic CMD shell with plugins", | removing osx py2app | cloudmesh-cmd3_cmd3 | train |
832a7e4992ba7bc30df07b15e2db559c99609ec8 | diff --git a/lib/traject/indexer.rb b/lib/traject/indexer.rb
index <HASH>..<HASH> 100644
--- a/lib/traject/indexer.rb
+++ b/lib/traject/indexer.rb
@@ -539,10 +539,11 @@ class Traject::Indexer
:logger => logger
)
+
if log_batch_size && (count % log_batch_size == 0)
batch_rps = log_batch_size / (Time.now - batch_start_time)
overall_rps = count / (Time.now - start_time)
- logger.send(settings["log.batch_size.severity"].downcase.to_sym, "Traject::Indexer#process, read #{count} records at: #{context.source_inspect}; #{'%.0f' % batch_rps}/s this batch, #{'%.0f' % overall_rps}/s overall")
+ logger.send(settings["log.batch_size.severity"].downcase.to_sym, "Traject::Indexer#process, read #{count} records at: #{context.record_inspect}; #{'%.0f' % batch_rps}/s this batch, #{'%.0f' % overall_rps}/s overall")
batch_start_time = Time.now
end
diff --git a/test/indexer/read_write_test.rb b/test/indexer/read_write_test.rb
index <HASH>..<HASH> 100644
--- a/test/indexer/read_write_test.rb
+++ b/test/indexer/read_write_test.rb
@@ -152,4 +152,27 @@ describe "Traject::Indexer#process" do
assert output_hashes.all? { |hash| hash["title"].length > 0 }
end
end
+
+ describe "setting log.batch_size" do
+ before do
+ @indexer = Traject::Indexer::MarcIndexer.new(
+ "writer_class_name" => "Traject::NullWriter",
+ "log.batch_size" => 1,
+ ) do
+ to_field "title", extract_marc("245")
+ end
+
+ @log_output = StringIO.new
+ logger = Logger.new(@log_output)
+ @indexer.logger = logger
+
+ @file = File.open(support_file_path "test_data.utf8.mrc")
+ end
+
+ it "outputs batch completion to log" do
+ @indexer.process(@file)
+
+ assert_includes @log_output.string, "Traject::Indexer#process, read 1 records at"
+ end
+ end
end | Fix method name typo in indexer batch logging
Bug found by @banukutlu, thanks!
Now with test that would have caught bug, and generally tests indexer batch logging. | traject_traject | train |
8519341d0f944ba6de9902528c43750b283a6bde | diff --git a/src/main/java/org/joda/money/DefaultCurrencyUnitDataProvider.java b/src/main/java/org/joda/money/DefaultCurrencyUnitDataProvider.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/joda/money/DefaultCurrencyUnitDataProvider.java
+++ b/src/main/java/org/joda/money/DefaultCurrencyUnitDataProvider.java
@@ -35,7 +35,7 @@ import java.util.regex.Pattern;
class DefaultCurrencyUnitDataProvider extends CurrencyUnitDataProvider {
/** Regex format for the csv line. */
- private static final Pattern REGEX_LINE = Pattern.compile("([A-Z]{3}),(-1|[0-9]{1,3}),(-1|0|1|2|3),([A-Z]*)#?.*");
+ private static final Pattern REGEX_LINE = Pattern.compile("([A-Z]{3}),(-1|[0-9]{1,3}),(-1|[0-9]),([A-Z]*)#?.*");
/**
* Registers all the currencies known by this provider. | Allow up to 9 decimal places to be defined in CSV file. | JodaOrg_joda-money | train |
8b20b0e5b6c2a4a5171f49c5cbddeb0d847d551b | diff --git a/scrapekit/logs.py b/scrapekit/logs.py
index <HASH>..<HASH> 100644
--- a/scrapekit/logs.py
+++ b/scrapekit/logs.py
@@ -1,7 +1,11 @@
import os
import logging
-import jsonlogger
+try:
+ import jsonlogger
+except ImportError:
+ # python-json-logger version 0.1.0 has changed the import structure
+ from pythonjsonlogger import jsonlogger
class TaskAdapter(logging.LoggerAdapter): | handle ImportError when importing jsonlogger since the package has changed its import structure | pudo-attic_scrapekit | train |
966a01891ff9c2db2f3fd4385f76c9f6744cb5ae | diff --git a/eZ/Publish/Core/Base/Exceptions/InvalidArgumentType.php b/eZ/Publish/Core/Base/Exceptions/InvalidArgumentType.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/Base/Exceptions/InvalidArgumentType.php
+++ b/eZ/Publish/Core/Base/Exceptions/InvalidArgumentType.php
@@ -20,18 +20,25 @@ use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException,
class InvalidArgumentType extends InvalidArgumentException
{
/**
- * Generates: "Argument '{$argumentName}' is invalid: '{$expectedType}' is wrong type[ in class '{$className}']"
+ * Generates: "Argument '{$argumentName}' is invalid: expected value to be of type '{$expectedType}'[, got '{$value}']"
*
* @param string $argumentName
* @param string $expectedType
- * @param string|null $className Optionally to specify class in abstract/parent classes
+ * @param mixed|null $value Optionally to output the type that was recived
* @param \Exception|null $previous
*/
- public function __construct( $argumentName, $expectedType, $className = null, Exception $previous = null )
+ public function __construct( $argumentName, $expectedType, $value = null, Exception $previous = null )
{
+ if ( $value === null )
+ $valueString = '';
+ else if ( is_object( $value ) )
+ $valueString = ", got '". get_class( $value ) . "'";
+ else
+ $valueString = ", got '". gettype( $value ) . "'";
+
parent::__construct(
$argumentName,
- "'{$expectedType}' is wrong type" .( $className ? " in class '{$className}'" : "" ),
+ "expected value to be of type '{$expectedType}'" . $valueString,
$previous
);
} | Fixed InvalidArgumentType to work as current use expects | ezsystems_ezpublish-kernel | train |
de46fde4091e7ec9d058f76e98fceca933bf80c2 | diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -20,7 +20,7 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
const debugLevelIndex = debugLevels.indexOf(options.debug);
function log(msg, level) {
if (level === 0) {
- msg = `WARNING - ${msg}`;
+ msg = `WARNING - ${msg}`;
} else {
level = level || 1;
}
@@ -42,8 +42,8 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
}
const apply = (compiler) => {
- const fileDependencies = [];
- const contextDependencies = [];
+ let fileDependencies;
+ let contextDependencies;
const written = {};
compiler.plugin('emit', (compilation, cb) => {
@@ -53,6 +53,9 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
cb();
};
+ fileDependencies = [];
+ contextDependencies = [];
+
const globalRef = {
info,
debug,
@@ -95,9 +98,12 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
cb();
};
+ const compilationFileDependencies = new Set(compilation.fileDependencies);
+ const compilationContextDependencies = new Set(compilation.contextDependencies);
+
// Add file dependencies if they're not already tracked
_.forEach(fileDependencies, (file) => {
- if (_.includes(compilation.fileDependencies, file)) {
+ if (compilationFileDependencies.has(file)) {
debug(`not adding ${file} to change tracking, because it's already tracked`);
} else {
debug(`adding ${file} to change tracking`);
@@ -107,7 +113,7 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
// Add context dependencies if they're not already tracked
_.forEach(contextDependencies, (context) => {
- if (_.includes(compilation.contextDependencies, context)) {
+ if (compilationContextDependencies.has(context)) {
debug(`not adding ${context} to change tracking, because it's already tracked`);
} else {
debug(`adding ${context} to change tracking`);
@@ -118,7 +124,7 @@ function CopyWebpackPlugin(patterns = [], options = {}) {
callback();
});
};
-
+
return {
apply
}; | fix: Memory leak in watch mode and use Set for performance (#<I>) | meeroslav_pr-copy-webpack-plugin | train |
f01dcc5795f3982b006357a5565edd9e802761e5 | diff --git a/src/PdoAdapter.php b/src/PdoAdapter.php
index <HASH>..<HASH> 100644
--- a/src/PdoAdapter.php
+++ b/src/PdoAdapter.php
@@ -393,12 +393,15 @@ class PdoAdapter implements AdapterInterface
*/
protected function extractChunks($pathId, $resource)
{
- $chunkSize = $this->config->get('chunk_size');
- $sql = "SELECT content FROM {$this->chunkTable} WHERE path_id = :path_id ORDER BY chunk_no ASC";
- $stmt = $this->db->prepare($sql);
+ $sql = "SELECT content FROM {$this->chunkTable} WHERE path_id = :path_id ORDER BY chunk_no ASC";
+ $stmt = $this->db->prepare($sql);
$stmt->execute(['path_id' => $pathId]);
while ($content = $stmt->fetchColumn()) {
- fwrite($resource, $content, $chunkSize);
+ $contentLength = strlen($content);
+ $pointer = 0;
+ while ($pointer < $contentLength) {
+ $pointer += fwrite($resource, substr($content, $pointer, 1024));
+ }
unset($content);
}
rewind($resource); | Fix #2 Split up data extraction
Further break down of the DB chunk into small more memory manageable
parts. | phlib_flysystem-pdo | train |
10a9a631ed92185da119940edf0228e64c47cf16 | diff --git a/dynamic_dynamodb/__init__.py b/dynamic_dynamodb/__init__.py
index <HASH>..<HASH> 100644
--- a/dynamic_dynamodb/__init__.py
+++ b/dynamic_dynamodb/__init__.py
@@ -27,7 +27,7 @@ import core
from daemon import Daemon
from config_handler import CONFIGURATION as configuration
-VERSION = '1.0.1'
+VERSION = '1.1.0-SNAPSHOT'
class DynamicDynamoDBDaemon(Daemon):
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup
setup(name='dynamic-dynamodb',
- version='1.0.1',
+ version='1.1.0-SNAPSHOT',
license='Apache License, Version 2.0',
description='Automatic provisioning for AWS DynamoDB tables',
author='Sebastian Dahlgren', | Bumped to <I>-SNAPSHOT | sebdah_dynamic-dynamodb | train |
f208479f5c64a552724863ca5dab2aa6555cd336 | diff --git a/app/actions/peptable/base.py b/app/actions/peptable/base.py
index <HASH>..<HASH> 100644
--- a/app/actions/peptable/base.py
+++ b/app/actions/peptable/base.py
@@ -1,13 +1,12 @@
from app.dataformats import mzidtsv as psmtsvdata
-def add_peptide(allpeps, psm, key, score, fncol=None, new=False,
- track_psms=True):
+def add_peptide(allpeps, psm, key, score, fncol=False, new=False):
peptide = {'score': score,
'line': psm,
'psms': []
}
- if track_psms:
+ if fncol:
if not new:
peptide['psms'] = allpeps[key]['psms']
peptide['psms'].append('{0}_{1}'.format(psm[fncol],
@@ -15,22 +14,19 @@ def add_peptide(allpeps, psm, key, score, fncol=None, new=False,
allpeps[key] = peptide
-def evaluate_peptide(peptides, psm, key, higherbetter, scorecol, fncol=None,
- track_psms=True):
+def evaluate_peptide(peptides, psm, key, higherbetter, scorecol, fncol=None):
try:
score = float(psm[scorecol])
except ValueError:
- # If score is NA or similar, dont use this PSM
+ # If score is NA or similar, dont use this PSM
return peptides
try:
existing_score = peptides[key]['score']
except KeyError:
- add_peptide(peptides, psm, key, score, fncol, True, track_psms)
+ add_peptide(peptides, psm, key, score, fncol, new=True)
else:
if higherbetter and score > existing_score:
- add_peptide(peptides, psm, key, score, fncol,
- track_psms=track_psms)
+ add_peptide(peptides, psm, key, score, fncol)
elif not higherbetter and score < existing_score:
- add_peptide(peptides, psm, key, score, fncol,
- track_psms=track_psms)
+ add_peptide(peptides, psm, key, score, fncol)
return peptides
diff --git a/app/actions/prottable/bestpeptide.py b/app/actions/prottable/bestpeptide.py
index <HASH>..<HASH> 100644
--- a/app/actions/prottable/bestpeptide.py
+++ b/app/actions/prottable/bestpeptide.py
@@ -16,8 +16,8 @@ def generate_proteins(pepfn, proteins, pepheader, scorecol, minlog,
if ';' in p_acc:
continue
protein_peptides = evaluate_peptide(protein_peptides, psm, p_acc,
- higherbetter, scorecol, fncol=None,
- track_psms=False)
+ higherbetter, scorecol,
+ fncol=False)
if minlog:
nextbestscore = min([pep['score'] for pep in protein_peptides.values()
if pep['score'] > 0])
diff --git a/app/drivers/peptable/psmtopeptable.py b/app/drivers/peptable/psmtopeptable.py
index <HASH>..<HASH> 100644
--- a/app/drivers/peptable/psmtopeptable.py
+++ b/app/drivers/peptable/psmtopeptable.py
@@ -13,8 +13,8 @@ class MzidTSVPeptableDriver(PepProttableDriver):
def __init__(self, **kwargs):
super().__init__(**kwargs)
- self.fncol = kwargs.get('speccol', None)
- self.scorecol = kwargs.get('scorecol', None)
+ self.fncol = kwargs.get('speccol', False)
+ self.scorecol = kwargs.get('scorecol')
self.quantcolpattern = kwargs.get('quantcolpattern', None)
self.precursorquantcolpattern = kwargs.get('precursorquantcolpattern',
None)
diff --git a/peptable.py b/peptable.py
index <HASH>..<HASH> 100755
--- a/peptable.py
+++ b/peptable.py
@@ -37,7 +37,8 @@ parser.add_argument('-c', dest='command', type=str,
help='How to manipulate the input:\n'
'psm2pep - Create peptide table from PSM TSV input,\n'
'uses best scoring PSM for each peptide and medians of\n'
- 'quant information. Use with --spectracol, --scorecol,\n'
+ 'quant information. Use with --spectracol (optional for\n'
+ 'tracking PSMs fr. different spectra files), --scorecol,\n'
'--ms1quantcolpattern, --isobquantcolpattern.\n\n'
'modelqvals - Recalculate peptide q-values by creating\n' | Removed track_psms var so scorecol input becomes what decides if psms are tracked when building peptide tables | glormph_msstitch | train |
3de971c6932f8da5d615007a089c08991b2ca5c7 | diff --git a/spec/models/generic_work_spec.rb b/spec/models/generic_work_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/generic_work_spec.rb
+++ b/spec/models/generic_work_spec.rb
@@ -41,9 +41,14 @@ RSpec.describe GenericWork do
let(:work) { described_class.new(state: inactive) }
let(:inactive) { ::RDF::URI('http://fedora.info/definitions/1/0/access/ObjState#inactive') }
- subject { work.state.rdf_subject }
+ it 'is inactive' do
+ expect(work.state.rdf_subject).to eq inactive
+ end
- it { is_expected.to eq inactive }
+ it 'allows state to be set to ActiveTriples::Resource' do
+ other_work = described_class.new(state: work.state)
+ expect(other_work.state.rdf_subject).to eq inactive
+ end
end
describe '#suppressed?' do | Setting work state to ActiveTriples::Resource. | samvera_hyrax | train |
dbfca4913546f6980b7e7b3b77dc04e153486137 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -25,7 +25,7 @@ __date__ = '$Date$'[7:-2]
name = 'jaraco.util'
setup (name = name,
- version = '2.3.1',
+ version = '3.0',
description = 'General utility modules that supply commonly-used functionality',
long_description = long_description,
author = 'Jason R. Coombs', | Bumped to <I> in preparation for code trimming | jaraco_jaraco.util | train |
f66251dc8b1e0893ade59c08535248eec5b9193c | diff --git a/src/test/java/picocli/SubcommandTests.java b/src/test/java/picocli/SubcommandTests.java
index <HASH>..<HASH> 100644
--- a/src/test/java/picocli/SubcommandTests.java
+++ b/src/test/java/picocli/SubcommandTests.java
@@ -1,5 +1,6 @@
package picocli;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
@@ -2734,4 +2735,28 @@ public class SubcommandTests {
assertTrue("An inherited parameter was not marked as such!", subsubParamFromSub.inherited());
assertEquals("An inheritable parameter rooted in a subcommand's root was not itself!", subParamRooted, subsubParamFromSub.root());
}
+
+ @Ignore("requires #1183")
+ @Test
+ public void testIssue1183_HelpWithSubcommandWithRequiredOptions() {
+ @Command(name = "app", mixinStandardHelpOptions = true)
+ class App implements Runnable {
+ public void run() { throw new IllegalStateException("app"); }
+
+ @Command int sub(@Option(names = "-x", required = true) int x) {
+ throw new IllegalStateException("sub");
+ }
+ }
+ int exitCode = new CommandLine(new App()).execute("-h", "sub");
+ assertEquals(0, exitCode);
+ assertEquals("", systemErrRule.getLog());
+
+ String expected = String.format("" +
+ "Usage: app [-hV] [COMMAND]%n" +
+ " -h, --help Show this help message and exit.%n" +
+ " -V, --version Print version information and exit.%n" +
+ "Commands:%n" +
+ " sub%n");
+ assertEquals(expected, systemOutRule.getLog());
+ }
} | [#<I>] add test to reproduce the issue | remkop_picocli | train |
a40a93dae8401f2c129e246383fe6c5825902a29 | diff --git a/lib/RippleBackgroundTransition.js b/lib/RippleBackgroundTransition.js
index <HASH>..<HASH> 100644
--- a/lib/RippleBackgroundTransition.js
+++ b/lib/RippleBackgroundTransition.js
@@ -12,36 +12,31 @@ import {
} from 'react-native'
import { easeOut } from './utils/easing'
-type Props = {
+type RBTProps = {
color: string,
posX: number,
posY: number
}
-export default class RippleBackgroundTransition extends Component {
- props: Props
+type RBTState = {
+ animating: boolean,
+ distance: number,
+ scale: Animated.Value
+}
- state: {
- animating: boolean,
- distance: number,
- scale: Animated.Value
- }
+export default class RippleBackgroundTransition extends Component {
+ props: RBTProps
+ state: RBTState
+ layout: { x: number, y: number, width: number, height: number }
scaleInit: number
- layout: {
- x: number,
- y: number,
- width: number,
- height: number
- }
-
- constructor(props: Props) {
+ constructor(props: RBTProps) {
super(props)
this.scaleInit = Platform.OS === 'android' ? 0.01 : 0
this.layout = { x: 0, y: 0, width: 0, height: 0 }
- this.state = { ...this._initState() }
+ this.state = this._initState()
}
_initState = () => {
@@ -143,7 +138,7 @@ export default class RippleBackgroundTransition extends Component {
callback(this.props.color)
// Reset everything
- this.setState({ ...this._initState() })
+ this.setState(this._initState())
})
}
} | Code cleaning RippleBackgroundTransition | timomeh_react-native-material-bottom-navigation | train |
d04c94f520995819aab1c3e84707a92cea8d561a | diff --git a/session.go b/session.go
index <HASH>..<HASH> 100644
--- a/session.go
+++ b/session.go
@@ -260,9 +260,8 @@ func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
// returns routing key indexes and type info
func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
s.routingKeyInfoCache.mu.Lock()
- cacheKey := s.cfg.Keyspace + stmt
- entry, cached := s.routingKeyInfoCache.lru.Get(cacheKey)
+ entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
if cached {
// done accessing the cache
s.routingKeyInfoCache.mu.Unlock()
@@ -286,7 +285,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
inflight := new(inflightCachedEntry)
inflight.wg.Add(1)
defer inflight.wg.Done()
- s.routingKeyInfoCache.lru.Add(cacheKey, inflight)
+ s.routingKeyInfoCache.lru.Add(stmt, inflight)
s.routingKeyInfoCache.mu.Unlock()
var (
@@ -300,14 +299,14 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
// no connections
inflight.err = ErrNoConnections
// don't cache this error
- s.routingKeyInfoCache.Remove(cacheKey)
+ s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
prepared, inflight.err = conn.prepareStatement(stmt, nil)
if inflight.err != nil {
// don't cache this error
- s.routingKeyInfoCache.Remove(cacheKey)
+ s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
@@ -323,7 +322,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace)
if inflight.err != nil {
// don't cache this error
- s.routingKeyInfoCache.Remove(cacheKey)
+ s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
@@ -334,7 +333,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
// in the metadata code, or that the table was just dropped.
inflight.err = ErrNoMetadata
// don't cache this error
- s.routingKeyInfoCache.Remove(cacheKey)
+ s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
} | session: No need to include keyspace in routingKeyInfoCache key | gocql_gocql | train |
ed01bb4bf61f7a726882d6347f3ef6d5c3a73daf | diff --git a/lib/gir_ffi/builders/initializer_return_value_builder.rb b/lib/gir_ffi/builders/initializer_return_value_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/gir_ffi/builders/initializer_return_value_builder.rb
+++ b/lib/gir_ffi/builders/initializer_return_value_builder.rb
@@ -7,9 +7,6 @@ module GirFFI
class InitializerReturnValueBuilder < BaseReturnValueBuilder
def post_conversion
result = []
- if specialized_type_tag == :struct
- result << "#{capture_variable_name}.autorelease = true"
- end
result << "store_pointer(#{capture_variable_name})"
if specialized_type_tag == :struct
result << "@struct.owned = true"
diff --git a/test/gir_ffi/builders/initializer_builder_test.rb b/test/gir_ffi/builders/initializer_builder_test.rb
index <HASH>..<HASH> 100644
--- a/test/gir_ffi/builders/initializer_builder_test.rb
+++ b/test/gir_ffi/builders/initializer_builder_test.rb
@@ -43,7 +43,6 @@ describe GirFFI::Builders::InitializerBuilder do
code.must_equal <<-CODE.reset_indentation
def initialize
_v1 = GIMarshallingTests::Lib.gi_marshalling_tests_boxed_struct_new
- _v1.autorelease = true
store_pointer(_v1)
@struct.owned = true
end | No longer set autorelease in boxed type initializers | mvz_gir_ffi | train |
8f6ec779f0a206de1c447b48d545489fafa75d95 | diff --git a/ChangeLog.txt b/ChangeLog.txt
index <HASH>..<HASH> 100644
--- a/ChangeLog.txt
+++ b/ChangeLog.txt
@@ -1,4 +1,8 @@
+v0.2.0:
+
+ * add SHLock class for shared/exclusive (also known as read/write) locks.
+
v0.1.4:
* fix silly typo when loading libc (it's a miracle previous versions
diff --git a/threading2/__init__.py b/threading2/__init__.py
index <HASH>..<HASH> 100644
--- a/threading2/__init__.py
+++ b/threading2/__init__.py
@@ -13,6 +13,7 @@ The following extensions are currently implemented:
* ability to set (advisory) thread priority
* ability to set (advisory) CPU affinity at thread and process level
* thread groups for simultaneous management of multiple threads
+ * SHLock class for shared/exclusive (also known as read/write) locks
The following API niceties are also included:
@@ -65,7 +66,7 @@ except ImportError:
__all__ = ["active_count","activeCount","Condition","current_thread",
"currentThread","enumerate","Event","local","Lock","RLock",
"Semaphore","BoundedSemaphore","Thread","ThreadGroup","Timer",
- "setprofile","settrace","stack_size","group_local",
+ "SHLock","setprofile","settrace","stack_size","group_local",
"CPUSet","system_affinity","process_affinity"]
diff --git a/threading2/t2_base.py b/threading2/t2_base.py
index <HASH>..<HASH> 100644
--- a/threading2/t2_base.py
+++ b/threading2/t2_base.py
@@ -7,8 +7,8 @@ from threading import _RLock,_Event,_Condition,_Semaphore,_BoundedSemaphore, \
__all__ = ["active_count","activeCount","Condition","current_thread",
"currentThread","enumerate","Event","local","Lock","RLock",
- "Semaphore","BoundedSemaphore","Thread","Timer","setprofile",
- "settrace","stack_size","CPUSet","system_affinity",
+ "Semaphore","BoundedSemaphore","Thread","Timer","SHLock",
+ "setprofile","settrace","stack_size","CPUSet","system_affinity",
"process_affinity"]
@@ -390,6 +390,91 @@ class Thread(Thread):
return affinity
+class SHLock(object):
+ """Shareable lock class.
+
+ This functions just like an RLock except that you can also request a
+ "shared" lock mode. Shared locks can co-exist with other shared locks
+ but block exclusive locks. You might also know this as a read/write lock.
+
+ Currently attempting to upgrade or downgrade between shared and exclusive
+ locks will cause a deadlock. This restriction may go away in future.
+ """
+
+ _LockClass = Lock
+ _ConditionClass = Condition
+
+ def __init__(self):
+ self._lock = self._LockClass()
+ self._shared_cond = self._ConditionClass(self._lock)
+ self._exclusive_cond = self._ConditionClass(self._lock)
+ self._next_exclusive = None
+ self.is_shared = 0
+ self.is_exclusive = 0
+
+ def acquire(self,blocking=True,timeout=None,shared=False):
+ """Acquire the lock in shared or exclusive mode."""
+ with self._lock:
+ if shared:
+ self._acquire_shared(blocking,timeout)
+ else:
+ self._acquire_exclusive(blocking,timeout)
+
+ def release(self):
+ with self._lock:
+ if self.is_exclusive:
+ self.is_exclusive -= 1
+ if not self.is_exclusive:
+ self._shared_cond.notifyAll()
+ self._next_exclusive = None
+ self._exclusive_cond.notify()
+ elif self.is_shared:
+ self.is_shared -= 1
+ if not self.is_shared:
+ self._exclusive_cond.notify()
+ else:
+ raise RuntimeError("release() called on unheld lock")
+
+ def _acquire_shared(self,blocking=True,timeout=None):
+ while self.is_exclusive or self._next_exclusive is not None:
+ if not blocking:
+ return False
+ if timeout is not None:
+ starttime = _time()
+ if not self._shared_cond.wait(timeout=timeout):
+ return False
+ timeout -= time() - starttime
+ if timeout < 0:
+ return False
+ self.is_shared += 1
+
+ def _acquire_exclusive(self,blocking=True,timeout=None):
+ me = currentThread()
+ while self._next_exclusive not in (me,None):
+ if not blocking:
+ return False
+ if timeout is not None:
+ starttime = _time()
+ if not self._exclusive_cond.wait(timeout=timeout):
+ return False
+ timeout -= time() - starttime
+ if timeout < 0:
+ return False
+ self._next_exclusive = me
+ while self.is_shared:
+ if not blocking:
+ return False
+ if timeout is not None:
+ starttime = _time()
+ if not self._exclusive_cond.wait(timeout=timeout):
+ return False
+ timeout -= time() - starttime
+ if timeout < 0:
+ return False
+ self.is_exclusive += 1
+
+
+
# Utilities for handling CPU affinity
class CPUSet(set): | add SHLock class for shared/exclusive (aka read/write) locks | rfk_threading2 | train |
28b9ed7264444f25ac6cc886a2f18d6583adf185 | diff --git a/cake/libs/session/database_session.php b/cake/libs/session/database_session.php
index <HASH>..<HASH> 100644
--- a/cake/libs/session/database_session.php
+++ b/cake/libs/session/database_session.php
@@ -77,7 +77,7 @@ class DatabaseSession implements CakeSessionHandlerInterface {
* @access private
*/
public static function write($id, $data) {
- $expires = time() + Configure::read('Session.timeout') * Security::inactiveMins();
+ $expires = time() + (Configure::read('Session.timeout') * 60);
$model =& ClassRegistry::getObject('Session');
$return = $model->save(compact('id', 'data', 'expires'));
return $return;
diff --git a/cake/tests/cases/libs/session/cache_session.test.php b/cake/tests/cases/libs/session/cache_session.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/session/cache_session.test.php
+++ b/cake/tests/cases/libs/session/cache_session.test.php
@@ -35,8 +35,9 @@ class CacheSessionTest extends CakeTestCase {
'engine' => 'File',
'prefix' => 'session_test_'
));
- Configure::write('Session.handler.config', 'session_test');
self::$_sessionBackup = Configure::read('Session');
+
+ Configure::write('Session.handler.config', 'session_test');
}
/**
diff --git a/cake/tests/cases/libs/session/database_session.test.php b/cake/tests/cases/libs/session/database_session.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/session/database_session.test.php
+++ b/cake/tests/cases/libs/session/database_session.test.php
@@ -18,9 +18,107 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
+App::import('Core', 'Model');
App::import('Core', 'CakeSession');
App::import('Core', 'session/DatabaseSession');
+class SessionTestModel extends Model {
+ var $name = 'SessionTestModel';
+ var $useTable = 'sessions';
+}
+
+/**
+ * Database session test.
+ *
+ * @package cake.tests.cases.libs.session
+ */
class DatabaseSessionTest extends CakeTestCase {
-
+
+ protected static $_sessionBackup;
+
+/**
+ * fixtures
+ *
+ * @var string
+ */
+ public $fixtures = array('core.session');
+
+/**
+ * test case startup
+ *
+ * @return void
+ */
+ public static function setupBeforeClass() {
+ self::$_sessionBackup = Configure::read('Session');
+ ClassRegistry::init(array(
+ 'class' => 'SessionTestModel',
+ 'alias' => 'Session',
+ 'ds' => 'test_suite'
+ ));
+ Configure::write('Session.handler.model', 'SessionTestModel');
+ Configure::write('Session.timeout', 100);
+ }
+
+/**
+ * cleanup after test case.
+ *
+ * @return void
+ */
+ public static function teardownAfterClass() {
+ Configure::write('Session', self::$_sessionBackup);
+ }
+
+/**
+ * test opening the session
+ *
+ * @return void
+ */
+ function testOpen() {
+ $this->assertTrue(DatabaseSession::open());
+ }
+
+/**
+ * test write()
+ *
+ * @return void
+ */
+ function testWrite() {
+ $result = DatabaseSession::write('foo', 'Some value');
+ $expected = array(
+ 'Session' => array(
+ 'id' => 'foo',
+ 'data' => 'Some value',
+ 'expires' => time() + (Configure::read('Session.timeout') * 60)
+ )
+ );
+ $this->assertEquals($expected, $result);
+ }
+
+/**
+ * test read()
+ *
+ * @return void
+ */
+ function testRead() {
+ DatabaseSession::write('foo', 'Some value');
+
+ $result = DatabaseSession::read('foo');
+ $expected = 'Some value';
+ $this->assertEquals($expected, $result);
+
+ $result = DatabaseSession::read('made up value');
+ $this->assertFalse($result);
+ }
+
+/**
+ * test blowing up the session.
+ *
+ * @return void
+ */
+ function testDestroy() {
+ DatabaseSession::write('foo', 'Some value');
+
+ $this->assertTrue(DatabaseSession::destroy('foo'), 'Destroy failed');
+ $this->assertFalse(DatabaseSession::read('foo'), 'Value still present.');
+ }
}
\ No newline at end of file | Adding test cases for DatabaseSession and fixing a test case in CacheSession. | cakephp_cakephp | train |
02c724d2dbc43ef9e5feca42ae2e037853dfea0a | diff --git a/IPython/html/static/widgets/js/widget.js b/IPython/html/static/widgets/js/widget.js
index <HASH>..<HASH> 100644
--- a/IPython/html/static/widgets/js/widget.js
+++ b/IPython/html/static/widgets/js/widget.js
@@ -52,6 +52,7 @@ define(["widgets/js/manager",
_handle_comm_closed: function (msg) {
// Handle when a widget is closed.
this.trigger('comm:close');
+ this.comm.model.trigger('destroy', this.comm.model);
delete this.comm.model; // Delete ref so GC will collect widget model.
delete this.comm;
delete this.model_id; // Delete id from model so widget manager cleans up. | Destroy backbone model on comm:close | jupyter-widgets_ipywidgets | train |
0755196e81c8e3e3f6a77cf08a64fee22ef7f671 | diff --git a/lib/rufus/scheduler/cronline.rb b/lib/rufus/scheduler/cronline.rb
index <HASH>..<HASH> 100644
--- a/lib/rufus/scheduler/cronline.rb
+++ b/lib/rufus/scheduler/cronline.rb
@@ -292,7 +292,7 @@ class Rufus::Scheduler
secs = @seconds.sort
- return secs.last + 60 - time.sec if time.sec > secs.last
+ return secs.first + 60 - time.sec if time.sec > secs.last
secs.shift while secs.first < time.sec | fix for CronLine#next_second vs six-field line | jmettraux_rufus-scheduler | train |
5998e8feb74c6d7ecba97c83cafab94fb2a66737 | diff --git a/command/print_token.go b/command/print_token.go
index <HASH>..<HASH> 100644
--- a/command/print_token.go
+++ b/command/print_token.go
@@ -15,7 +15,7 @@ type PrintTokenCommand struct {
}
func (c *PrintTokenCommand) Synopsis() string {
- return "Prints the vault token currenty in use"
+ return "Prints the vault token currently in use"
}
func (c *PrintTokenCommand) Help() string { | Fix typo in print token synopsis text (#<I>) | hashicorp_vault | train |
b8c8e747407187185d718b8b148d18e9eca3a222 | diff --git a/cellpy/readers/instruments/pec.py b/cellpy/readers/instruments/pec.py
index <HASH>..<HASH> 100644
--- a/cellpy/readers/instruments/pec.py
+++ b/cellpy/readers/instruments/pec.py
@@ -56,14 +56,52 @@ class PECLoader(Loader):
get_headers_normal()
) # should consider to move this to the Loader class
- @staticmethod
- def _get_pec_units():
- pec_units = dict()
- pec_units["voltage"] = 0.001 # V
- pec_units["current"] = 0.001 # A
- pec_units["charge"] = 0.001 # Ah
- pec_units["mass"] = 0.001 # g
- pec_units["energy"] = 0.001 # Wh
+ #@staticmethod
+ #def _get_pec_units():
+ # pec_units = dict()
+ # pec_units["voltage"] = 0.001 # V
+ # pec_units["current"] = 0.001 # A
+ # pec_units["charge"] = 0.001 # Ah
+ # pec_units["mass"] = 0.001 # g
+ # pec_units["energy"] = 0.001 # Wh
+
+ # return pec_units
+
+ def _get_pec_units(self, filename): # Fetches units from a csv file
+ # Mapping prefixes to values
+ prefix = {
+ 'µ': 10 ** -6,
+ 'm': 10 ** -3,
+ '': 1
+ }
+
+ # Adding the non-variable units to the return value
+ pec_units = {
+ 'charge': 0.001, # Ah
+ 'mass': 0.001, # g
+ 'energy': 0.001 # Wh
+ }
+
+ # Searching values for variable units
+ header = ['Voltage (', 'Current (']
+
+ data = pd.read_csv(filename, skiprows=find_header_length(filename))
+
+ for item in data.keys():
+ for unit in header:
+ if unit in item:
+ x = item
+
+ # Isolating the prefix
+ for element in header:
+ x = x.lstrip(element)
+ x = x.rstrip('A)').rstrip('V)')
+
+ # Adding units to return value
+ if header.index(unit) == 0:
+ pec_units['voltage'] = prefix.get(x)
+ elif header.index(unit) == 1:
+ pec_units['current'] = prefix.get(x)
return pec_units | Added a method to find units in a csv file. | jepegit_cellpy | train |
f92203535590e99104e7e29bca2404348acb7971 | diff --git a/karma.conf.js b/karma.conf.js
index <HASH>..<HASH> 100644
--- a/karma.conf.js
+++ b/karma.conf.js
@@ -11,6 +11,7 @@ module.exports = function(config) {
let coverage = !Boolean(argv['disable-coverage']) && !quick;
let browsers = argv['browser'];
let logLevel = argv['log-level'] || argv['loglevel'] || (keepOpen ? 'info' : '');
+ let headless = !keepOpen;
let karmaConfig = {
@@ -83,7 +84,6 @@ module.exports = function(config) {
base: 'Chrome',
flags: [
'--no-sandbox',
- '--headless',
'--disable-gpu',
'--remote-debugging-port=9222',
'--remote-debugging-address=0.0.0.0',
@@ -277,5 +277,9 @@ module.exports = function(config) {
};
}
+ if (headless) {
+ karmaConfig.customLaunchers.xChrome.flags.push('--headless');
+ }
+
config.set(karmaConfig);
}; | Do not go into headless mode when keep-open passed | paypal_paypal-checkout-components | train |
40d6bc4825c5f1b88458b1082749a1cdd3bf2937 | diff --git a/lang/en_utf8/portfolio.php b/lang/en_utf8/portfolio.php
index <HASH>..<HASH> 100644
--- a/lang/en_utf8/portfolio.php
+++ b/lang/en_utf8/portfolio.php
@@ -93,6 +93,7 @@ $string['logs'] = 'Transfer logs';
$string['logsummary'] = 'Previous successful transfers';
$string['manageportfolios'] = 'Manage portfolios';
$string['manageyourportfolios'] = 'Manage your portfolios';
+$string['mimecheckfail'] = 'The portfolio plugin $a->plugin doesn\'t support that mimetype $a->mimetype';
$string['missingcallbackarg'] = 'Missing callback argument $a->arg for class $a->class';
$string['moderatefilesizethreshold'] = 'Moderate transfer filesize';
$string['moderatefilesizethresholddesc'] = 'Filesizes over this threshold will be considered to take a moderate amount of time to transfer';
@@ -103,7 +104,7 @@ $string['mustsetcallbackoptions'] = 'You must set the callback options either in
$string['noavailableplugins'] = 'Sorry, but there are no available portfolios for you to export to';
$string['nocallbackfile'] = 'Something in the module you\'re trying to export from is broken - couldn\'t find a required file ($a)';
$string['nocallbackclass'] = 'Could not find the callback class to use ($a)';
-$string['nocommonformats'] = 'No common formats between any available portfolio plugin and the calling location $a';
+$string['nocommonformats'] = 'No common formats between any available portfolio plugin and the calling location $a->location (caller supported $a->formats)';
$string['noclassbeforeformats'] = 'You must set the callback class before calling set_formats in portfolio_button';
$string['noinstanceyet'] = 'Not yet selected';
$string['nologs'] = 'There are no logs to display!';
diff --git a/lib/portfolio/exporter.php b/lib/portfolio/exporter.php
index <HASH>..<HASH> 100644
--- a/lib/portfolio/exporter.php
+++ b/lib/portfolio/exporter.php
@@ -291,7 +291,7 @@ class portfolio_exporter {
$expectedtime = $this->instance->expected_time($this->caller->expected_time());
if (count($formats) == 0) {
// something went wrong, we should not have gotten this far.
- throw new portfolio_export_exception($this, 'nocommonformats', 'portfolio', null, get_class($this->caller));
+ throw new portfolio_export_exception($this, 'nocommonformats', 'portfolio', null, array('location' => get_class($this->caller), 'formats' => implode(',', $formats)));
}
// even if neither plugin or caller wants any config, we have to let the user choose their format, and decide to wait.
if ($pluginobj || $callerobj || count($formats) > 1 || ($expectedtime != PORTFOLIO_TIME_LOW && $expectedtime != PORTFOLIO_TIME_FORCEQUEUE)) { | portfolio NOBUG added some more helpful debugging information about common formats | moodle_moodle | train |
213a9c8988ee5a78ff23d1ad14e0b18386baff4c | diff --git a/spec/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolverSpec.php b/spec/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolverSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolverSpec.php
+++ b/spec/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolverSpec.php
@@ -59,6 +59,13 @@ class ServiceArgumentResolverSpec extends ObjectBehavior
);
}
+ function it_does_not_escape_other_at_signs_in_arguments(ReflectionClass $reflectionClass)
+ {
+ $this->resolveArguments($reflectionClass, array('service' => 'service@@'))->shouldReturn(
+ array('service' => 'service@@')
+ );
+ }
+
function it_unescapes_string_arguments_with_escaped_percentages(ReflectionClass $reflectionClass)
{
$this->resolveArguments($reflectionClass, array('parameter' => 'percent%%percent'))->shouldReturn(
diff --git a/src/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolver.php b/src/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolver.php
index <HASH>..<HASH> 100644
--- a/src/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolver.php
+++ b/src/Behat/Symfony2Extension/Context/Argument/ServiceArgumentResolver.php
@@ -135,6 +135,8 @@ final class ServiceArgumentResolver implements ArgumentResolver
*/
private function escape($argument)
{
- return str_replace(array('@@', '%%'), array('@', '%'), $argument);
+ $argument = preg_replace('/^@/', '', $argument);
+
+ return str_replace('%%', '%', $argument);
}
} | Only escape service names at start of string | Behat_Symfony2Extension | train |
5a014aada69acb9fc5158e75a6a229eff4c71fc4 | diff --git a/src/runtime/runtime.js b/src/runtime/runtime.js
index <HASH>..<HASH> 100644
--- a/src/runtime/runtime.js
+++ b/src/runtime/runtime.js
@@ -340,12 +340,6 @@
return $Object(x);
}
- function assertObject(x) {
- if (!isObject(x))
- throw $TypeError(x + ' is not an Object');
- return x;
- }
-
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-checkobjectcoercible
function checkObjectCoercible(argument) {
if (argument == null) {
@@ -366,7 +360,6 @@
setupGlobals(global);
global.$traceurRuntime = {
- assertObject: assertObject,
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject, | Remove runtime remove assertObject
This could not be included in the last commit due to self hostin
issues. It required a npm push before it was safe to remove. | google_traceur-compiler | train |
b5f62ba95a8bce41e85b2515b9d6859a8b1500dd | diff --git a/spec/ClientSpec.php b/spec/ClientSpec.php
index <HASH>..<HASH> 100644
--- a/spec/ClientSpec.php
+++ b/spec/ClientSpec.php
@@ -34,8 +34,7 @@ class ClientSpec extends ObjectBehavior
$this->httpClient = $httpClient;
- $authenticator->createToken( Argument::type('string') )->willReturn( self::TEST_JWT_TOKEN );
- $authenticator->createToken( Argument::type('string'), Argument::type('string') )->willReturn( self::TEST_JWT_TOKEN );
+ $authenticator->createToken()->willReturn( self::TEST_JWT_TOKEN );
$options = [
'baseUrl' => self::BASE_URL,
diff --git a/src/Authentication/JWTAuthenticationInterface.php b/src/Authentication/JWTAuthenticationInterface.php
index <HASH>..<HASH> 100644
--- a/src/Authentication/JWTAuthenticationInterface.php
+++ b/src/Authentication/JWTAuthenticationInterface.php
@@ -12,11 +12,8 @@ interface JWTAuthenticationInterface {
/**
* Generate a JSON Web Token.
*
- * @param string $request The pre-encoded request
- * @param string|null $payload The pre-encoded payload
- *
* @return string The generated token
*/
- public function createToken( $request, $payload = null );
+ public function createToken();
}
\ No newline at end of file
diff --git a/src/Authentication/JsonWebToken.php b/src/Authentication/JsonWebToken.php
index <HASH>..<HASH> 100644
--- a/src/Authentication/JsonWebToken.php
+++ b/src/Authentication/JsonWebToken.php
@@ -40,14 +40,11 @@ class JsonWebToken implements JWTAuthenticationInterface {
/**
* Generate a JSON Web Token.
*
- * @param string $request The pre-encoded request
- * @param string|null $payload The pre-encoded payload
- *
* @return string The generated token
*/
- public function createToken( $request, $payload = null ){
+ public function createToken(){
- $claims = $this->generateClaims( $request, $payload );
+ $claims = $this->generateClaims();
return JWT::encode( $claims, $this->key );
@@ -56,40 +53,17 @@ class JsonWebToken implements JWTAuthenticationInterface {
/**
* Prepare the required Notify claims.
*
- * @param $request
- * @param $payload
- *
* @return array
*/
- protected function generateClaims( $request, $payload ){
+ protected function generateClaims(){
$claims = array(
"iss" => $this->serviceId,
"iat" => time(),
- "req" => $this->generateSignature( $request ),
);
- if( is_string($payload) ){
- $claims['pay'] = $this->generateSignature( $payload );
- }
-
return $claims;
}
- /**
- * Return the signature for the passed data.
- *
- * @param string $data
- *
- * @return string
- */
- protected function generateSignature( $data ){
-
- return base64_encode(
- hash_hmac( 'sha256', $data, $this->key, true)
- );
-
- }
-
}
\ No newline at end of file
diff --git a/src/Client.php b/src/Client.php
index <HASH>..<HASH> 100644
--- a/src/Client.php
+++ b/src/Client.php
@@ -153,7 +153,7 @@ class Client {
* Send an SMS message.
*
* @param string $to
- * @param int $template
+ * @param string $template
* @param array $personalisation
*
* @return array
@@ -171,7 +171,7 @@ class Client {
* Send an Email message.
*
* @param string $to
- * @param int $template
+ * @param string $template
* @param array $personalisation
*
* @return array
@@ -239,7 +239,7 @@ class Client {
* Generates the payload expected by the API.
*
* @param string $to
- * @param int $template
+ * @param string $template
* @param array $personalisation
*
* @return array
@@ -262,14 +262,12 @@ class Client {
/**
* Generates the standard set of HTTP headers expected by the API.
*
- * @param string $token The JSON Web Token
- *
* @return array
*/
- private function buildHeaders( $token ){
+ private function buildHeaders(){
return [
- 'Authorization' => 'Bearer '.$token,
+ 'Authorization' => 'Bearer '.$this->getAuthenticator()->createToken(),
'Accept' => 'application/json',
'Content-type' => 'application/json',
'User-agent' => 'NOTIFY-API-PHP-CLIENT/'.self::VERSION
@@ -291,10 +289,6 @@ class Client {
*/
private function httpGet( $path, array $query = array() ){
- $token = $this->getAuthenticator()->createToken( "GET {$path}" );
-
- //---
-
$url = new Uri( $this->baseUrl . $path );
foreach( $query as $name => $value ){
@@ -306,7 +300,7 @@ class Client {
$request = new Request(
'GET',
$url,
- $this->buildHeaders( $token )
+ $this->buildHeaders()
);
try {
@@ -340,20 +334,14 @@ class Client {
* @throw Exception\NotifyException | Exception\ApiException | Exception\UnexpectedValueException
*/
private function httpPost( $path, Array $payload ){
-
- $payload = json_encode( $payload );
-
- $token = $this->getAuthenticator()->createToken( "POST {$path}", $payload );
-
- //---
-
+
$url = new Uri( $this->baseUrl . $path );
$request = new Request(
'POST',
$url,
- $this->buildHeaders( $token ),
- $payload
+ $this->buildHeaders(),
+ json_encode( $payload )
);
try { | Dropped support for 'req' & 'pay' claims in JWT | alphagov_notifications-php-client | train |
e853fc73e85d41fa8ecabae418cfd45fa3b2a97f | diff --git a/lib/symlink.js b/lib/symlink.js
index <HASH>..<HASH> 100644
--- a/lib/symlink.js
+++ b/lib/symlink.js
@@ -20,7 +20,7 @@ const symlinkSync = (symlinkValue, path) => {
fs.symlinkSync(symlinkValue, path);
} catch (err) {
if (err.code === "ENOENT") {
- // Parent directories don't exist. Just create them and rety.
+ // Parent directories don't exist. Just create them and retry.
dir.createSync(pathUtil.dirname(path));
fs.symlinkSync(symlinkValue, path);
} else {
@@ -39,7 +39,7 @@ const symlinkAsync = (symlinkValue, path) => {
.then(resolve)
.catch(err => {
if (err.code === "ENOENT") {
- // Parent directories don't exist. Just create them and rety.
+ // Parent directories don't exist. Just create them and retry.
dir
.createAsync(pathUtil.dirname(path))
.then(() => { | Fix typo in `lib/symlink.js` | szwacz_fs-jetpack | train |
76bd3f17f6744f4758d5b1e82ffdd89267fd543c | diff --git a/src/ro/nextreports/engine/querybuilder/sql/dialect/MSSQLDialect.java b/src/ro/nextreports/engine/querybuilder/sql/dialect/MSSQLDialect.java
index <HASH>..<HASH> 100644
--- a/src/ro/nextreports/engine/querybuilder/sql/dialect/MSSQLDialect.java
+++ b/src/ro/nextreports/engine/querybuilder/sql/dialect/MSSQLDialect.java
@@ -61,6 +61,7 @@ public class MSSQLDialect extends AbstractDialect {
registerColumnType("smallmoney", Types.DECIMAL);
registerColumnType("blob", Types.BLOB);
registerColumnType("varbinary", Types.BLOB);
+ registerColumnType("image", Types.BLOB);
registerColumnType("clob", Types.CLOB);
} | map image type to sql blob | nextreports_nextreports-engine | train |
a17729321f4c4af1cd8b99f611f596a41f093f1b | diff --git a/vlcp/event/core.py b/vlcp/event/core.py
index <HASH>..<HASH> 100644
--- a/vlcp/event/core.py
+++ b/vlcp/event/core.py
@@ -206,7 +206,7 @@ class Scheduler(object):
self.registerIndex = {}
self.daemons = set()
self.processevents = processevents
- self.logger.setLevel(WARNING)
+ #self.logger.setLevel(WARNING)
self.debugging = False
def register(self, matchers, runnable):
'''
diff --git a/vlcp/server/module.py b/vlcp/server/module.py
index <HASH>..<HASH> 100644
--- a/vlcp/server/module.py
+++ b/vlcp/server/module.py
@@ -382,8 +382,13 @@ class ModuleLoader(RoutineContainer):
except AttributeError:
pass
if p is None and autoimport:
- p = __import__(package, fromlist=(classname,))
- module = getattr(p, classname)
+ try:
+ p = __import__(package, fromlist=(classname,))
+ module = getattr(p, classname)
+ except KeyError:
+ pass
+ except ImportError:
+ pass
return (p, module)
def loadByPath(self, path):
p, module = self._findModule(path, True)
diff --git a/vlcp/server/server.py b/vlcp/server/server.py
index <HASH>..<HASH> 100644
--- a/vlcp/server/server.py
+++ b/vlcp/server/server.py
@@ -57,7 +57,7 @@ class Server(Configurable):
defaultQueueClass=CBQueue.AutoClassQueue.initHelper('_classname0'), defaultQueuePriority = 400)
if self.debugging:
self.scheduler.debugging = True
- self.scheduler.logger.setLevel(logging.DEBUG)
+ logging.getLogger().setLevel(logging.DEBUG)
self.scheduler.queue.addSubQueue(self.pollwritepriority, PollEvent.createMatcher(category=PollEvent.WRITE_READY), 'write', None, None, CBQueue.AutoClassQueue.initHelper('fileno'))
self.scheduler.queue.addSubQueue(self.pollreadpriority, PollEvent.createMatcher(category=PollEvent.READ_READY), 'read', None, None, CBQueue.AutoClassQueue.initHelper('fileno'))
self.scheduler.queue.addSubQueue(self.pollerrorpriority, PollEvent.createMatcher(category=PollEvent.ERROR), 'error')
@@ -130,10 +130,11 @@ def main(configpath = None, startup = None, daemon = False, pidfile = None):
if uid is None:
import pwd
user = manager.get('daemon.user')
- user_pw = pwd.getpwnam(user)
- uid = user_pw.pw_uid
- if gid is None:
- gid = user_pw.pw_gid
+ if user is not None:
+ user_pw = pwd.getpwnam(user)
+ uid = user_pw.pw_uid
+ if gid is None:
+ gid = user_pw.pw_gid
if uid is not None and gid is None:
import pwd
gid = pwd.getpwuid(uid).pw_gid | Small improvement on logging and module load | hubo1016_vlcp | train |
a4abb2397fbe3ec7a6189f69f31f4c87bd5faf78 | diff --git a/img_proof/ipa_cloud.py b/img_proof/ipa_cloud.py
index <HASH>..<HASH> 100644
--- a/img_proof/ipa_cloud.py
+++ b/img_proof/ipa_cloud.py
@@ -349,7 +349,7 @@ class IpaCloud(object):
if self.early_exit:
options.append('-x')
- args = '-v {} --ssh-config={} --hosts={} {}'.format(
+ args = '-v -s {} --ssh-config={} --hosts={} {}'.format(
' '.join(options),
ssh_config,
self.instance_ip,
@@ -369,7 +369,11 @@ class IpaCloud(object):
while num_retries < self.retry_count:
plugin = Report()
- result = pytest.main(cmds, plugins=[plugin])
+
+ try:
+ result = pytest.main(cmds, plugins=[plugin])
+ except Exception:
+ result = 2
if result != 0:
num_retries += 1 | Catch unhandled exceptions from pytest.
- And retry the given test.
- Also, disable all pytest stdout capturing with -s option. This
seems to clash with img-proof which already redirects stdout to a
log file. <URL> | SUSE-Enceladus_ipa | train |
1436788bacffbc765db7d4b8c6a33de4ab10bf9e | diff --git a/benchmark.js b/benchmark.js
index <HASH>..<HASH> 100644
--- a/benchmark.js
+++ b/benchmark.js
@@ -46,7 +46,7 @@ var funcs = [
// Insert a new user
function(done) {
- var email = RECORDS + inserts + '-' + email
+ var email = RECORDS + inserts + '-' + baseEmail
dbi.addUser(email, "password"+ops, {data:ops}, function(err) { if (err) errs++; inserts++; ops++; done()}, true)
},
]
@@ -103,7 +103,7 @@ function startBench() {
nreads / 10, nchangePasswords / 10, ninserts / 10, nmodifies / 10 , nops / 10, nerrs / 10)
}, 10000)
- var OPS = 1000000
+ var OPS = 100000000
var i = 0
async.whilst(
function() { return i < OPS }, | s/email/baseEmail
increase # ops | FrozenRidge_level-userdb | train |
b1f577724e3f06efd31bdb61b7e7746cdf0d92d7 | diff --git a/tools/webpack.babel.js b/tools/webpack.babel.js
index <HASH>..<HASH> 100644
--- a/tools/webpack.babel.js
+++ b/tools/webpack.babel.js
@@ -8,7 +8,7 @@ var config = require('../config/project'),
configWebpack = config.webpack;
var Clean = require('clean-webpack-plugin'),
- ExtractTextPlugin = require("extract-text-webpack-plugin-steamer");
+ ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpackConfig = {
entry: {
@@ -76,4 +76,4 @@ var webpackConfig = {
// devtool: "#inline-source-map",
};
-module.exports = webpackConfig;
\ No newline at end of file
+module.exports = webpackConfig; | update extract-text-webpack-plugin
update extract-text-webpack-plugin | steamerjs_steamer-react-component | train |
aa810745501782ed29661a659eed41ae4a7aed6d | diff --git a/pylon/pyreto/smart_market.py b/pylon/pyreto/smart_market.py
index <HASH>..<HASH> 100644
--- a/pylon/pyreto/smart_market.py
+++ b/pylon/pyreto/smart_market.py
@@ -25,7 +25,7 @@
import time
import logging
-from pylon import UDOPF
+from pylon import UDOPF, DCOPF
#------------------------------------------------------------------------------
# Logging:
@@ -134,7 +134,7 @@ class SmartMarket(object):
# self.bids = [bid for vl in vloads for bid in vl.get_bids()]
- def clear(self):
+ def clear_offers_and_bids(self):
""" Computes cleared offers and bids.
"""
t0 = time.time()
@@ -327,7 +327,8 @@ class SmartMarket(object):
def _run_opf(self, case):
""" Solves the optimisation problem.
"""
- routine = self.routine = UDOPF(dc=self.loc_adjust == "dc")
+# routine = self.routine = UDOPF(dc=self.loc_adjust == "dc")
+ routine = self.routine = DCOPF(show_progress=False)
success = self.success = routine(case)
return success
@@ -387,10 +388,9 @@ class SmartMarket(object):
# Clear offer/bid quantities and prices.
- Auction(case, offers, bids, guarantee_offer_price,
- guarantee_bid_price, self.limits).clear(self.auction_type)
-
-# prices = [of.quantity * of.price for of in offers]
+ Auction(case, offers, bids,
+ guarantee_offer_price, guarantee_bid_price,
+ self.limits).clear_offers_and_bids(self.auction_type)
else:
logger.error("Non-convergent UOPF.")
@@ -404,8 +404,6 @@ class SmartMarket(object):
for offbid in offers + bids:
offbid.cleared_quantity = offbid.cleared_price = 0.0
-# cleared_offers, cleared_bids = offers, bids
-
def _compute_costs(self, case, offers, bids):
""" Returns a map of generators to their dispatch info, which details
@@ -487,7 +485,7 @@ class Auction(object):
self.limits = limits
- def clear(self, auction_type):
+ def clear_offers_and_bids(self, auction_type):
""" Clears a set of bids and offers.
"""
offers, bids = self.offers, self.bids
diff --git a/pylon/pyreto/test/auction_test.py b/pylon/pyreto/test/auction_test.py
index <HASH>..<HASH> 100644
--- a/pylon/pyreto/test/auction_test.py
+++ b/pylon/pyreto/test/auction_test.py
@@ -134,7 +134,7 @@ class MarketTestCase(unittest.TestCase):
mkt = SmartMarket(self.case, self.offers, self.bids,
loc_adjust='dc', auction_type="first price", price_cap=100.0)
- settlement = mkt.clear()
+ settlement = mkt.clear_offers_and_bids()
# for dispatch in settlement:
# print dispatch.quantity, dispatch.price | Adding option to use plain DCOPF. | rwl_pylon | train |
8396f2736a8bdc69a15270b4ff1d6412e5b3277a | diff --git a/lib/writer/xelatex.js b/lib/writer/xelatex.js
index <HASH>..<HASH> 100644
--- a/lib/writer/xelatex.js
+++ b/lib/writer/xelatex.js
@@ -209,6 +209,7 @@ var header =
'\n' +
'% select widely available fonts\n' +
'\\setmainfont{Georgia}\n' +
+ '\\setmonofont{Courier New}\n' +
'\n' +
'% set paragraph margins\n' +
'\\setlength{\\parindent}{0pt}\n' + | [xelatex] Set Courier New as monospaced font. | sheremetyev_texts.js | train |
e7c592610e18b73df0ace756dde764b4c62d4bcf | diff --git a/src/main/php/ehough/shortstop/impl/exec/command/CurlCommand.php b/src/main/php/ehough/shortstop/impl/exec/command/CurlCommand.php
index <HASH>..<HASH> 100644
--- a/src/main/php/ehough/shortstop/impl/exec/command/CurlCommand.php
+++ b/src/main/php/ehough/shortstop/impl/exec/command/CurlCommand.php
@@ -180,14 +180,14 @@ class ehough_shortstop_impl_exec_command_CurlCommand extends ehough_shortstop_im
{
curl_setopt_array($this->_handle, array(
- CURLOPT_CONNECTTIMEOUT => 5,
+ CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_HEADER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_MAXREDIRS => 5,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true,
- CURLOPT_TIMEOUT => 5,
+ CURLOPT_TIMEOUT => 15,
CURLOPT_URL => $request->getUrl()->toString(),
CURLOPT_USERAGENT => $request->getHeaderValue(ehough_shortstop_api_HttpRequest::HTTP_HEADER_USER_AGENT),
diff --git a/src/main/php/ehough/shortstop/impl/exec/command/ExtCommand.php b/src/main/php/ehough/shortstop/impl/exec/command/ExtCommand.php
index <HASH>..<HASH> 100644
--- a/src/main/php/ehough/shortstop/impl/exec/command/ExtCommand.php
+++ b/src/main/php/ehough/shortstop/impl/exec/command/ExtCommand.php
@@ -143,8 +143,8 @@ class ehough_shortstop_impl_exec_command_ExtCommand extends ehough_shortstop_imp
private static function _buildOptionsArray(ehough_shortstop_api_HttpRequest $request)
{
return array(
- self::$_option_timeout => 5,
- self::$_option_connecttimeout => 5,
+ self::$_option_timeout => 15,
+ self::$_option_connecttimeout => 15,
self::$_option_redirect => 5,
self::$_option_useragent => $request->getHeaderValue(ehough_shortstop_api_HttpRequest::HTTP_HEADER_USER_AGENT),
self::$_option_headers => $request->getAllHeaders()
diff --git a/src/main/php/ehough/shortstop/impl/exec/command/FopenCommand.php b/src/main/php/ehough/shortstop/impl/exec/command/FopenCommand.php
index <HASH>..<HASH> 100644
--- a/src/main/php/ehough/shortstop/impl/exec/command/FopenCommand.php
+++ b/src/main/php/ehough/shortstop/impl/exec/command/FopenCommand.php
@@ -68,7 +68,7 @@ class ehough_shortstop_impl_exec_command_FopenCommand extends ehough_shortstop_i
$this->_logger->debug('Successfully opened stream');
}
- stream_set_timeout($this->_handle, 5);
+ stream_set_timeout($this->_handle, 15);
$rawContent = '';
diff --git a/src/main/php/ehough/shortstop/impl/exec/command/FsockOpenCommand.php b/src/main/php/ehough/shortstop/impl/exec/command/FsockOpenCommand.php
index <HASH>..<HASH> 100644
--- a/src/main/php/ehough/shortstop/impl/exec/command/FsockOpenCommand.php
+++ b/src/main/php/ehough/shortstop/impl/exec/command/FsockOpenCommand.php
@@ -62,7 +62,7 @@ class ehough_shortstop_impl_exec_command_FsockOpenCommand extends ehough_shortst
$this->_logger->debug('Now calling fsockopen()...');
}
- $this->_handle = @fsockopen("$host:$port", $port, $iError, $strError, 5);
+ $this->_handle = @fsockopen("$host:$port", $port, $iError, $strError, 15);
if (false === $this->_handle) {
@@ -76,7 +76,7 @@ class ehough_shortstop_impl_exec_command_FsockOpenCommand extends ehough_shortst
fwrite($this->_handle, self::_buildHeaderString($request));
- stream_set_timeout($this->_handle, 5);
+ stream_set_timeout($this->_handle, 15);
if ($isDebugging) {
diff --git a/src/main/php/ehough/shortstop/impl/exec/command/StreamsCommand.php b/src/main/php/ehough/shortstop/impl/exec/command/StreamsCommand.php
index <HASH>..<HASH> 100644
--- a/src/main/php/ehough/shortstop/impl/exec/command/StreamsCommand.php
+++ b/src/main/php/ehough/shortstop/impl/exec/command/StreamsCommand.php
@@ -112,8 +112,8 @@ class ehough_shortstop_impl_exec_command_StreamsCommand extends ehough_shortstop
$this->_logger->debug(sprintf('Successfully used fopen() to get a handle to %s', $request->getUrl()));
}
- /* set the timeout to 5 seconds */
- stream_set_timeout($handle, 5);
+ /* set the timeout to 15 seconds */
+ stream_set_timeout($handle, 15);
/* read stream contents */
if ($isDebugging) { | Bumping default timeouts to <I> seconds | ehough_shortstop | train |
ec3fff5a6d928bf1fe6fb5de6e28509d69155509 | diff --git a/lib/reform/form/active_model.rb b/lib/reform/form/active_model.rb
index <HASH>..<HASH> 100644
--- a/lib/reform/form/active_model.rb
+++ b/lib/reform/form/active_model.rb
@@ -55,15 +55,16 @@ module Reform::Form::ActiveModel
end
end
+
module ClassMethods
- def model_options
- return @model_options unless superclass.respond_to?(:model_options) and value = superclass.model_options
- @model_options ||= value.clone
+ # this module is only meant to extend (not include). # DISCUSS: is this a sustainable concept?
+ def self.extended(base)
+ base.class_eval do
+ extend Hooks::InheritableAttribute
+ inheritable_attr :model_options
+ end
end
- def model_options=(value)
- @model_options = value
- end
# Set a model name for this form if the infered is wrong.
#
@@ -74,8 +75,8 @@ module Reform::Form::ActiveModel
end
def model_name
- if self.model_options
- form_name = self.model_options.first.to_s.camelize
+ if model_options
+ form_name = model_options.first.to_s.camelize
else
form_name = name.sub(/Form$/, "")
end
diff --git a/lib/reform/form/composition.rb b/lib/reform/form/composition.rb
index <HASH>..<HASH> 100644
--- a/lib/reform/form/composition.rb
+++ b/lib/reform/form/composition.rb
@@ -5,12 +5,13 @@ class Reform::Form
module Composition
def self.included(base)
base.class_eval do
+ extend Reform::Form::ActiveModel::ClassMethods # ::model.
extend ClassMethods
end
end
module ClassMethods
- include Reform::Form::ActiveModel::ClassMethods # ::model.
+ #include Reform::Form::ActiveModel::ClassMethods # ::model.
def model_class # DISCUSS: needed?
rpr = representer_class | use inheritable_attr to implement ActiveModel::model_options. slightly changed F::ActiveModel::ClassMethods, this is an extend-only module now, so if you used to include it, things might break. | trailblazer_reform | train |
68d508e8492ddd1ab48eb2dad83c5c90fe4b07cd | diff --git a/src/Entry.php b/src/Entry.php
index <HASH>..<HASH> 100644
--- a/src/Entry.php
+++ b/src/Entry.php
@@ -66,7 +66,7 @@ class Entry implements EntryInterface
return $this->resolvedLinks[$key];
}
- if (is_array($this->fields[$key]) && count($this->fields[$key]) > 0 && array_values($this->fields[$key])[0] instanceof Link) {
+ if (is_array($this->fields[$key]) && count($this->fields[$key]) > 0 && $this->containsLink($this->fields[$key])) {
if (!isset($this->resolvedLinks[$key])) {
$this->resolvedLinks[$key] = array_filter(array_map(function ($link) {
try {
@@ -131,4 +131,19 @@ class Entry implements EntryInterface
return $this;
}
+
+ /**
+ * @param array $resources
+ * @return bool
+ */
+ private function containsLink(array $resources)
+ {
+ foreach ($resources as $resource) {
+ if ($resource instanceof Link) {
+ return true;
+ }
+ }
+
+ return false;
+ }
} | make entry resolve links if there are any links in field data (i.e. don't just check the first one) | usemarkup_contentful | train |
c28595228f3ea70b1817269649bbf763b7e7461f | diff --git a/src/com/google/javascript/jscomp/serialization/JSTypeSerializer.java b/src/com/google/javascript/jscomp/serialization/JSTypeSerializer.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/serialization/JSTypeSerializer.java
+++ b/src/com/google/javascript/jscomp/serialization/JSTypeSerializer.java
@@ -45,6 +45,8 @@ import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Set;
import javax.annotation.Nullable;
final class JSTypeSerializer {
@@ -173,14 +175,10 @@ final class JSTypeSerializer {
}
if (type.isUnionType()) {
- ImmutableSet<SimplifiedType> alternates =
+ return SimplifiedType.ofUnion(
type.toMaybeUnionType().getAlternates().stream()
.map(this::simplifyTypeInternal)
- .collect(toImmutableSet());
- // Simplification may collapse some members of the union
- return alternates.size() > 1
- ? SimplifiedType.ofUnion(alternates)
- : Iterables.getOnlyElement(alternates);
+ .collect(toImmutableSet()));
}
if (type.isFunctionType() && type.toMaybeFunctionType().getCanonicalRepresentation() != null) {
@@ -516,9 +514,29 @@ final class JSTypeSerializer {
return AutoOneOf_JSTypeSerializer_SimplifiedType.single(t);
}
- private static SimplifiedType ofUnion(ImmutableSet<SimplifiedType> union) {
- checkArgument(union.size() > 1, "Union %s must have > 1 element", union);
- return AutoOneOf_JSTypeSerializer_SimplifiedType.union(union);
+ private static SimplifiedType ofUnion(Set<SimplifiedType> dirtyAlts) {
+ if (dirtyAlts.size() == 1) {
+ return Iterables.getOnlyElement(dirtyAlts);
+ }
+
+ LinkedHashSet<SimplifiedType> cleanAlts = new LinkedHashSet<>();
+ for (SimplifiedType s : dirtyAlts) {
+ switch (s.getKind()) {
+ case SINGLE:
+ cleanAlts.add(s);
+ break;
+ case UNION:
+ cleanAlts.addAll(s.union());
+ break;
+ }
+ }
+
+ if (cleanAlts.size() == 1) {
+ // Cleaning may collapse some members of the union
+ return Iterables.getOnlyElement(cleanAlts);
+ }
+
+ return AutoOneOf_JSTypeSerializer_SimplifiedType.union(ImmutableSet.copyOf(cleanAlts));
}
}
diff --git a/test/com/google/javascript/jscomp/serialization/SerializeTypedAstPassTest.java b/test/com/google/javascript/jscomp/serialization/SerializeTypedAstPassTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/serialization/SerializeTypedAstPassTest.java
+++ b/test/com/google/javascript/jscomp/serialization/SerializeTypedAstPassTest.java
@@ -185,6 +185,40 @@ public final class SerializeTypedAstPassTest extends CompilerTestCase {
}
@Test
+ public void testUnion_proxyLikeTypes_dontPreventUnionCollapsing() {
+ List<TypeProto> typePool =
+ compileToTypes(
+ lines(
+ "/** @enum {boolean|number} */", //
+ "const Foo = {};",
+ "",
+ "let /** !Foo|string|number */ x;"));
+
+ List<UnionTypeProto> unionsContainingUnions =
+ typePool.stream()
+ .filter(TypeProto::hasUnion)
+ .map(TypeProto::getUnion)
+ .filter(
+ (u) ->
+ u.getUnionMemberList().stream()
+ .filter((p) -> !isAxiomatic(p))
+ .anyMatch((e) -> typePool.get(trimOffset(e)).hasUnion()))
+ .collect(toImmutableList());
+ assertThat(unionsContainingUnions).isEmpty();
+
+ assertThat(typePool)
+ .contains(
+ TypeProto.newBuilder()
+ .setUnion(
+ UnionTypeProto.newBuilder()
+ .addUnionMember(pointerForType(PrimitiveType.BOOLEAN_TYPE))
+ .addUnionMember(pointerForType(PrimitiveType.NUMBER_TYPE))
+ .addUnionMember(pointerForType(PrimitiveType.STRING_TYPE))
+ .build())
+ .build());
+ }
+
+ @Test
public void testSerializedInstanceTypeHasClassName() {
assertThat(compileToTypes("/** @constructor */ function Foo() {} new Foo;"))
.ignoringFieldDescriptors(BRITTLE_TYPE_FIELDS) | Fix an issue with nested unions in JSTypeSerializer.
PiperOrigin-RevId: <I> | google_closure-compiler | train |
8b700648d19cf29883bc94e05dea7756d049a609 | diff --git a/lib/perobs/Store.rb b/lib/perobs/Store.rb
index <HASH>..<HASH> 100644
--- a/lib/perobs/Store.rb
+++ b/lib/perobs/Store.rb
@@ -244,6 +244,7 @@ module PEROBS
# from the back-end storage. The garbage collector is not invoked
# automatically. Depending on your usage pattern, you need to call this
# method periodically.
+ # @return [Fixnum] The number of collected objects
def gc
sync
mark
@@ -285,48 +286,24 @@ module PEROBS
# unreadable object is found, the reference will simply be deleted.
# @param repair [TrueClass/FalseClass] true if a repair attempt should be
# made.
+ # @return [Fixnum] The number of references to bad objects found.
def check(repair = true)
- # FIXME: This does not work with cyclic references!
+ # All objects must have in-db version.
+ sync
# Run basic consistency checks first.
@db.check_db(repair)
+ # We will use the mark to mark all objects that we have checked already.
+ # Before we start, we need to clear all marks.
@db.clear_marks
- # A buffer to hold a working set of object IDs.
- stack = []
- # First we check the top-level objects. They are only added to the
- # working set if they are OK.
+
+ errors = 0
@root_objects.each do |name, id|
- unless @db.check(id, repair)
- stack << id
- end
- end
- if repair
- # Delete any top-level object that is defective.
- stack.each { |id| @root_objects.delete(id) }
- # The remaining top-level objects are the initial working set.
- stack = @root_objects.values
- else
- # The initial working set must only be OK objects.
- stack = @root_objects.values - stack
+ errors += check_object(id, repair)
end
- stack.each { |id| @db.mark(id) }
+ @root_objects.delete_if { |name, id| [email protected](id, false) }
- while !stack.empty?
- id = stack.pop
- (obj = object_by_id(id))._referenced_object_ids.each do |id|
- # Add all found references that have passed the check to the working
- # list for the next iterations.
- if @db.check(id, repair)
- unless @db.is_marked?(id)
- stack << id
- @db.mark(id)
- end
- elsif repair
- # Remove references to bad objects.
- obj._delete_reference_to_id(id)
- end
- end
- end
+ errors
end
# This method will execute the provided block as an atomic transaction
@@ -404,8 +381,46 @@ module PEROBS
# Sweep phase of a mark-and-sweep garbage collector. It will remove all
# unmarked objects from the store.
def sweep
- @db.delete_unmarked_objects.each { |id| _collect(id, true) }
+ cntr = @db.delete_unmarked_objects.length
@cache.reset
+ cntr
+ end
+
+ # Check the object with the given start_id and all other objects that are
+ # somehow reachable from the start object.
+ # @param start_id [Fixnum or Bignum] ID of the top-level object to start
+ # with
+ # @param repair [Boolean] Delete refernces to broken objects if true
+ # @return [Fixnum] The number of references to bad objects.
+ def check_object(start_id, repair)
+ errors = 0
+ @db.mark(start_id)
+ # The todo list holds a touple for each object that still needs to be
+ # checked. The first item is the referring object and the second is the
+ # ID of the object to check.
+ todo_list = [ [ nil, start_id ] ]
+
+ while !todo_list.empty?
+ # Get the next PEROBS object to check
+ ref_obj, id = todo_list.pop
+
+ if (obj = object_by_id(id)) && @db.check(id, repair)
+ # The object exists and is OK. Mark is as checked.
+ @db.mark(id)
+ # Now look at all other objects referenced by this object.
+ obj._referenced_object_ids.each do |refd_id|
+ # Push them onto the todo list unless they have been marked
+ # already.
+ todo_list << [ obj, refd_id ] unless @db.is_marked?(refd_id)
+ end
+ else
+ # Remove references to bad objects.
+ ref_obj._delete_reference_to_id(id) if ref_obj && repair
+ errors += 1
+ end
+ end
+
+ errors
end
end
diff --git a/test/Store_spec.rb b/test/Store_spec.rb
index <HASH>..<HASH> 100644
--- a/test/Store_spec.rb
+++ b/test/Store_spec.rb
@@ -218,19 +218,23 @@ describe PEROBS::Store do
p1.related = p2
p2.related = p1
p0.related = p1
- @store.sync
- @store.gc
+ expect(@store.check).to eq(0)
+ expect(@store.gc).to eq(0)
+ p0 = p1 = p2 = nil
+ GC.start
@store = PEROBS::Store.new(@db_file)
expect(@store['person0']._id).to eq(id0)
expect(@store['person0'].related._id).to eq(id1)
expect(@store['person0'].related.related._id).to eq(id2)
@store['person0'].related = nil
- @store.gc
+ expect(@store.gc).to eq(2)
+ GC.start
expect(@store.object_by_id(id1)).to be_nil
expect(@store.object_by_id(id2)).to be_nil
@store = PEROBS::Store.new(@db_file)
+ expect(@store.check).to eq(0)
expect(@store.object_by_id(id1)).to be_nil
expect(@store.object_by_id(id2)).to be_nil
end
@@ -448,7 +452,7 @@ describe PEROBS::Store do
when 6
if rand(50) == 0
@store.sync
- @store.check(false)
+ expect(@store.check(false)).to eq(0)
end
when 7
index = rand(i) | Improve robustness of Store.check().
Under certain conditions check() did run into an infinite loop. | scrapper_perobs | train |
968e831d35c17a0a38093f4e2b1beeb21c615220 | diff --git a/scoop/futures.py b/scoop/futures.py
index <HASH>..<HASH> 100644
--- a/scoop/futures.py
+++ b/scoop/futures.py
@@ -339,7 +339,7 @@ def wait(fs, timeout=None, return_when=ALL_COMPLETED):
futures."""
DoneAndNotDoneFutures = namedtuple('DoneAndNotDoneFutures', 'done not_done')
if return_when == FIRST_COMPLETED:
- _waitAny(*fs)
+ next(_waitAny(*fs))
elif return_when in [ALL_COMPLETED, FIRST_EXCEPTION]:
for _ in _waitAll(*fs):
pass | Fixed a bug in wait with the argument FIRST_COMPLETE | soravux_scoop | train |
f56f02c241ad0ee1947c1652e3b2773b0ebd1232 | diff --git a/ontquery/plugins/services/interlex.py b/ontquery/plugins/services/interlex.py
index <HASH>..<HASH> 100644
--- a/ontquery/plugins/services/interlex.py
+++ b/ontquery/plugins/services/interlex.py
@@ -36,7 +36,9 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
self.apiEndpoint = apiEndpoint
self.api_first = api_first
- self.user_curies = user_curies or {'ILX', 'http://uri.interlex.org/base/ilx_'}
+ self.user_curies = user_curies or {'ILX': 'http://uri.interlex.org/base/ilx_',
+ #'CDE': 'http://uri.interlex.org/base/cde_', # currently used internall -> ILX.CDE
+ 'ILX.CDE': 'http://uri.interlex.org/base/cde_',}
self.readonly = readonly
self.Graph = rdflib.Graph
@@ -51,8 +53,12 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
# FIXME can't do this at the moment because interlex itself calls this --- WHOOPS
super().__init__(*args, **kwargs)
+ @staticmethod
+ def _fix_fragment(fragment):
+ return fragment.replace('ilx_', 'ILX:').replace('tmp_', 'TMP:').replace('cde_', 'ILX.CDE:')
+
def setup(self, **kwargs):
- oq.OntCuries({'ILXTEMP': 'http://uri.interlex.org/base/tmp_'})
+ oq.OntCuries({'TMP': 'http://uri.interlex.org/base/tmp_'})
if self.apiEndpoint is not None:
try:
@@ -169,7 +175,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
return self.QueryResult(
query_args=kwargs,
iri='http://uri.interlex.org/base/' + resp['ilx'],
- curie=resp['ilx'].replace('ilx_', 'ILX:').replace('tmp_', 'TMP:'),
+ curie=self._fix_fragment(resp['ilx']),
label=resp['label'],
labels=tuple(),
# abbrev=None, # TODO
@@ -194,7 +200,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
return self.QueryResult(
query_args=kwargs,
iri='http://uri.interlex.org/base/' + resp['ilx'],
- curie=resp['ilx'].replace('ilx_', 'ILX:').replace('tmp_', 'TMP:'),
+ curie=self._fix_fragment(resp['ilx']),
label=resp['label'],
labels=tuple(),
# abbrev=None, # TODO
@@ -281,7 +287,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
return self.QueryResult(
query_args={},
iri='http://uri.interlex.org/base/' + resp['ilx'],
- curie=resp['ilx'].replace('ilx_', 'ILX:').replace('tmp_', 'TMP:'),
+ curie=self._fix_fragment(resp['ilx']),
label=resp['label'],
labels=tuple(),
# abbrev=None, # TODO
@@ -400,7 +406,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
result = self.QueryResult(
query_args={},
iri='http://uri.interlex.org/base/' + resp['ilx'],
- curie=resp['ilx'].replace('ilx_', 'ILX:').replace('tmp_', 'TMP:'),
+ curie=self._fix_fragment(resp['ilx']),
label=resp['label'],
labels=tuple(),
# abbrev=None, # TODO
@@ -457,6 +463,8 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
pass
elif ontid.prefix == 'ILXTEMP':
ontid = 'tmp_' + ontid.suffix
+ elif ontid.prefix == 'ILX.CDE':
+ ontid = 'cde_' + ontid.suffix
else:
ontid = 'ilx_' + ontid.suffix
return ontid
@@ -562,7 +570,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
elif term:
resp: list = self.ilx_cli.query_elastic(term=term, size=limit)
else:
- return
+ pass # querying on iri or curie through ilx cli is ok
if not resp:
return
@@ -580,7 +588,7 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
_iri = iri
if curie is None:
- _curie = resp['ilx'].replace('ilx_', 'ILX:').replace('tmp_', 'TMP:')
+ _curie = self._fix_fragment(resp['ilx'])
else:
_curie = curie
@@ -635,12 +643,19 @@ class InterLexRemote(_InterLexSharedCache, OntService): # note to self
p = 'rdfs:subClassOf'
elif resp['type'] in ('annotation', 'relationship'):
p = 'rdfs:subPropertyOf'
+ elif resp['type'] in ('cde', 'fde', 'pde', 'TermSet'):
+ # none of these have a meaningful subClassOf relation,
+ # though it may be present in the interface
+ # XXX TODO for cde the modelling is incorrect, but the
+ # edge represents what is probably a partOf relationship
+ # or something similar
+ p = 'meaningless-superclass'
else:
raise NotImplementedError(f'how to sub thing of {resp["type"]}?')
out = {p:tuple()}
for blob_id in resp['superclasses']:
- i = self.OntId(blob_id['ilx'].replace('ilx_', 'ILX:'))
+ i = self.OntId(self._fix_fragment(blob_id['ilx']))
out[p] += i,
return out | interlex plugin add support for cde_ ids | tgbugs_ontquery | train |
e92d9be2ffc6f17a9aa700390bee2a8d9f58fda3 | diff --git a/modules/directives/calendar/calendar.js b/modules/directives/calendar/calendar.js
index <HASH>..<HASH> 100644
--- a/modules/directives/calendar/calendar.js
+++ b/modules/directives/calendar/calendar.js
@@ -1,8 +1,10 @@
/*
-* Implementation of JQuery FullCalendar inspired by http://arshaw.com/fullcalendar/
+* Implementation of JQuery FullCalendar
+* inspired by http://arshaw.com/fullcalendar/
*
* Basic Calendar Directive that takes in live events as the ng-model and then calls fullCalendar(options) to render the events correctly.
-* fullCalendar.js
+*
+* @joshkurz
*/
angular.module('ui.directives').directive('uiCalendar',['ui.config', '$parse', function (uiConfig,$parse) {
@@ -16,7 +18,7 @@ angular.module('ui.directives').directive('uiCalendar',['ui.config', '$parse', f
replace : true,
transclude : true,
scope: {
- events: "=ngModel"
+ events: "=ngModel",
},
@@ -46,19 +48,9 @@ angular.module('ui.directives').directive('uiCalendar',['ui.config', '$parse', f
expression = {};
}
angular.extend(options, uiConfig.uiCalendar, expression);
-
- var model = $parse($attrs.uiCalendar);
- //render the urls for the events. Adds a link to the event object inserted into the attribute.
- //This is where the events can be manipulated if need be.
- for(var i = 0;i < scope.events.length;i++){
- scope.events[i].url = "http://www.angularjs.org";
- }
-
+ //use the options object to create the personalized calendar
elm.fullCalendar(options);
-
- //Set events to the scope.
- model.assign(scope, scope.events);
}
};
-}]);
\ No newline at end of file
+}]);
diff --git a/modules/directives/calendar/test/calendarSpec.js b/modules/directives/calendar/test/calendarSpec.js
index <HASH>..<HASH> 100644
--- a/modules/directives/calendar/test/calendarSpec.js
+++ b/modules/directives/calendar/test/calendarSpec.js
@@ -19,10 +19,11 @@ describe('uiCalendar', function () {
afterEach(function() {
angular.module('ui.config').value('ui.config', {}); // cleanup
});
-
- function createCalendar(events) {
+
+ //Creates a calendar with with two expressions height and weekends
+ function createCalendar0(events) {
scope.events = events || {};
- $compile("<div ui-calendar='calendar' ng-model='events'></div>")(scope);
+ $compile("<div ui-calendar='{height: 200, weekends: false}' ng-model='events'></div>")(scope);
}
describe('compiling this directive and checking for the events', function () {
@@ -37,7 +38,8 @@ describe('uiCalendar', function () {
var events = [
{
title: 'All Day Event',
- start: new Date(y, m, 1)},
+ start: new Date(y, m, 1),
+ url: 'http://www.angularjs.org'},
{
title: 'Long Event',
start: new Date(y, m, d - 5),
@@ -57,26 +59,45 @@ describe('uiCalendar', function () {
//These tests pass because the scope.events object is created by the controller and passed into the directive, where the events are manipulated to fit the certain standards of the calendar.
it('should excpect to load 4 events to scope', function () {
- createCalendar(events);
+ createCalendar0(events);
expect(scope.events.length).toBe(4);
});
-
+ //test to check the title of the first event.
it('should excpect to load 4 events to scope', function () {
- createCalendar(events);
+ createCalendar0(events);
expect(scope.events[0].title).toBe('All Day Event');
});
-
- it('should expect the url to = http://www.angularjs.org', function () {
+ //test to make sure the event has a url assigned to it.
+ it('should expect the url to = http://www.angularjs.org', function () {
- createCalendar(events);
+ createCalendar0(events);
expect(scope.events[0].url).toBe('http://www.angularjs.org');
});
+ //test the 3rd events' allDay field.
+ it('should expect the url to = http://www.angularjs.org', function () {
+
+ createCalendar0(events);
+ expect(scope.events[3].allDay).toBe(false);
+ });
+ //Tests the height of the calendar.
+ it('should expect the calendar attribute height to be 200', function () {
+
+ spyOn($.fn, 'fullCalendar');
+ createCalendar0(events);
+ runs(function () {
+ expect($.fn.fullCalendar.mostRecentCall.args[0].height).toEqual(200);
+ });
+ });
+ //Tests the weekends boolean of the calendar.
+ it('should expect the calendar attribute weekends to be false', function () {
- it('should bind fullcalendar object to scope', function() {
- createCalendar(events);
- expect(scope.events).toBeTruthy();
+ spyOn($.fn, 'fullCalendar');
+ createCalendar0(events);
+ runs(function () {
+ expect($.fn.fullCalendar.mostRecentCall.args[0].weekends).toEqual(false);
});
+ });
}); | added tests to prove the ability to add expressions to the options from the html | angular-ui_ui-select2 | train |
16ae0eb4ce8fe9cd14af1f02275f2b1b73526765 | diff --git a/mot/model_building/parameter_functions/sample_statistics.py b/mot/model_building/parameter_functions/sample_statistics.py
index <HASH>..<HASH> 100644
--- a/mot/model_building/parameter_functions/sample_statistics.py
+++ b/mot/model_building/parameter_functions/sample_statistics.py
@@ -29,9 +29,7 @@ class GaussianFit(ParameterSampleStatistics):
"""
def get_statistics(self, samples):
- from mot.cl_routines.mapping.gaussian_fit import GaussianFit as GaussianFitter
- mean, std = GaussianFitter().calculate(samples)
- return SamplingStatisticsContainer(mean, {'std': std})
+ return SamplingStatisticsContainer(np.mean(samples, axis=1), {'std': np.std(samples, axis=1, ddof=1)})
class CircularGaussianFit(ParameterSampleStatistics): | Changed the sample statistic to use the CPU again for the easy statistics, for large samples this is faster than using the GPU | cbclab_MOT | train |
c839f24d6b1abce70c0d88d2b7b940083a31baa9 | diff --git a/lime/explanation.py b/lime/explanation.py
index <HASH>..<HASH> 100644
--- a/lime/explanation.py
+++ b/lime/explanation.py
@@ -225,7 +225,8 @@ class Explanation(object):
explanations for all available labels. (only used for classification)
predict_proba: if true, add barchart with prediction probabilities
for the top classes. (only used for classification)
- show_predicted_value: if true, add barchart with expected value (only used for regression)
+ show_predicted_value: if true, add barchart with expected value
+ (only used for regression)
kwargs: keyword arguments, passed to domain_mapper
Returns:
@@ -292,8 +293,14 @@ class Explanation(object):
''' % (exp, self.dummy_label)
raw_js = '''var raw_div = top_div.append('div');'''
+
+ if self.mode == "classification":
+ html_data = self.local_exp[labels[0]]
+ else:
+ html_data = self.local_exp[self.dummy_label]
+
raw_js += self.domain_mapper.visualize_instance_html(
- self.local_exp[labels[0]] if self.mode == "classification" else self.local_exp[self.dummy_label],
+ html_data,
labels[0] if self.mode == "classification" else self.dummy_label,
'raw_div',
'exp',
diff --git a/lime/lime_tabular.py b/lime/lime_tabular.py
index <HASH>..<HASH> 100644
--- a/lime/lime_tabular.py
+++ b/lime/lime_tabular.py
@@ -229,7 +229,9 @@ class LimeTabularExplainer(object):
predict_fn: prediction function. For classifiers, this should be a
function that takes a numpy array and outputs prediction
probabilities. For regressors, this takes a numpy array and
- returns the predictions. For ScikitClassifiers, this is `classifier.predict_proba()`. For ScikitRegressors, this is `regressor.predict()`.
+ returns the predictions. For ScikitClassifiers, this is
+ `classifier.predict_proba()`. For ScikitRegressors, this
+ is `regressor.predict()`.
labels: iterable with labels to be explained.
top_labels: if not None, ignore labels and produce explanations for
the K labels with highest prediction probabilities, where K is
@@ -287,7 +289,8 @@ class LimeTabularExplainer(object):
try:
assert isinstance(yss, np.ndarray) and len(yss.shape) == 1
except AssertionError:
- raise ValueError("Your model needs to output single-dimensional numpy arrays, not arrays of {} dimensions".format(yss.shape))
+ raise ValueError("Your model needs to output single-dimensional \
+ numpyarrays, not arrays of {} dimensions".format(yss.shape))
predicted_value = yss[0]
min_y = min(yss)
@@ -345,13 +348,14 @@ class LimeTabularExplainer(object):
for label in labels:
(ret_exp.intercept[label],
ret_exp.local_exp[label],
- ret_exp.score) = self.base.explain_instance_with_data(scaled_data,
- yss,
- distances,
- label,
- num_features,
- model_regressor=model_regressor,
- feature_selection=self.feature_selection)
+ ret_exp.score) = self.base.explain_instance_with_data(
+ scaled_data,
+ yss,
+ distances,
+ label,
+ num_features,
+ model_regressor=model_regressor,
+ feature_selection=self.feature_selection)
if self.mode == "regression":
ret_exp.intercept[0] = ret_exp.intercept[1] | * minor linting cleanup to satisfy flake8 | marcotcr_lime | train |
3016f3bb03709d5b1cfd69aac46695e3a54748c3 | diff --git a/salt/modules/inspectlib/collector.py b/salt/modules/inspectlib/collector.py
index <HASH>..<HASH> 100644
--- a/salt/modules/inspectlib/collector.py
+++ b/salt/modules/inspectlib/collector.py
@@ -490,8 +490,15 @@ class Inspector(EnvLoader):
'''
self._init_env()
- self._save_cfg_pkgs(self._get_changed_cfg_pkgs(self._get_cfg_pkgs()))
- self._save_payload(*self._scan_payload())
+ changed_cfg_pkgs = self._get_changed_cfg_pkgs(self._get_cfg_pkgs())
+ self._save_cfg_packages(changed_cfg_pkgs)
+
+ payload = self._scan_payload()
+ self._save_payload(*payload)
+
+ # Old stuff
+ self._save_cfg_pkgs(changed_cfg_pkgs)
+ self._save_pld(*payload)
def request_snapshot(self, mode, priority=19, **kwargs):
''' | Merge two db operations on collector | saltstack_salt | train |
f982d84a076afce73d31dab56c3f084b6f521e83 | diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/Util.java
+++ b/core/src/main/java/hudson/Util.java
@@ -866,29 +866,50 @@ public class Util {
CharBuffer buf = null;
char c;
for (int i = 0, m = s.length(); i < m; i++) {
- c = s.charAt(i);
- if (c > 122 || uriMap[c]) {
+ int codePoint = Character.codePointAt(s, i);
+ if((codePoint&0xffffff80)==0) { // 1 byte
+ c = s.charAt(i);
+ if (c > 122 || uriMap[c]) {
+ if (!escaped) {
+ out = new StringBuilder(i + (m - i) * 3);
+ out.append(s, 0, i);
+ enc = StandardCharsets.UTF_8.newEncoder();
+ buf = CharBuffer.allocate(1);
+ escaped = true;
+ }
+ // 1 char -> UTF8
+ buf.put(0, c);
+ buf.rewind();
+ try {
+ ByteBuffer bytes = enc.encode(buf);
+ while (bytes.hasRemaining()) {
+ byte b = bytes.get();
+ out.append('%');
+ out.append(toDigit((b >> 4) & 0xF));
+ out.append(toDigit(b & 0xF));
+ }
+ } catch (CharacterCodingException ex) {
+ }
+ } else if (escaped) {
+ out.append(c);
+ }
+ } else {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s, 0, i);
- enc = StandardCharsets.UTF_8.newEncoder();
- buf = CharBuffer.allocate(1);
escaped = true;
}
- // 1 char -> UTF8
- buf.put(0,c);
- buf.rewind();
- try {
- ByteBuffer bytes = enc.encode(buf);
- while (bytes.hasRemaining()) {
- byte b = bytes.get();
- out.append('%');
- out.append(toDigit((b >> 4) & 0xF));
- out.append(toDigit(b & 0xF));
- }
- } catch (CharacterCodingException ex) { }
- } else if (escaped) {
- out.append(c);
+
+ byte[] bytes = new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8);
+ for(int j=0;j<bytes.length;j++) {
+ out.append('%');
+ out.append(toDigit((bytes[j] >> 4) & 0xF));
+ out.append(toDigit(bytes[j] & 0xF));
+ }
+
+ if(Character.charCount(codePoint) > 1) {
+ i++; // we processed two characters
+ }
}
}
return escaped ? out.toString() : s;
diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/hudson/UtilTest.java
+++ b/core/src/test/java/hudson/UtilTest.java
@@ -158,6 +158,7 @@ public class UtilTest {
" \"#%/:;<>?", "%20%22%23%25%2F%3A%3B%3C%3E%3F",
"[\\]^`{|}~", "%5B%5C%5D%5E%60%7B%7C%7D%7E",
"d\u00E9velopp\u00E9s", "d%C3%A9velopp%C3%A9s",
+ "Foo \uD800\uDF98 Foo", "Foo%20%F0%90%8E%98%20Foo"
};
for (int i = 0; i < data.length; i += 2) {
assertEquals("test " + i, data[i + 1], Util.rawEncode(data[i])); | Fix JENKINS-<I> (#<I>)
This fixes the issue when the project name
includes a character that can't be encoded
directly in UTF-8, e.g., surrogate pairs. | jenkinsci_jenkins | train |
f6c580882783768d8a66b335b6ef7ceec144da4f | diff --git a/OsLogin/synth.metadata b/OsLogin/synth.metadata
index <HASH>..<HASH> 100644
--- a/OsLogin/synth.metadata
+++ b/OsLogin/synth.metadata
@@ -1,19 +1,19 @@
{
- "updateTime": "2019-05-10T10:03:43.051821Z",
+ "updateTime": "2019-06-04T19:27:21.300653Z",
"sources": [
{
"generator": {
"name": "artman",
- "version": "0.19.0",
- "dockerImage": "googleapis/artman@sha256:d3df563538225ac6caac45d8ad86499500211d1bcb2536955a6dbda15e1b368e"
+ "version": "0.23.0",
+ "dockerImage": "googleapis/artman@sha256:846102ebf7ea2239162deea69f64940443b4147f7c2e68d64b332416f74211ba"
}
},
{
"git": {
"name": "googleapis",
"remote": "https://github.com/googleapis/googleapis.git",
- "sha": "07883be5bf3c3233095e99d8e92b8094f5d7084a",
- "internalRef": "247530843"
+ "sha": "0026f4b890ed9e2388fb0573c0727defa6f5b82e",
+ "internalRef": "251265049"
}
}
],
diff --git a/OsLogin/tests/Unit/V1/OsLoginServiceClientTest.php b/OsLogin/tests/Unit/V1/OsLoginServiceClientTest.php
index <HASH>..<HASH> 100644
--- a/OsLogin/tests/Unit/V1/OsLoginServiceClientTest.php
+++ b/OsLogin/tests/Unit/V1/OsLoginServiceClientTest.php
@@ -50,14 +50,22 @@ class OsLoginServiceClientTest extends GeneratedTest
}
/**
+ * @return CredentialsWrapper
+ */
+ private function createCredentials()
+ {
+ return $this->getMockBuilder(CredentialsWrapper::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+
+ /**
* @return OsLoginServiceClient
*/
private function createClient(array $options = [])
{
$options += [
- 'credentials' => $this->getMockBuilder(CredentialsWrapper::class)
- ->disableOriginalConstructor()
- ->getMock(),
+ 'credentials' => $this->createCredentials(),
];
return new OsLoginServiceClient($options);
diff --git a/OsLogin/tests/Unit/V1beta/OsLoginServiceClientTest.php b/OsLogin/tests/Unit/V1beta/OsLoginServiceClientTest.php
index <HASH>..<HASH> 100644
--- a/OsLogin/tests/Unit/V1beta/OsLoginServiceClientTest.php
+++ b/OsLogin/tests/Unit/V1beta/OsLoginServiceClientTest.php
@@ -50,14 +50,22 @@ class OsLoginServiceClientTest extends GeneratedTest
}
/**
+ * @return CredentialsWrapper
+ */
+ private function createCredentials()
+ {
+ return $this->getMockBuilder(CredentialsWrapper::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+
+ /**
* @return OsLoginServiceClient
*/
private function createClient(array $options = [])
{
$options += [
- 'credentials' => $this->getMockBuilder(CredentialsWrapper::class)
- ->disableOriginalConstructor()
- ->getMock(),
+ 'credentials' => $this->createCredentials(),
];
return new OsLoginServiceClient($options); | test: Update generated unit tests. (#<I>) | googleapis_google-cloud-php | train |
fe3ebe75fec5f4384187210160fd7773661dc433 | diff --git a/txaws/client/base.py b/txaws/client/base.py
index <HASH>..<HASH> 100644
--- a/txaws/client/base.py
+++ b/txaws/client/base.py
@@ -415,6 +415,9 @@ def query(**kw):
@attr.s(frozen=True)
class _Query(object):
+ """
+ Representation of enough information to submit an AWS request.
+ """
_credentials = attr.ib()
_details = attr.ib()
_reactor = attr.ib(default=attr.Factory(lambda: namedAny("twisted.internet.reactor")))
@@ -471,8 +474,24 @@ class _Query(object):
def submit(self, agent=None, receiver_factory=None, utcnow=None):
- if receiver_factory is None:
- receiver_factory = StreamingBodyReceiver
+ """
+ Send this request to AWS.
+
+ @param IAgent agent: The agent to use to issue the request.
+
+ @param receiver_factory: Backwards compatibility only. The
+ value is ignored.
+
+ @param utcnow: A function like L{datetime.datetime.utcnow} to
+ get the time as of the call. This is used to provide a
+ stable timestamp for signing purposes.
+
+ @return: A L{twisted.internet.defer.Deferred} that fires with
+ the response body (L{bytes}) on success or with a
+ L{twisted.python.failure.Failure} on error. Most
+ AWS-originated errors are represented as
+ L{twisted.web.error.Error} instances.
+ """
if utcnow is None:
utcnow = datetime.utcnow
@@ -538,11 +557,11 @@ class _Query(object):
headers,
body_producer,
)
- d.addCallback(self._handle_response, receiver_factory)
+ d.addCallback(self._handle_response)
return d
- def _handle_response(self, response, receiver_factory):
- receiver = receiver_factory()
+ def _handle_response(self, response):
+ receiver = StreamingBodyReceiver()
receiver.finished = d = Deferred()
receiver.content_length = response.length
response.deliverBody(receiver) | Some more docs and stop paying attention to receiver_factory. | twisted_txaws | train |
d8875b3eae5526357e55a3d5b24e0ec0252ad4c6 | diff --git a/mod/quiz/editlib.php b/mod/quiz/editlib.php
index <HASH>..<HASH> 100644
--- a/mod/quiz/editlib.php
+++ b/mod/quiz/editlib.php
@@ -445,13 +445,13 @@ function quiz_print_question_list($quiz, $pageurl, $allowdelete=true,
?>
<div class="points">
<form method="post" action="edit.php"><div>
- <label for="<?php echo "inputq$qnum" ?>"><?php echo $strgrade; ?></label>:<br />
<fieldset class="invisiblefieldset" style="display: block;">
+ <label for="<?php echo "inputq$qnum" ?>"><?php echo $strgrade; ?></label>:<br />
<input type="hidden" name="sesskey" value="<?php echo $USER->sesskey ?>" />
<?php echo $pageurl->hidden_params_out(); ?>
<input type="hidden" name="savechanges" value="save" />
<?php
- echo '<input type="text" name="q'.$qnum.'" size="' . ($quiz->decimalpoints + 2) . '"
+ echo '<input type="text" name="q'.$qnum.'" id="inputq'.$qnum.'" size="' . ($quiz->decimalpoints + 2) . '"
value="'.(0 + $quiz->grades[$qnum]).
'" tabindex="'.($lastindex+$qno).'" />';
?> | quiz editing: MDL-<I> added an id attribute for the grading input field to make labels work | moodle_moodle | train |
d9bf07ce967d227d7aff6b21f5e87d8f5db6ef3c | diff --git a/etcd3gw/client.py b/etcd3gw/client.py
index <HASH>..<HASH> 100644
--- a/etcd3gw/client.py
+++ b/etcd3gw/client.py
@@ -400,11 +400,13 @@ class Etcd3Client(object):
def client(host='localhost', port=2379,
- ca_cert=None, cert_key=None, cert_cert=None, timeout=None):
+ ca_cert=None, cert_key=None, cert_cert=None,
+ timeout=None, protocol="http"):
"""Return an instance of an Etcd3Client."""
return Etcd3Client(host=host,
port=port,
ca_cert=ca_cert,
cert_key=cert_key,
cert_cert=cert_cert,
- timeout=timeout)
+ timeout=timeout,
+ protocol=protocol) | Support for protocol type while creating client. | dims_etcd3-gateway | train |
fe98d509c4bd9bf8b2f7f664828f5fa06ba1d88f | diff --git a/openquake/hazard/opensha.py b/openquake/hazard/opensha.py
index <HASH>..<HASH> 100644
--- a/openquake/hazard/opensha.py
+++ b/openquake/hazard/opensha.py
@@ -425,6 +425,16 @@ class ClassicalMixin(BasePSHAMixin):
:param sites: the sites of which the curve will be serialized
:type sites: list of :py:class:`openquake.shapes.Site`
"""
+
+ def duration_generator(value):
+ """
+ Returns the initial value when called for the first time and
+ the double value upon each subsequent invocation."""
+ yield value
+ while True:
+ value *= 2
+ yield value
+
nrml_path = self.build_nrml_path(nrml_file)
curve_writer = hazard_output.create_hazardcurve_writer(
@@ -433,13 +443,14 @@ class ClassicalMixin(BasePSHAMixin):
sites = set(sites)
accounted_for = set()
- initial_iteration = True
+ dgen = duration_generator(0.1)
+ duration = dgen.next()
while accounted_for != sites:
# Sleep a little before checking the availability of additional
# hazard curve results.
- if not initial_iteration:
- time.sleep(5.0)
+ time.sleep(duration)
+ results_found = 0
for site in sites:
key = key_template % hash(site)
value = kvs.get_value_json_decoded(key)
@@ -457,6 +468,10 @@ class ClassicalMixin(BasePSHAMixin):
hc_attrib.update(hc_attrib_update)
hc_data.append((site, hc_attrib))
accounted_for.add(site)
+ results_found += 1
+ if not results_found:
+ # No results found, increase the sleep duration.
+ duration = dgen.next()
curve_writer.serialize(hc_data) | the sleep duration of the (classical PSHA) results collector is now flexible
Former-commit-id: f6bf7d<I>f3d<I>e<I>eebea<I>ab<I>cd5a<I>c1 | gem_oq-engine | train |
c5545d151969b66f87cda3feee98d12b45638bed | diff --git a/src/DocBlock/Tags/Method.php b/src/DocBlock/Tags/Method.php
index <HASH>..<HASH> 100644
--- a/src/DocBlock/Tags/Method.php
+++ b/src/DocBlock/Tags/Method.php
@@ -218,6 +218,7 @@ final class Method extends BaseTag implements Factory\StaticMethod
$argument['type'] = new Void_();
}
$keys = array_keys($argument);
+ sort($keys);
if ($keys !== [ 'name', 'type' ]) {
throw new \InvalidArgumentException(
'Arguments can only have the "name" and "type" fields, found: ' . var_export($keys, true) | Adds sort to order expected keys
Without this sort the order of argument name and type matter. But
we accually don't care about the order. Only name and type are allowed
but the order doesn't matter. | phpDocumentor_ReflectionDocBlock | train |
40baf24eb1a56743e99734908d2b6ce1a32c253f | diff --git a/_state.go b/_state.go
index <HASH>..<HASH> 100644
--- a/_state.go
+++ b/_state.go
@@ -1031,7 +1031,7 @@ func (ls *LState) getField(obj LValue, key LValue) LValue {
metaindex := ls.metaOp1(curobj, "__index")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key.String())
}
return LNil
}
@@ -1062,7 +1062,7 @@ func (ls *LState) getFieldString(obj LValue, key string) LValue {
metaindex := ls.metaOp1(curobj, "__index")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key)
}
return LNil
}
@@ -1093,7 +1093,7 @@ func (ls *LState) setField(obj LValue, key LValue, value LValue) {
metaindex := ls.metaOp1(curobj, "__newindex")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key.String())
}
ls.RawSet(tb, key, value)
return
@@ -1125,7 +1125,7 @@ func (ls *LState) setFieldString(obj LValue, key string, value LValue) {
metaindex := ls.metaOp1(curobj, "__newindex")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key)
}
tb.RawSetString(key, value)
return
diff --git a/state.go b/state.go
index <HASH>..<HASH> 100644
--- a/state.go
+++ b/state.go
@@ -1186,7 +1186,7 @@ func (ls *LState) getField(obj LValue, key LValue) LValue {
metaindex := ls.metaOp1(curobj, "__index")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key.String())
}
return LNil
}
@@ -1217,7 +1217,7 @@ func (ls *LState) getFieldString(obj LValue, key string) LValue {
metaindex := ls.metaOp1(curobj, "__index")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key)
}
return LNil
}
@@ -1248,7 +1248,7 @@ func (ls *LState) setField(obj LValue, key LValue, value LValue) {
metaindex := ls.metaOp1(curobj, "__newindex")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key.String())
}
ls.RawSet(tb, key, value)
return
@@ -1280,7 +1280,7 @@ func (ls *LState) setFieldString(obj LValue, key string, value LValue) {
metaindex := ls.metaOp1(curobj, "__newindex")
if metaindex == LNil {
if !istable {
- ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
+ ls.RaiseError("attempt to index a non-table object(%v) with key '%s'", curobj.Type().String(), key)
}
tb.RawSetString(key, value)
return | improve error message when indexing non-table
when indexing a non-table object, it was sometimes hard to
understand missing key errors:
eg.
a.b.c = 5
> error was "attempt to index a non-table object(nil)"
was 'a' nil or 'a.b' nil?
now the error is:
> error was "attempt to index a non-table object(nil) with key 'b'" | yuin_gopher-lua | train |
Subsets and Splits