hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
02c2017d99ebffb1c7de2841dea2a723aa30f3d5
diff --git a/src/Illuminate/Http/Request.php b/src/Illuminate/Http/Request.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Http/Request.php +++ b/src/Illuminate/Http/Request.php @@ -598,12 +598,14 @@ class Request extends SymfonyRequest implements ArrayAccess return true; } + $types = (array) $contentTypes; + foreach ($accepts as $accept) { if ($accept === '*/*') { return true; } - foreach ((array) $contentTypes as $type) { + foreach ($types as $type) { if ($accept === $type || $accept === strtok('/', $type).'/*') { return true; }
Micro optimisation to prevent multiple casts
laravel_framework
train
2eacb4a148ebdf6e5cde1fd3f7fe285fe96d35e7
diff --git a/src/BinaryStream.php b/src/BinaryStream.php index <HASH>..<HASH> 100644 --- a/src/BinaryStream.php +++ b/src/BinaryStream.php @@ -512,8 +512,18 @@ class BinaryStream { $bytes = $sizeInBits / 8; if ($sizeInBits == 8) $data = chr($integer); + // handle 24, 40, 48 and 56 bits integers (very rare case, but it happens). + // also, handle 64-bit integer on PHP < 5.6.3 + else if ($sizeInBits % 16 == 8 || ($sizeInBits == 64 && version_compare(PHP_VERSION, '5.6.3', '<'))) { + $data = null; + for ($i = 0; $i < $bytes; $i++) { + //$value = ($value << 8) + ord($data[ $this->endian == self::BIG ? $i : abs($i - $bytes + 1) ]); + $data .= chr(($integer >> (8 * ($this->endian == self::BIG ? $bytes - $i - 1 : $i))) & 255); + } + } else $data = pack($this->types[$this->endian][$this->labels['integer'][$sizeInBits]], $integer); + if (fwrite($this->fp, $data)) { $this->offset += $bytes; } else { diff --git a/tests/WriterTest.php b/tests/WriterTest.php index <HASH>..<HASH> 100644 --- a/tests/WriterTest.php +++ b/tests/WriterTest.php @@ -23,20 +23,26 @@ class WriterTest extends PHPUnit_Framework_TestCase { $s->writeInteger(65535, 16); $s->writeInteger(65536, 32); $s->writeInteger(65536, 64); + $s->writeInteger(16777215, 24); rewind($file); $this->assertEquals([ 'a' => 127, 'b' => 65535, 'c' => 65536, - 'd' => 65536, - ], unpack('Ca/nb/Nc/Jd', fread($file, 15))); + 'd' => 0, // first part of 64-bit integer + 'e' => 65536, // second part of 64-bit integer + ], unpack('Ca/nb/Nc/Nd/Ne', fread($file, 15))); $this->assertEquals([ 'a' => 127, 'b' => 65535, 'c' => 65536, - 'd' => 65536, - ], unpack('Ca/vb/Vc/Pd', fread($file, 15))); + 'd' => 256, // first part of 64-bit integer + 'e' => 0, // second part of 64-bit integer + 'f' => 255, // first byte of 24-bit integer + 'g' => 255, // second byte of 24-bit integer + 'h' => 255, // third byte of 24-bit integer + ], unpack('Ca/vb/Vc/Nd/Ne/Cf/Cg/Ch', fread($file, 18))); } public function testFloat() {
Support for writing <I>-bit integers
wapmorgan_BinaryStream
train
1df1c27f25461f17a14edeb0d60b2460a2fa12d3
diff --git a/hypercorn/__main__.py b/hypercorn/__main__.py index <HASH>..<HASH> 100644 --- a/hypercorn/__main__.py +++ b/hypercorn/__main__.py @@ -188,12 +188,6 @@ def main(sys_args: Optional[List[str]] = None) -> None: if len(args.insecure_binds) > 0: config.insecure_bind = args.insecure_binds - for bind in config.bind: - scheme = "https" if config.ssl_enabled else "http" - print(f"Running on {bind} over {scheme} (CTRL + C to quit)") # noqa: T001 - for bind in config.insecure_bind: - print(f"Running on {bind} over http (CTRL + C to quit)") # noqa: T001 - run(config) diff --git a/hypercorn/asyncio/run.py b/hypercorn/asyncio/run.py index <HASH>..<HASH> 100644 --- a/hypercorn/asyncio/run.py +++ b/hypercorn/asyncio/run.py @@ -14,6 +14,7 @@ from ..utils import ( load_application, MustReloadException, observe_changes, + repr_socket_addr, restart, Shutdown, ) @@ -90,25 +91,29 @@ async def worker_serve( async def _server_callback(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: await Server(app, loop, config, reader, writer) - servers = [ - await asyncio.start_server( - _server_callback, - backlog=config.backlog, - loop=loop, - ssl=ssl_context, - sock=sock, - ssl_handshake_timeout=ssl_handshake_timeout, + servers = [] + for sock in sockets.secure_sockets: + servers.append( + await asyncio.start_server( + _server_callback, + backlog=config.backlog, + loop=loop, + ssl=ssl_context, + sock=sock, + ssl_handshake_timeout=ssl_handshake_timeout, + ) ) - for sock in sockets.secure_sockets - ] - servers.extend( - [ + bind = repr_socket_addr(sock.family, sock.getsockname()) + config.log.info(f"Running on {bind} over https (CTRL + C to quit)") + + for sock in sockets.insecure_sockets: + servers.append( await asyncio.start_server( _server_callback, backlog=config.backlog, loop=loop, sock=sock ) - for sock in sockets.insecure_sockets - ] - ) + ) + bind = repr_socket_addr(sock.family, sock.getsockname()) + config.log.info(f"Running on {bind} over http (CTRL + C to quit)") reload_ = False try: diff --git a/hypercorn/trio/run.py b/hypercorn/trio/run.py index <HASH>..<HASH> 100644 --- a/hypercorn/trio/run.py +++ b/hypercorn/trio/run.py @@ -13,6 +13,7 @@ from ..utils import ( load_application, MustReloadException, observe_changes, + repr_socket_addr, restart, Shutdown, ) @@ -49,20 +50,23 @@ async def worker_serve( sock.listen(config.backlog) ssl_context = config.create_ssl_context() - listeners = [ - trio.SSLListener( - trio.SocketListener(trio.socket.from_stdlib_socket(sock)), - ssl_context, - https_compatible=True, + listeners = [] + for sock in sockets.secure_sockets: + listeners.append( + trio.SSLListener( + trio.SocketListener(trio.socket.from_stdlib_socket(sock)), + ssl_context, + https_compatible=True, + ) ) - for sock in sockets.secure_sockets - ] - listeners.extend( - [ - trio.SocketListener(trio.socket.from_stdlib_socket(sock)) - for sock in sockets.insecure_sockets - ] - ) + bind = repr_socket_addr(sock.family, sock.getsockname()) + config.log.info(f"Running on {bind} over https (CTRL + C to quit)") + + for sock in sockets.insecure_sockets: + listeners.append(trio.SocketListener(trio.socket.from_stdlib_socket(sock))) + bind = repr_socket_addr(sock.family, sock.getsockname()) + config.log.info(f"Running on {bind} over http (CTRL + C to quit)") + task_status.started() await trio.serve_listeners(partial(Server, app, config), listeners) diff --git a/hypercorn/utils.py b/hypercorn/utils.py index <HASH>..<HASH> 100644 --- a/hypercorn/utils.py +++ b/hypercorn/utils.py @@ -169,6 +169,15 @@ def parse_socket_addr(family: int, address: tuple) -> Optional[Tuple[str, int]]: return None +def repr_socket_addr(family: int, address: tuple) -> str: + if family in {socket.AF_INET, socket.AF_INET6}: + return f"{address[0]}:{address[1]}" + elif family == socket.AF_UNIX: + return f"unix:{address}" + else: + return f"{address}" + + async def invoke_asgi(app: ASGIFramework, scope: dict, receive: Callable, send: Callable) -> None: if _is_asgi_2(app): scope["asgi"]["version"] = "2.0"
Log the binding, rather than print This also ensures that the correct binding is logged (say if the configured port is 0 and hence a random port is chosen).
pgjones_hypercorn
train
c2f631a64225fb0155f690f89a9c4c0299aa723f
diff --git a/src/scene.js b/src/scene.js index <HASH>..<HASH> 100644 --- a/src/scene.js +++ b/src/scene.js @@ -302,6 +302,47 @@ exports.Scene = function(containerIn, rendererIn) { return objectsArray; } + this.getBoundingBoxOfZincObjects = objectsArray => { + let boundingBox = undefined; + for (let i = 0; i < objectsArray.length; i++) { + let box = objectsArray[i].getBoundingBox(); + if (box) { + if (!boundingBox) + boundingBox = box; + else + boundingBox.union(box); + } + } + return boundingBox; + } + + this.vectorToScreenXY = point => { + const vector = new THREE.Vector3(); + point.project(this.camera); + let width = getDrawingWidth(); + let height = getDrawingHeight(); + var widthHalf = (width/2); + var heightHalf = (height/2); + vector.x = ( point.x * widthHalf ) + widthHalf; + vector.y = - ( point.y * heightHalf ) + heightHalf; + return vector; + } + + this.getObjectsScreenXY = zincObjects => { + if (zincObjects && zincObjects.length > 0) { + let boundingBox = this.getBoundingBoxOfZincObjects(zincObjects); + const center = new THREE.Vector3(); + boundingBox.getCenter(center); + return this.vectorToScreenXY(center); + } + return undefined; + } + + this.getNamedObjectsScreenXY = name => { + let zincObjects = this.findObjectsWithGroupName(name); + return this.getObjectsScreenXY(zincObjects); + }; + this.addGlyphset = glyphset => { if (glyphset && glyphset.isGlyphset) { const group = glyphset.getGroup(); @@ -815,12 +856,11 @@ exports.Scene = function(containerIn, rendererIn) { return false; } - this.alignObjectToCameraView = (zincObject, transitionTime) => { - if (this.objectIsInScene(zincObject)) { + this.alignBoundingBoxToCameraView = (boundingBox, transitionTime) => { + if (boundingBox) { const center = new THREE.Vector3(); - const boundingBox = zincObject.getBoundingBox(); - const viewport = this.getZincCameraControls().getCurrentViewport(); boundingBox.getCenter(center); + const viewport = this.getZincCameraControls().getCurrentViewport(); const target = new THREE.Vector3(viewport.targetPosition[0], viewport.targetPosition[1], viewport.targetPosition[2]); const eyePosition = new THREE.Vector3(viewport.eyePosition[0], @@ -844,6 +884,13 @@ exports.Scene = function(containerIn, rendererIn) { } } + this.alignObjectToCameraView = (zincObject, transitionTime) => { + if (this.objectIsInScene(zincObject)) { + const boundingBox = zincObject.getBoundingBox(); + this.alignBoundingBoxToCameraView(boundingBox, transitionTime); + } + } + this.setCameraTargetToObject = zincObject => { if (this.objectIsInScene(zincObject)) { const center = new THREE.Vector3();
Add function to get the window coordinates.
alan-wu_ZincJS
train
459e8c12a9c828a0b3faff59df69c2e1f083309c
diff --git a/hdfs_datanode/tests/common.py b/hdfs_datanode/tests/common.py index <HASH>..<HASH> 100644 --- a/hdfs_datanode/tests/common.py +++ b/hdfs_datanode/tests/common.py @@ -33,7 +33,7 @@ EXPECTED_METRICS = [ 'hdfs.datanode.num_blocks_cached', 'hdfs.datanode.num_failed_volumes', 'hdfs.datanode.num_blocks_failed_to_cache', - 'hdfs.datanode.num_blocks_failed_to_uncache', + # 'hdfs.datanode.num_blocks_failed_to_uncache', metric is flakey in 3.1.3 ] HDFS_DATANODE_CONFIG = {'instances': [{'hdfs_datanode_jmx_uri': DATANODE_URI, 'tags': list(CUSTOM_TAGS)}]} @@ -61,7 +61,7 @@ HDFS_DATANODE_METRICS_VALUES = { 'hdfs.datanode.num_blocks_cached': 0, 'hdfs.datanode.num_failed_volumes': 0, 'hdfs.datanode.num_blocks_failed_to_cache': 0, - 'hdfs.datanode.num_blocks_failed_to_uncache': 0, + # 'hdfs.datanode.num_blocks_failed_to_uncache': 0, metric is flakey in 3.1.3 } HDFS_DATANODE_METRIC_TAGS = ['datanode_url:{}'.format(DATANODE_URI)] diff --git a/hdfs_datanode/tests/test_e2e.py b/hdfs_datanode/tests/test_e2e.py index <HASH>..<HASH> 100644 --- a/hdfs_datanode/tests/test_e2e.py +++ b/hdfs_datanode/tests/test_e2e.py @@ -10,6 +10,7 @@ from . import common @pytest.mark.e2e def test_e2e(dd_agent_check, instance): + # We do not do aggregator.assert_all_metrics_covered() because depending on timing, some other metrics may appear aggregator = dd_agent_check(instance, rate=True) tags = ['datanode_url:{}'.format(instance["hdfs_datanode_jmx_uri"])] @@ -17,6 +18,4 @@ def test_e2e(dd_agent_check, instance): for metric in common.EXPECTED_METRICS: aggregator.assert_metric(metric, tags=tags) - aggregator.assert_all_metrics_covered() - aggregator.assert_service_check('hdfs.datanode.jmx.can_connect', status=HDFSDataNode.OK, tags=tags) diff --git a/hdfs_datanode/tests/test_hdfs_datanode.py b/hdfs_datanode/tests/test_hdfs_datanode.py index <HASH>..<HASH> 100644 --- a/hdfs_datanode/tests/test_hdfs_datanode.py +++ b/hdfs_datanode/tests/test_hdfs_datanode.py @@ -24,6 +24,7 @@ CHECK_ID = 'test:123' def test_check(aggregator, mocked_request): """ Test that we get all the metrics we're supposed to get + Note: We don't do aggregator.assert_all_metrics_covered() because depending on timing, some other metrics may appear """ instance = HDFS_DATANODE_CONFIG['instances'][0] @@ -40,8 +41,6 @@ def test_check(aggregator, mocked_request): for metric, value in iteritems(HDFS_DATANODE_METRICS_VALUES): aggregator.assert_metric(metric, value=value, tags=HDFS_DATANODE_METRIC_TAGS + CUSTOM_TAGS, count=1) - aggregator.assert_all_metrics_covered() - def test_metadata(aggregator, mocked_request, mocked_metadata_request, datadog_agent): """
Remove expected metric from tests (#<I>) * Comment out flakey test * Remove assert_all_metrics call * Remove other assert_all_metrics
DataDog_integrations-core
train
a8b66e50caf229509b975b62eb7a7e51ca638d85
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ setup( maintainer="Jeff Ortel", maintainer_email="jortel@redhat.com", packages=find_packages(), - url="https://fedorahosted.org/suds" + url="https://fedorahosted.org/suds", install_requires=requires )
fix comma missing after url
suds-community_suds
train
bd947cd1b43b4e9d63df800edd17219a2b9bdc0b
diff --git a/spec/integration/switch_user_spec.rb b/spec/integration/switch_user_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/switch_user_spec.rb +++ b/spec/integration/switch_user_spec.rb @@ -58,11 +58,11 @@ RSpec.describe "Using SwitchUser", type: :request do it "can switch back to a different user without hitting remember_user endpoint" do # login - post "/login", params: { :id => user.id } + post "/login", params: { id: user.id } follow_redirect! # check that we can switch to another user - get "/switch_user?scope_identifier=user_#{other_user.id}", params: { :remember => true } + get "/switch_user?scope_identifier=user_#{other_user.id}", params: { remember: true } expect(session["user_id"]).to eq other_user.id expect(session["original_user_scope_identifier"]).to_not be_nil @@ -75,7 +75,7 @@ RSpec.describe "Using SwitchUser", type: :request do expect(session["user_id"]).to eq user.id # check that we can be un-remembered - get "/switch_user/remember_user", params: { :remember => false } + get "/switch_user/remember_user", params: { remember: false } expect(session["original_user"]).to be_nil end @@ -116,11 +116,11 @@ RSpec.describe "Using SwitchUser", type: :request do it "can switch back to a different user without hitting remember_user endpoint" do # login - post "/login", params: { :id => user.id } + post "/login", params: { id: user.id } follow_redirect! # check that we can switch to another user - get "/switch_user?scope_identifier=user_#{other_user.email}", params: { :remember => true } + get "/switch_user?scope_identifier=user_#{other_user.email}", params: { remember: true } expect(session["user_id"]).to eq other_user.id expect(session["original_user_scope_identifier"]).to_not be_nil @@ -133,7 +133,7 @@ RSpec.describe "Using SwitchUser", type: :request do expect(session["user_id"]).to eq user.id # check that we can be un-remembered - get "/switch_user/remember_user", params: { :remember => false } + get "/switch_user/remember_user", params: { remember: false } expect(session["original_user"]).to be_nil end end
Auto corrected by following Style/HashSyntax
flyerhzm_switch_user
train
73b19fc5bcbc90f5187985dc4b3033a3b3b3f82a
diff --git a/simuvex/procedures/cgc/receive.py b/simuvex/procedures/cgc/receive.py index <HASH>..<HASH> 100644 --- a/simuvex/procedures/cgc/receive.py +++ b/simuvex/procedures/cgc/receive.py @@ -31,6 +31,7 @@ class receive(simuvex.SimProcedure): if self.state.satisfiable(extra_constraints=[count != 0]): data = self.state.posix.read(fd, count) + self.state.log.events[-1].size.ast = actual_size self.state.store_mem(buf, data, size=actual_size) self.state.store_mem(rx_bytes, actual_size, condition=rx_bytes != 0, endness='Iend_LE')
constrain the size correctly in recieve
angr_angr
train
ee12d933f1951b16117ba463889a7acf379e0e27
diff --git a/rusha.sweet.js b/rusha.sweet.js index <HASH>..<HASH> 100644 --- a/rusha.sweet.js +++ b/rusha.sweet.js @@ -188,7 +188,7 @@ case 'array': return convBuf.bind(data); case 'buffer': return convBuf.bind(data); case 'arraybuffer': return convBuf.bind(new Uint8Array(data)); - case 'view': return convBuf.bind(new Uint8Array(data.buffer)); + case 'view': return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); case 'blob': return convBlob.bind(data); } };
Support typed arrays with custom parents Typed arrays (Uint8Array, etc.) can point to a slice of a larger backing ArrayBuffer. Currently, Rusha is broken because it just uses the whole backing ArrayBuffer disregarding the slice that the typed array points to. This PR resolves this issue.
srijs_rusha
train
bfb4deb73cf85f616d68d8bffde67981e90d4009
diff --git a/indra/tests/test_html_assembler.py b/indra/tests/test_html_assembler.py index <HASH>..<HASH> 100644 --- a/indra/tests/test_html_assembler.py +++ b/indra/tests/test_html_assembler.py @@ -181,23 +181,30 @@ def test_default_colors(): # that adds a source without also running # regenerate_default_source_styling() - # Get sources in DEFAULT_SOURCE_COLORS + # Get sources and colors in DEFAULT_SOURCE_COLORS def_all_sources = set() color_combos = [] + def_source_color = {} for source_type, scheme in DEFAULT_SOURCE_COLORS: txt_col = scheme['color'] for source in scheme['sources']: def_all_sources.add(source) color_combos.append((txt_col, scheme['sources'][source])) + def_source_color[source] = scheme['sources'][source] source_info_json = load_resource_json('source_info.json') # pc and biopax both map to pc here src_inf_sources = {internal_source_mappings.get(s, s) for s in source_info_json.keys()} + src_inf_colors = { + internal_source_mappings.get(source, source): + info['default_style']['background-color'] + for source, info in source_info_json.items() + } - # Trips is NOT in source_info, but exists in INDRA DB naming + # Trips is NOT in source_info, but exists in INDRA DB naming. # biopax and pathway commons are both in source_info, but are mapped to - # the same source in INDRA DB naming: pc + # the same source in INDRA DB naming: pc. assert 'trips' in def_all_sources assert 'pc' in def_all_sources assert 'drum' not in def_all_sources @@ -221,6 +228,17 @@ def test_default_colors(): color_combos_set = set(color_combos) assert len(color_combos_set) == len(color_combos) + # Test that the colors in DEFAULT_SOURCE_COLORS match what is set in + # source_info.json, after mapping of source names + for source, bg_color in def_source_color.items(): + if source == 'trips': + mapped = 'drum' + else: + mapped = source + + assert bg_color == src_inf_colors[mapped], \ + f'{mapped}: default={bg_color}; json={src_inf_colors[mapped]}' + def test_color_schemes(): # Test for uniqueness in the schemes
Add testing of color equivalence
sorgerlab_indra
train
1c2f906650a50c63fd4574c4deb56b743a3fa4bd
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,16 +10,10 @@ install: - composer install --no-interaction script: - - vendor/bin/phpunit -c phpunit.xml + - ./vendor/bin/phpunit # Configure email notifications notifications: email: on_success: never on_failure: always - -# You can delete cache using travis-ci web interface -cache: - directories: - - vendor - - $HOME/.cache/composer diff --git a/phpunit.xml b/phpunit.xml index <HASH>..<HASH> 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,6 +1,8 @@ <?xml version="1.0" encoding="UTF-8"?> -<phpunit bootstrap="vendor/autoload.php" colors="true" +<phpunit bootstrap="./vendor/autoload.php" + colors="true" + verbose="true" beStrictAboutTestsThatDoNotTestAnything="true" beStrictAboutOutputDuringTests="true" beStrictAboutChangesToGlobalState="true"> diff --git a/src/Check/D7/PreprocessCSS.php b/src/Check/D7/PreprocessCSS.php index <HASH>..<HASH> 100644 --- a/src/Check/D7/PreprocessCSS.php +++ b/src/Check/D7/PreprocessCSS.php @@ -16,7 +16,7 @@ use Drutiny\Annotation\CheckInfo; * supports_remediation = TRUE, * ) */ -class PreprocessCss extends Check { +class PreprocessCSS extends Check { public function check() { $fixups = []; diff --git a/src/Check/D8/PreprocessCSS.php b/src/Check/D8/PreprocessCSS.php index <HASH>..<HASH> 100644 --- a/src/Check/D8/PreprocessCSS.php +++ b/src/Check/D8/PreprocessCSS.php @@ -16,7 +16,7 @@ use Drutiny\Annotation\CheckInfo; * supports_remediation = TRUE, * ) */ -class PreprocessCss extends Check { +class PreprocessCSS extends Check { public function check() { $fixups = []; diff --git a/tests/src/Unit/Check/D7/PreprocessCSSTest.php b/tests/src/Unit/Check/D7/PreprocessCSSTest.php index <HASH>..<HASH> 100644 --- a/tests/src/Unit/Check/D7/PreprocessCSSTest.php +++ b/tests/src/Unit/Check/D7/PreprocessCSSTest.php @@ -1,12 +1,12 @@ <?php -use Drutiny\Check\D7\PreprocessCss; +use Drutiny\Check\D7\PreprocessCSS; use Drutiny\Base\DrushCaller; use Drutiny\Context; use PHPUnit\Framework\TestCase; /** - * @coversDefaultClass \Drutiny\Check\D7\PreprocessCss + * @coversDefaultClass \Drutiny\Check\D7\PreprocessCSS */ class PreprocessCSSTest extends TestCase { @@ -26,7 +26,7 @@ class PreprocessCSSTest extends TestCase $context->set('drush', $drushStub) ->set('autoRemediate', FALSE); - $check = new PreprocessCss($context); + $check = new PreprocessCSS($context); // Test it. $this->assertEquals(FALSE, $check->check()); // 0
Mac OSX is case insensitive, fix autoloading.
drutiny_drutiny
train
71bb1dfdcd030b2518e5b6a10c531f6fcba65e9f
diff --git a/cobra_test.go b/cobra_test.go index <HASH>..<HASH> 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -119,6 +119,16 @@ func initializeWithRootCmd() *Command { return cmdRootWithRun } +func checkOutputContains(t *testing.T, c *Command, check string) { + buf := new(bytes.Buffer) + c.SetOutput(buf) + c.Execute() + + if !strings.Contains(buf.String(), check) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", check, buf.String()) + } +} + func TestSingleCommand(t *testing.T) { c := initialize() c.AddCommand(cmdPrint, cmdEcho) @@ -378,29 +388,19 @@ func TestPersistentFlags(t *testing.T) { } func TestHelpCommand(t *testing.T) { - buf := new(bytes.Buffer) c := initialize() cmdEcho.AddCommand(cmdTimes) c.AddCommand(cmdPrint, cmdEcho) c.SetArgs(strings.Split("help echo", " ")) - c.SetOutput(buf) - c.Execute() - if !strings.Contains(buf.String(), cmdEcho.Long) { - t.Errorf("Wrong error message displayed, \n %s", buf.String()) - } + checkOutputContains(t, c, cmdEcho.Long) - buf.Reset() c = initialize() cmdEcho.AddCommand(cmdTimes) c.AddCommand(cmdPrint, cmdEcho) c.SetArgs(strings.Split("help echo times", " ")) - c.SetOutput(buf) - c.Execute() - if !strings.Contains(buf.String(), cmdTimes.Long) { - t.Errorf("Wrong error message displayed, \n %s", buf.String()) - } + checkOutputContains(t, c, cmdTimes.Long) } func TestRunnableRootCommand(t *testing.T) { @@ -427,5 +427,15 @@ func TestRootFlags(t *testing.T) { if flagir != 17 { t.Errorf("flag value should be 17, %d given", flagir) } +} + +func TestRootHelp(t *testing.T) { + fmt.Println("testing root help") + c := initializeWithRootCmd() + c.AddCommand(cmdPrint, cmdEcho) + c.SetArgs(strings.Split("--help", " ")) + e := c.Execute() + fmt.Println(e) + checkOutputContains(t, c, "Available Commands:") } diff --git a/command.go b/command.go index <HASH>..<HASH> 100644 --- a/command.go +++ b/command.go @@ -344,6 +344,9 @@ func (c *Command) Execute() (err error) { if err != nil && c.Runnable() { e := c.ParseFlags(args) if e != nil { + // Flags parsing had an error. + fmt.Println(e) + c.Usage() return e } else { argWoFlags := c.Flags().Args()
Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.
spf13_cobra
train
8361476bd59b9807ac8e306e74f702bd1cefc2f9
diff --git a/procstats/proc.go b/procstats/proc.go index <HASH>..<HASH> 100644 --- a/procstats/proc.go +++ b/procstats/proc.go @@ -31,6 +31,10 @@ type procCPU struct { percent float64 `metric:"usage.percent" type:"gauge"` typ string `tag:"type"` // system } + total struct { + time time.Duration `metric:"usage_total.seconds" type:"counter"` + percent float64 `metric:"usage_total.percent" type:"gauge"` + } } type procMemory struct { @@ -136,6 +140,9 @@ func (p *ProcMetrics) Collect() { p.cpu.system.time = m.CPU.Sys - p.last.CPU.Sys p.cpu.system.percent = 100 * float64(p.cpu.system.time) / float64(interval) + p.cpu.total.time = (m.CPU.User + m.CPU.Sys) - (p.last.CPU.User + p.last.CPU.Sys) + p.cpu.total.percent = 100 * float64(p.cpu.total.time) / float64(interval) + p.memory.available = m.Memory.Available p.memory.size = m.Memory.Size p.memory.resident.usage = m.Memory.Resident
report total CPU usage (#<I>)
segmentio_stats
train
60ede9eb7fcbf8f2f33f6834f1c417e90cccd542
diff --git a/endpoints/ship/tests/integration_test.js b/endpoints/ship/tests/integration_test.js index <HASH>..<HASH> 100644 --- a/endpoints/ship/tests/integration_test.js +++ b/endpoints/ship/tests/integration_test.js @@ -1,22 +1,23 @@ import request from 'request' import helpers from '../../../lib/test_helpers.js' -describe('car', () => { +describe('ship', () => { it('should return an array of objects containing correct fields', (done) => { const fieldsToCheckFor = [ - 'registryNumber', - 'number', - 'factoryNumber', + 'name', 'type', - 'subType', - 'color', - 'registeredAt', - 'status', - 'nextCheck', - 'pollution', - 'weight', + 'registrationNumber', + 'regionalCode', + 'homePort', + 'registrationStatus', + 'grossRegisterTonnage', + 'grossTonnage', + 'length', + 'buildYear', + 'buildYard', + 'owners', ] - const params = helpers.testRequestParams('/car', { carPlate: 'AA031' }) + const params = helpers.testRequestParams('/ship', { search: 'helga maría' }) const resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor) request.get(params, resultHandler) })
Adding tests for /ship endpoint
apis-is_apis
train
43c6c7ddb475a99e09ddfe700cc2bc285e550705
diff --git a/cmd/juju/bootstrap.go b/cmd/juju/bootstrap.go index <HASH>..<HASH> 100644 --- a/cmd/juju/bootstrap.go +++ b/cmd/juju/bootstrap.go @@ -33,29 +33,5 @@ func (c *BootstrapCommand) Run(_ *cmd.Context) error { if err != nil { return err } - // TODO(rog) use (juju/environs).Bootstrap - return environ.Bootstrap(c.UploadTools, caPEM) + return environs.Bootstrap(environ, c.UploadTools, nil) } - -var caPEM = []byte(` ------BEGIN CERTIFICATE----- -MIIBnTCCAUmgAwIBAgIBADALBgkqhkiG9w0BAQUwJjENMAsGA1UEChMEanVqdTEV -MBMGA1UEAxMManVqdSB0ZXN0aW5nMB4XDTEyMTExNDE0Mzg1NFoXDTIyMTExNDE0 -NDM1NFowJjENMAsGA1UEChMEanVqdTEVMBMGA1UEAxMManVqdSB0ZXN0aW5nMFow -CwYJKoZIhvcNAQEBA0sAMEgCQQCCOOpn9aWKcKr2GQGtygwD7PdfNe1I9BYiPAqa -I33F5+6PqFdfujUKvoyTJI6XG4Qo/CECaaN9smhyq9DxzMhAgMBAAGjZjBkMA4G -A1UdDwEB/wQEAwIABDASBgNVHRMBAf8ECDAGAQH/AgEBMB0GA1UdDgQWBBQQDswP -FQGeGMeTzPbHW62EZbbTJzAfBgNVHSMEGDAWgBQQDswPFQGeGMeTzPbHW62EZbbT -JzALBgkqhkiG9w0BAQUDQQAqZzN0DqUyEfR8zIanozyD2pp10m9le+ODaKZDDNfH -cB2x26F1iZ8ccq5IC2LtQf1IKJnpTcYlLuDvW6yB96g ------END CERTIFICATE----- ------BEGIN RSA PRIVATE KEY----- -MIIBOwIBAAJBAII46mf1pYpwqvYZAa3KDAPs91817Uj0FiI8CprYjfcXn7o+oV1+ -NQq+jJMkjpcbhCj8IQJpo32yaHKr0PHMyECAwEAAQJAYctedh4raLE+Ir0a3qnK -pjQSfiUggtYTvTf7+tfAnZu946PX88ysr7XHPkXEGP4tWDTbl8BfGndrTKswVOx6 -RQIhAOT5OzafJneDQ5cuGLN/hxIPBLWxKT1/25O6dhtBlRyPAiEAkZfFvCtBZyKB -JFwDdp+7gE98mXtaFrjctLWeFx797U8CIAnnqiMTwWM8H2ljyhfBtYMXeTmu3zzU -hfS4hcNwDiLAiEAkNXXU7YEPkFJD46ps1x7/s0UOutHV8tXZD44ou+l1GkCIQDO -HOzuvYngJpoClGw0ipzJPoNZ2Z/GkdOWGByPeKu/8g== ------END RSA PRIVATE KEY----- -`) diff --git a/cmd/juju/bootstrap_test.go b/cmd/juju/bootstrap_test.go index <HASH>..<HASH> 100644 --- a/cmd/juju/bootstrap_test.go +++ b/cmd/juju/bootstrap_test.go @@ -57,9 +57,8 @@ func (*BootstrapSuite) TestBootstrapCommand(c *C) { // Check that the CA certificate has been automatically generated // for the environment. - // TODO(rog) reenable - //_, err = os.Stat(filepath.Join(home, ".juju", "peckham.pem")) - //c.Assert(err, IsNil) + _, err = os.Stat(filepath.Join(home, ".juju", "peckham.pem")) + c.Assert(err, IsNil) // bootstrap with tool uploading - checking that a file // is uploaded should be sufficient, as the detailed semantics
cmd/juju: revert bootstrap to trunk version
juju_juju
train
58b0e7d23d31ac74ea5334b92068feee9c85eb20
diff --git a/client/src/main/java/io/pravega/client/stream/impl/PendingEvent.java b/client/src/main/java/io/pravega/client/stream/impl/PendingEvent.java index <HASH>..<HASH> 100644 --- a/client/src/main/java/io/pravega/client/stream/impl/PendingEvent.java +++ b/client/src/main/java/io/pravega/client/stream/impl/PendingEvent.java @@ -24,7 +24,12 @@ import lombok.Data; */ @Data public class PendingEvent { - public static final int MAX_WRITE_SIZE = Serializer.MAX_EVENT_SIZE; + /** + * The serialized event max size. Equals to the max event payload size plus additional 8 bytes for the wire command + * code and the payload size. + * @see Event for the details. + */ + public static final int MAX_WRITE_SIZE = Serializer.MAX_EVENT_SIZE + 8; /** * The routing key that was provided to route the data. */
Issue <I>: Correct maximum event size (#<I>) * Allow max event size payload = 1MB
pravega_pravega
train
eeb6529bf3fa1883c691f5c4024e5b4278fb9c38
diff --git a/src/lib/metadata-yaml.js b/src/lib/metadata-yaml.js index <HASH>..<HASH> 100644 --- a/src/lib/metadata-yaml.js +++ b/src/lib/metadata-yaml.js @@ -111,7 +111,13 @@ function applyObjectMeta(value, meta) { meta.children[childMeta.key] = { templates: [] }; meta.countOfChildren++; } - meta.children[childMeta.key].templates.push(childMeta.more()); + + // [JSH] Fixed issue #22 with this conditional. + // Unsure of the intent, all tests continue to pass. + // meta.children[childMeta.key].templates was undefined + if (meta.children[childMeta.key].templates) { + meta.children[childMeta.key].templates.push(childMeta.more()); + } } else { meta.children[childMeta.key] = childMeta; meta.countOfChildren++;
Fixed Issue with Header Partial. Closes #<I>
lynx-json_lynx-docs
train
c3eeae282944dd4e86b75ff45c82581cd1c4de54
diff --git a/groupstore_GEN_.go b/groupstore_GEN_.go index <HASH>..<HASH> 100644 --- a/groupstore_GEN_.go +++ b/groupstore_GEN_.go @@ -82,6 +82,8 @@ type defaultGroupStore struct { lookupGroupItems int32 reads int32 readErrors int32 + readGroups int32 + readGroupItems int32 writes int32 writeErrors int32 writesOverridden int32 @@ -456,6 +458,30 @@ func (store *defaultGroupStore) LookupGroup(keyA uint64, keyB uint64) ([]LookupG return rv[:i], nil } +func (store *defaultGroupStore) ReadGroup(keyA uint64, keyB uint64) ([]ReadGroupItem, error) { + // Returned []ReadGroupItem is not a []* for less garbage collection and + // is likely fine most use cases. + atomic.AddInt32(&store.readGroups, 1) + items := store.locmap.GetGroup(keyA, keyB) + if len(items) == 0 { + return nil, nil + } + rv := make([]ReadGroupItem, len(items)) + i := 0 + for _, item := range items { + timestampMicro, value, err := store.read(keyA, keyB, item.ChildKeyA, item.ChildKeyB, nil) + if err == nil && timestampMicro&_TSB_DELETION == 0 { + rv[i].ChildKeyA = item.ChildKeyA + rv[i].ChildKeyB = item.ChildKeyB + rv[i].TimestampMicro = int64(timestampMicro >> _TSB_UTIL_BITS) + rv[i].Value = value + i++ + } + } + atomic.AddInt32(&store.readGroupItems, int32(i)) + return rv[:i], nil +} + func (store *defaultGroupStore) Read(keyA uint64, keyB uint64, childKeyA uint64, childKeyB uint64, value []byte) (int64, []byte, error) { atomic.AddInt32(&store.reads, 1) timestampbits, value, err := store.read(keyA, keyB, childKeyA, childKeyB, value) diff --git a/package.go b/package.go index <HASH>..<HASH> 100644 --- a/package.go +++ b/package.go @@ -280,6 +280,14 @@ type LookupGroupItem struct { Length uint32 } +// ReadGroupItem is returned by the GroupStore.ReadGroup call. +type ReadGroupItem struct { + ChildKeyA uint64 + ChildKeyB uint64 + TimestampMicro int64 + Value []byte +} + // GroupStore is an interface for a disk-backed data structure that stores // []byte values referenced by 128 bit key pairs with options for replication. // Values are stored by the combination of both pairs (parentKeyA, parentKeyB, @@ -315,6 +323,9 @@ type GroupStore interface { // or returns any error; a newer timestampmicro already in place is not // reported as an error. Note that with a Write and a Delete for the exact // same timestampmicro, the Delete wins. + // ReadGroup returns all the (childKeyA, childKeyB, timestampMicro, value) + // items matching under (parentKeyA, parentKeyB). + ReadGroup(parentKeyA, parentKeyB uint64) ([]ReadGroupItem, error) Write(parentKeyA, parentKeyB, childKeyA, childKeyB uint64, timestampmicro int64, value []byte) (oldtimestampmicro int64, err error) // Delete stores timestampmicro for (parentKeyA, parentKeyB, childKeyA, // childKeyB) and returns the previously stored timestampmicro or returns diff --git a/store.got b/store.got index <HASH>..<HASH> 100644 --- a/store.got +++ b/store.got @@ -82,6 +82,8 @@ type default{{.T}}Store struct { lookupGroupItems int32 reads int32 readErrors int32 + readGroups int32 + readGroupItems int32 writes int32 writeErrors int32 writesOverridden int32 @@ -457,6 +459,30 @@ func (store *default{{.T}}Store) LookupGroup(keyA uint64, keyB uint64) ([]Lookup atomic.AddInt32(&store.lookupGroupItems, int32(i)) return rv[:i], nil } + +func (store *default{{.T}}Store) ReadGroup(keyA uint64, keyB uint64) ([]ReadGroupItem, error) { + // Returned []ReadGroupItem is not a []* for less garbage collection and + // is likely fine most use cases. + atomic.AddInt32(&store.readGroups, 1) + items := store.locmap.GetGroup(keyA, keyB) + if len(items) == 0 { + return nil, nil + } + rv := make([]ReadGroupItem, len(items)) + i := 0 + for _, item := range items { + timestampMicro, value, err := store.read(keyA, keyB, item.ChildKeyA, item.ChildKeyB, nil) + if err == nil && timestampMicro & _TSB_DELETION == 0 { + rv[i].ChildKeyA = item.ChildKeyA + rv[i].ChildKeyB = item.ChildKeyB + rv[i].TimestampMicro = int64(timestampMicro >> _TSB_UTIL_BITS) + rv[i].Value = value + i++ + } + } + atomic.AddInt32(&store.readGroupItems, int32(i)) + return rv[:i], nil +} {{end}} func (store *default{{.T}}Store) Read(keyA uint64, keyB uint64{{if eq .t "group"}}, childKeyA uint64, childKeyB uint64{{end}}, value []byte) (int64, []byte, error) { diff --git a/valuestore_GEN_.go b/valuestore_GEN_.go index <HASH>..<HASH> 100644 --- a/valuestore_GEN_.go +++ b/valuestore_GEN_.go @@ -82,6 +82,8 @@ type defaultValueStore struct { lookupGroupItems int32 reads int32 readErrors int32 + readGroups int32 + readGroupItems int32 writes int32 writeErrors int32 writesOverridden int32
Added ReadGroup, though I normally wouldn't rec... Added ReadGroup, though I normally wouldn't recommend using this default implementation as it will allocate memory for all the values that could be done more efficiently depending on your use case.
gholt_store
train
4bfe8e2f79c19ce0a840d1810b8fbc483941d37d
diff --git a/src/Common/Select.php b/src/Common/Select.php index <HASH>..<HASH> 100644 --- a/src/Common/Select.php +++ b/src/Common/Select.php @@ -273,7 +273,7 @@ class Select extends AbstractQuery implements SelectInterface, SubselectInterfac * * @param string $alias The column to remove * - * @return boolean + * @return bool * */ public function removeCol($alias)
change return type from boolean to bool
auraphp_Aura.SqlQuery
train
186a1f12095260208ea15d2829a5ac90aaa3ca80
diff --git a/util/parser/expression_test.go b/util/parser/expression_test.go index <HASH>..<HASH> 100644 --- a/util/parser/expression_test.go +++ b/util/parser/expression_test.go @@ -14,10 +14,19 @@ package parser import ( + "testing" + . "github.com/pingcap/check" "github.com/pingcap/tidb/ast" ) +func TestT(t *testing.T) { + CustomVerboseFlag = true + TestingT(t) +} + +var _ = Suite(&testParserSuite{}) + type testParserSuite struct{} func (s *testParserSuite) TestParseExpression(c *C) {
util: improve the test coverage (#<I>)
pingcap_tidb
train
1e5d906d2e0c9cd96d3a22325a8621aaec3f3800
diff --git a/src/search/FindBar.js b/src/search/FindBar.js index <HASH>..<HASH> 100644 --- a/src/search/FindBar.js +++ b/src/search/FindBar.js @@ -408,6 +408,10 @@ define(function (require, exports, module) { this.focusQuery(); }; + /** + * @private + * Shows the search History in dropdown. + */ FindBar.prototype.showSearchHints = function () { var self = this; this.$searchField = $("input#find-what"); diff --git a/test/spec/FindInFiles-test.js b/test/spec/FindInFiles-test.js index <HASH>..<HASH> 100644 --- a/test/spec/FindInFiles-test.js +++ b/test/spec/FindInFiles-test.js @@ -427,7 +427,7 @@ define(function (require, exports, module) { }); }); - it("should traverse through search history using up and down arrow keys", function () { + it("should traverse through search history using arrow down key", function () { var fileEntry = FileSystem.getFileForPath(testPath + "/foo.js"); openSearchBar(fileEntry); executeSearch("foo1"); @@ -439,11 +439,32 @@ define(function (require, exports, module) { runs(function () { var searchHistory = PreferencesManager.getViewState("searchHistory"); var $searchField = $("#find-what"); - SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_UP, "keydown", $searchField[0]); - expect($("#find-what").val()).toBe("foo4"); + + $("#find-what").val(""); SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_DOWN, "keydown", $searchField[0]); - expect($("#find-what").val()).toBe("foo5"); SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_DOWN, "keydown", $searchField[0]); + SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_RETURN, "keydown", $searchField[0]); + expect($("#find-what").val()).toBe("foo5"); + }); + }); + + it("should traverse through search history using arrow up key", function () { + var fileEntry = FileSystem.getFileForPath(testPath + "/foo.js"); + openSearchBar(fileEntry); + executeSearch("foo1"); + executeSearch("foo2"); + executeSearch("foo3"); + executeSearch("foo4"); + executeSearch("foo5"); + + runs(function () { + var searchHistory = PreferencesManager.getViewState("searchHistory"); + var $searchField = $("#find-what"); + + $("#find-what").val(""); + SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_UP, "keydown", $searchField[0]); + SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_UP, "keydown", $searchField[0]); + SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_RETURN, "keydown", $searchField[0]); expect($("#find-what").val()).toBe("foo1"); }); });
Added JSDocs and updated tests
adobe_brackets
train
95e57928f89ba5cce16a7a7dee1cde4981e57a8c
diff --git a/lib/app.js b/lib/app.js index <HASH>..<HASH> 100644 --- a/lib/app.js +++ b/lib/app.js @@ -29,6 +29,7 @@ var dataform = require("./dataForm"); var https = require('https'); var log = require('./log'); var moment = require('moment-timezone'); +var url = require('url'); var __theApp = null; @@ -410,6 +411,33 @@ setupViews: function(options) { app.set('view engine', 'html'); }, +saveCurrentNamedRoute: function() { + var app = this; + app.addListener('namedroutes-install-hook', function(routehooks) { + routehooks.push(function(route, name) { + var val = route['get']; + if (val) { + val.unshift(function(req, res, next){ + if (req.session.parentNamedRoute) { + res.locals.parentNamedRoute = req.session.parentNamedRoute; + } else { + var referer = req.get('Referer'); + // XXX should check hostname + var refererPath = referer && url.parse(referer).pathname; + if (refererPath && refererPath.indexOf(req.baseUrl) == 0) { + refererPath = refererPath.slice(req.baseUrl.length); + } + res.locals.parentNamedRoute = refererPath && req.app.get("namedRoutes").findPath(refererPath); + } + res.locals.currentNamedRoute = route; + return next(); + }); + } + return route; + }) + }); +}, + setupPrivateMode: function(){ var app = this; if (!app.config.privatemode || app.config.privatemode.disable) @@ -655,6 +683,7 @@ function createApp(root, options) { ////////end initial middleware (see start() for more) ////////// app.setupPrivateMode(); + app.saveCurrentNamedRoute(); app.setupAccessControlPolicy(); app.createDefaultAdmin(); diff --git a/lib/namedroutes.js b/lib/namedroutes.js index <HASH>..<HASH> 100644 --- a/lib/namedroutes.js +++ b/lib/namedroutes.js @@ -1,4 +1,4 @@ -var _ = require('underscore'); +var _ = require('underscore'); var assert = require('assert'); var path = require('path'); @@ -44,7 +44,7 @@ function applyRoute(route, base, pre, name) { var app = route.app; assert(app); for (var key in route) { - if (key == "path" || key == 'app' || !app[key]) + if (key == "path" || key == 'app' || key == 'label' || !app[key]) continue; //call app.METHOD(path, ...route[METHOD]): app[key].apply(app, [path].concat(route[key])); @@ -82,6 +82,11 @@ NamedRoutes.prototype = { return update(app, this, source); }, + findPath: function(path) { + var key = _.findKey(this, {'path':path}); + return key ? this[key] : null; + }, + getUrlMap: function() { var PARAMREGEX = this.PARAMREGEX, PARAMREGEXG = new RegExp(PARAMREGEX.source, 'g'); @@ -122,6 +127,11 @@ NamedRoutes.prototype = { }; +function niceName(name) { + //insert space before cap + return name.charAt(0).toUpperCase() + name.slice(1).replace(/([a-z])([A-Z])/g, '$1 $2'); +} + /* If path is omitted the name of the route is used as the path If method is ommitted, GET is used @@ -129,10 +139,12 @@ If method is ommitted, GET is used function expandDefinition(app, name, route) { if (!route) return null; + var label = niceName(name); if (typeof route === 'function') { return { app: app, - get: [route] + get: [route], + label: label } } else if (Array.isArray(route)) { var path = undefined, funcs; @@ -145,14 +157,16 @@ function expandDefinition(app, name, route) { return { app: app, path: path, - get: funcs + get: funcs, + label: label } } else if (route.route) { //nested routes debugger; //XXX } else { var def = { app: app, - path: route.path + path: route.path, + label: route.label || label }; var found = false; for (var key in route) {
expose the current and parent named routes to views and let them have nice labels
onecommons_base
train
568b5a8da09b4d15667f0ad5fbd75a99b89d3440
diff --git a/lib/app.js b/lib/app.js index <HASH>..<HASH> 100644 --- a/lib/app.js +++ b/lib/app.js @@ -94,7 +94,7 @@ Object.getOwnPropertyNames(flattened).forEach(function (key) { }); // in live, we run behind a proxy - so this will give us our IPs again: http://expressjs.com/guide.html#proxies -if (process.env.NODE_ENV === app.PRODUCTION) { +if (process.env.NODE_ENV === app.PRODUCTION || process.env.JSBIN_PROXY) { app.enable('trust proxy'); } @@ -112,6 +112,7 @@ if (String(process.env.ALLOW_CLIENT_USER).toLowerCase() === 'true') { app.set('view engine', 'html'); app.set('views', path.join(app.set('root'), 'views')); app.set('url prefix', options.url.prefix); +app.set('url ssl', options.url.ssl); app.set('url full', (app.set('url ssl') ? 'https://' : 'http://') + app.set('url host') + app.set('url prefix')); app.set('basepath', app.set('url prefix'));
Detect SSL and alter URLs to match.
jsbin_jsbin
train
e7e32d13a3eef694e3795f3af1a224d526961e4a
diff --git a/tests/php/Security/MemberTest.php b/tests/php/Security/MemberTest.php index <HASH>..<HASH> 100644 --- a/tests/php/Security/MemberTest.php +++ b/tests/php/Security/MemberTest.php @@ -21,6 +21,7 @@ use SilverStripe\Security\Member_Validator; use SilverStripe\Security\MemberAuthenticator\MemberAuthenticator; use SilverStripe\Security\MemberAuthenticator\SessionAuthenticationHandler; use SilverStripe\Security\MemberPassword; +use SilverStripe\Security\PasswordEncryptor_Blowfish; use SilverStripe\Security\Permission; use SilverStripe\Security\RememberLoginHash; use SilverStripe\Security\Security; @@ -899,6 +900,8 @@ class MemberTest extends FunctionalTest public function testValidateAutoLoginToken() { + $enc = new PasswordEncryptor_Blowfish(); + $m1 = new Member(); $m1->PasswordEncryption = 'blowfish'; $m1->Salt = $enc->salt('123');
FIX Add namespace and encryptor to tests that expect blowfish to be available
silverstripe_silverstripe-framework
train
c01875bd5d9104bdd703d086f64e8e632ee28212
diff --git a/spec/ey/deploy_spec.rb b/spec/ey/deploy_spec.rb index <HASH>..<HASH> 100644 --- a/spec/ey/deploy_spec.rb +++ b/spec/ey/deploy_spec.rb @@ -197,9 +197,17 @@ describe "ey deploy" do context "specifying the application" do before(:all) do api_scenario "one app, one environment" + end + + before(:each) do + @_deploy_spec_start_dir = Dir.getwd Dir.chdir(File.expand_path("~")) end + after(:each) do + Dir.chdir(@_deploy_spec_start_dir) + end + it "allows you to specify an app when not in a directory" do ey "deploy --app rails232app --ref master" @ssh_commands.last.should match(/--app rails232app/) @@ -212,16 +220,21 @@ describe "ey deploy" do end end - it "passes along the repository URL to eysd" do - api_scenario "one app, one environment", "user@git.host:path/to/repo.git" - ey "deploy" - @ssh_commands.last.should =~ /--repo user@git.host:path\/to\/repo.git/ - end + context "sending necessary information" do + use_git_repo("deploy test") - it "passes along the web server stack to eysd" do - api_scenario "one app, one environment" - ey "deploy" - @ssh_commands.last.should =~ /--stack nginx_mongrel/ - end + before(:all) do + api_scenario "one app, one environment", "user@git.host:path/to/repo.git" + ey "deploy" + @deploy_command = @ssh_commands.find {|c| c =~ /eysd deploy/ } + end + it "passes along the repository URL to eysd" do + @deploy_command.should =~ /--repo user@git.host:path\/to\/repo.git/ + end + + it "passes along the web server stack to eysd" do + @deploy_command.should =~ /--stack nginx_mongrel/ + end + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -14,6 +14,19 @@ end require 'fakeweb' require 'fakeweb_matcher' require 'fakefs/safe' +module FakeFS + def self.activated? + Object.const_get(:Dir) == FakeFS::Dir + end + + def self.without + was_on = activated? + deactivate! + yield + activate! if was_on + end +end + require 'json' # Engineyard gem diff --git a/spec/support/git_repo.rb b/spec/support/git_repo.rb index <HASH>..<HASH> 100644 --- a/spec/support/git_repo.rb +++ b/spec/support/git_repo.rb @@ -3,19 +3,22 @@ module Spec def define_git_repo(name, &setup) # EY's ivars don't get cleared between examples, so we can keep # a git repo around longer (and thus make our tests faster) - EY.define_git_repo(name, &setup) + FakeFS.without { EY.define_git_repo(name, &setup) } end def use_git_repo(repo_name) - before(:each) do - @_original_wd ||= [] - @_original_wd << Dir.getwd - Dir.chdir(EY.git_repo_dir(repo_name)) + before(:all) do + FakeFS.without do + @_original_wd ||= [] + @_original_wd << Dir.getwd + Dir.chdir(EY.git_repo_dir(repo_name)) + end end - after(:each) do - Dir.chdir(@_original_wd.pop) + after(:all) do + FakeFS.without { Dir.chdir(@_original_wd.pop) } end end + end end diff --git a/spec/support/helpers.rb b/spec/support/helpers.rb index <HASH>..<HASH> 100644 --- a/spec/support/helpers.rb +++ b/spec/support/helpers.rb @@ -128,10 +128,10 @@ module EY class << self def fake_awsm @fake_awsm ||= begin - unless system("ruby -c spec/support/fake_awsm.ru > /dev/null") + config_ru = File.join(EY_ROOT, "spec/support/fake_awsm.ru") + unless system("ruby -c '#{config_ru}' > /dev/null") raise SyntaxError, "There is a syntax error in fake_awsm.ru! fix it!" end - config_ru = File.join(EY_ROOT, "spec/support/fake_awsm.ru") @server = RealWeb.start_server_in_fork(config_ru) "http://localhost:#{@server.port}" end
Add ability to run integration test in a before(:all). This lets you run e.g. ey "deploy" in a before(:all) and then assert different things about the results in different examples. Used this to save one run of bundled_ey in spec/ey/deploy_spec.rb.
engineyard_engineyard
train
2ffbf43c963d05e113e7508149ecb0d63e74a6f1
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,11 @@ Changelog ######### ---- +0.17 +---- +* ``write_raster_window`` now returns a ``rasterio.MemoryFile()`` if path is ``"memoryfile"`` + +---- 0.16 ---- * added ``TileDirectory`` as additional input option (#89) diff --git a/mapchete/__init__.py b/mapchete/__init__.py index <HASH>..<HASH> 100644 --- a/mapchete/__init__.py +++ b/mapchete/__init__.py @@ -39,7 +39,7 @@ LOGGER = logging.getLogger(__name__) logging.getLogger("rasterio").setLevel(logging.ERROR) -__version__ = "0.16" +__version__ = "0.17" def open( diff --git a/mapchete/io/raster.py b/mapchete/io/raster.py index <HASH>..<HASH> 100644 --- a/mapchete/io/raster.py +++ b/mapchete/io/raster.py @@ -199,7 +199,8 @@ def write_raster_window( out_tile : ``Tile`` provides output boundaries; if None, in_tile is used out_path : string - output path + output path to write to; if output path is "memoryfile", a + rasterio.MemoryFile() is returned """ out_tile = in_tile if out_tile is None else out_tile for t in [in_tile, out_tile]: @@ -216,11 +217,21 @@ def write_raster_window( in_affine=in_tile.affine, out_tile=out_tile ) + # use transform instead of affine + if "affine" in out_profile: + out_profile["transform"] = out_profile.pop("affine") # write if there is any band with non-masked data if window_data.all() is not ma.masked: - with rasterio.open(out_path, 'w', **out_profile) as dst: - for band, data in enumerate(window_data): - dst.write(data.astype(out_profile["dtype"]), band+1) + if out_path == "memoryfile": + memfile = MemoryFile() + with memfile.open(**out_profile) as dst: + for band, data in enumerate(window_data): + dst.write(data.astype(out_profile["dtype"]), band+1) + return memfile + else: + with rasterio.open(out_path, 'w', **out_profile) as dst: + for band, data in enumerate(window_data): + dst.write(data.astype(out_profile["dtype"]), band+1) def extract_from_array(in_raster=None, in_affine=None, out_tile=None): diff --git a/test/test_io.py b/test/test_io.py index <HASH>..<HASH> 100644 --- a/test/test_io.py +++ b/test/test_io.py @@ -171,11 +171,43 @@ def test_write_raster_window(): assert src.shape == out_tile.shape assert src.read().any() assert src.meta["driver"] == out_profile["driver"] - assert src.transform == out_profile["affine"] + assert src.transform == out_profile["transform"] finally: shutil.rmtree(path, ignore_errors=True) +def test_write_raster_window_memory(): + """Basic output format writing.""" + path = "memoryfile" + # standard tile + tp = BufferedTilePyramid("geodetic") + tile = tp.tile(5, 5, 5) + data = ma.masked_array(np.ones((2, ) + tile.shape)) + for out_profile in [ + dict( + driver="GTiff", count=2, dtype="uint8", compress="lzw", nodata=0, + height=tile.height, width=tile.width, affine=tile.affine), + dict( + driver="GTiff", count=2, dtype="uint8", compress="deflate", + nodata=0, height=tile.height, width=tile.width, + affine=tile.affine), + dict( + driver="PNG", count=2, dtype="uint8", nodata=0, height=tile.height, + width=tile.width, compress=None, affine=tile.affine), + ]: + memfile = write_raster_window( + in_tile=tile, in_data=data, out_profile=out_profile, out_path=path) + # with rasterio.open(memfile, 'r') as src: + with memfile.open() as src: + assert src.read().any() + assert src.meta["driver"] == out_profile["driver"] + assert src.transform == tile.affine + if out_profile["compress"]: + assert src.compression == Compression( + out_profile["compress"].upper()) + memfile.close() + + def test_write_raster_window_errors(): """Basic output format writing.""" tile = BufferedTilePyramid("geodetic").tile(5, 5, 5)
enhance write_raster_window() with rasterio.MemoryFile()
ungarj_mapchete
train
d01162293034e2335f7d8dbd25e853d7e5135703
diff --git a/src/test/java/io/github/bonigarcia/wdm/test/PhantomJsBetaTest.java b/src/test/java/io/github/bonigarcia/wdm/test/PhantomJsBetaTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/github/bonigarcia/wdm/test/PhantomJsBetaTest.java +++ b/src/test/java/io/github/bonigarcia/wdm/test/PhantomJsBetaTest.java @@ -14,22 +14,25 @@ */ package io.github.bonigarcia.wdm.test; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; +import org.junit.Test; +import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import io.github.bonigarcia.wdm.PhantomJsDriverManager; -import io.github.bonigarcia.wdm.base.BaseBrowserTst; /** - * Test with PhatomJS. + * Test with PhatomJS beta. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ -@Ignore -public class PhantomJsBetaTest extends BaseBrowserTst { +public class PhantomJsBetaTest { @BeforeClass public static void setupClass() { @@ -41,4 +44,19 @@ public class PhantomJsBetaTest extends BaseBrowserTst { driver = new PhantomJSDriver(); } + protected WebDriver driver; + + @After + public void teardown() { + if (driver != null) { + driver.quit(); + } + } + + @Test + public void testPhantomBeta() { + String binaryPath = PhantomJsDriverManager.getInstance() + .getBinaryPath(); + assertThat(binaryPath, notNullValue()); + } }
Activate PhantomJS with beta version
bonigarcia_webdrivermanager
train
d49cf57339ef82626674299f9e058d00dade468c
diff --git a/lib/origen/sub_blocks.rb b/lib/origen/sub_blocks.rb index <HASH>..<HASH> 100644 --- a/lib/origen/sub_blocks.rb +++ b/lib/origen/sub_blocks.rb @@ -329,14 +329,32 @@ module Origen # creates an array referenced by method called 'my_ip_group' # which contains the sub_blocks 'ip0', 'ip1', 'ip2', 'ip3'. # + # Can also indicate a custom class container to hold these. + # This custom class container MUST support a '<<' method in + # order to add new sub_blocks to the container instance. + # + # e.g. + # sub_block_group :my_ip_group, class_name: 'MYGRP' do + # sub_block :ip0, class_name: 'IP0', base_address: 0x000000 + # sub_block :ip1, class_name: 'IP1', base_address: 0x000200 + # sub_block :ip2, class_name: 'IP2', base_address: 0x000400 + # sub_block :ip3, class_name: 'IP3', base_address: 0x000600 + # end + # + # def sub_block_group(id, options = {}) @current_group = [] # open group yield # any sub_block calls within this block will have their ID added to @current_group - b = [] - @current_group.each do |group_id| - b << send(group_id) # instantiate the sub_block here, as created lazily above - end + my_group = @current_group.dup define_singleton_method "#{id}" do + if options[:class_name] + b = Object.const_get(options[:class_name]).new + else + b = [] + end + my_group.each do |group_id| + b << send(group_id) + end b # return array inside new singleton method end @current_group = nil # close group
Updated to support custom container class for sub_block_group method.
Origen-SDK_origen
train
061921afaec8884843dbb7cd5cc9dd34202a1f63
diff --git a/src/State.php b/src/State.php index <HASH>..<HASH> 100644 --- a/src/State.php +++ b/src/State.php @@ -6,6 +6,7 @@ use Exception; use ReflectionMethod; use ReflectionFunction; use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; use Zend\Diactoros\Response\HtmlResponse; use Zend\Diactoros\Response\EmptyResponse; @@ -40,11 +41,10 @@ class State * @param null|string The (preferably unique) name of the state. * @param mixed $state A valid state. */ - public function __construct($name, $state) + public function __construct($name) { $this->name = $name; - $state = $this->makeCallable($state); - $this->actions = ['GET' => $state, 'POST' => $state]; + $this->actions = ['GET' => new EmptyResponse(200), 'POST' => new EmptyResponse(200)]; } /** @@ -53,7 +53,7 @@ class State * * @param array $arguments All matched URL parameters. * @param Psr\Http\Message\RequestInterface $request The current request. - * @return mixed Whatever the state eventually resolves to. + * @return Psr\Http\Message\ReponseInterface */ public function __invoke(array $arguments, RequestInterface $request) { @@ -82,6 +82,9 @@ class State } $call = call_user_func_array($call, $args); } while (is_callable($call)); + if (!($call instanceof ResponseInterface)) { + $call = new HtmlResponse($call); + } return $call; }
fix some shizzle for v4
monolyth-php_reroute
train
0091669fbd856049fd32e24037eb39c97180876a
diff --git a/gmail/mailbox.py b/gmail/mailbox.py index <HASH>..<HASH> 100644 --- a/gmail/mailbox.py +++ b/gmail/mailbox.py @@ -9,6 +9,7 @@ class Mailbox(): # TODO: utf-7 encode mailbox name self.external_name = encode_utf7(name) self.gmail = gmail + self.date_format = "%d-%b-%Y" self.messages = {} @@ -27,9 +28,9 @@ class Mailbox(): kwargs.get('draft') and search.append('DRAFT') kwargs.get('undraft') and search.append('UNDRAFT') - kwargs.get('before') and search.extend(['BEFORE', kwargs.get('before').strftime("%d-%b-%Y")]) - kwargs.get('after') and search.extend(['SINCE', kwargs.get('after').strftime("%d-%b-%Y")]) - kwargs.get('on') and search.extend(['ON', kwargs.get('on').strftime("%d-%b-%Y")]) + kwargs.get('before') and search.extend(['BEFORE', kwargs.get('before').strftime(self.date_format)]) + kwargs.get('after') and search.extend(['SINCE', kwargs.get('after').strftime(self.date_format)]) + kwargs.get('on') and search.extend(['ON', kwargs.get('on').strftime(self.date_format)]) kwargs.get('sender') and search.extend(['FROM', kwargs.get('sender')]) kwargs.get('fr') and search.extend(['FROM', kwargs.get('fr')])
Define date format in class initialization
charlierguo_gmail
train
c697670e9bc3681571dfcdff38fe6b157afb99af
diff --git a/plugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/SARLProjectNewWizard.java b/plugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/SARLProjectNewWizard.java index <HASH>..<HASH> 100644 --- a/plugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/SARLProjectNewWizard.java +++ b/plugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/SARLProjectNewWizard.java @@ -3,6 +3,8 @@ */ package io.sarl.eclipse.wizards; +import io.sarl.eclipse.images.EclipseSARLImages; + import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; @@ -21,7 +23,6 @@ import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.JavaProjectWizard; @@ -42,6 +43,7 @@ import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; * Most part of the code of this class comes from {@link JavaProjectWizard} * * @author $Author: ngaud$ + * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ @@ -77,7 +79,8 @@ public class SARLProjectNewWizard extends NewElementWizard implements IExecutabl * @param pageTwo */ public SARLProjectNewWizard(NewSARLProjectWizardPageOne pageOne, NewSARLProjectWizardPageTwo pageTwo) { - setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ); + setDefaultPageImageDescriptor(EclipseSARLImages.getImageDescriptor( + EclipseSARLImages.NEW_PROJECT_WIZARD_DIALOG_IMAGE)); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(WIZARD_NAME);
Change the default page image in the "new SARL project" wizard.
sarl_sarl
train
2ae8ba750f65f8719b0f96d912aff1f8b2ece045
diff --git a/untwisted/iossl.py b/untwisted/iossl.py index <HASH>..<HASH> 100644 --- a/untwisted/iossl.py +++ b/untwisted/iossl.py @@ -1,4 +1,3 @@ -from untwisted.wrappers import xmap, zmap, spawn from untwisted.network import SSL from untwisted.event import CLOSE, SSL_CERTIFICATE_ERR, \ SSL_CONNECT_ERR, SSL_CONNECT, CONNECT_ERR @@ -13,7 +12,7 @@ import ssl def install_ssl_handles(con): StdinSSL(con) StdoutSSL(con) - xmap(con, CLOSE, lambda con, err: lose(con)) + con.add_map(CLOSE, lambda con, err: lose(con)) def create_client_ssl(addr, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -24,10 +23,10 @@ def create_client_ssl(addr, port): con.connect_ex((addr, port)) ClientSSL(con) - xmap(con, SSL_CONNECT, install_ssl_handles) - xmap(con, SSL_CONNECT_ERR, lambda con, err: lose(con)) - xmap(con, CONNECT_ERR, lambda con, err: lose(con)) - xmap(con, SSL_CERTIFICATE_ERR, lambda con, err: lose(con)) + con.add_map(SSL_CONNECT, install_ssl_handles) + con.add_map(SSL_CONNECT_ERR, lambda con, err: lose(con)) + con.add_map(CONNECT_ERR, lambda con, err: lose(con)) + con.add_map(SSL_CERTIFICATE_ERR, lambda con, err: lose(con)) return con def create_server_ssl(): @@ -41,3 +40,4 @@ def create_server_ssl(): +
Removing usage of xmap from iossl.py module.
untwisted_untwisted
train
5817cfd8bba0c42d98d1480c6334e11a2af1ad8b
diff --git a/src/ServiceFactory/SerializationServiceFactory.php b/src/ServiceFactory/SerializationServiceFactory.php index <HASH>..<HASH> 100644 --- a/src/ServiceFactory/SerializationServiceFactory.php +++ b/src/ServiceFactory/SerializationServiceFactory.php @@ -4,11 +4,11 @@ declare(strict_types=1); namespace Chubbyphp\Serialization\ServiceFactory; -use Chubbyphp\Container\ContainerInterface; use Chubbyphp\Serialization\Encoder\Encoder; use Chubbyphp\Serialization\Normalizer\Normalizer; use Chubbyphp\Serialization\Normalizer\NormalizerObjectMappingRegistry; use Chubbyphp\Serialization\Serializer; +use Psr\Container\ContainerInterface; final class SerializationServiceFactory {
Chubbyphp\Container\ContainerInterface => Psr\Container\ContainerInterface
chubbyphp_chubbyphp-serialization
train
16a23a184e8b091392c0b6001a025bee8323ec8e
diff --git a/activesupport/lib/active_support/testing/garbage_collection.rb b/activesupport/lib/active_support/testing/garbage_collection.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/testing/garbage_collection.rb +++ b/activesupport/lib/active_support/testing/garbage_collection.rb @@ -3,6 +3,9 @@ module ActiveSupport module GarbageCollection def self.included(base) base.teardown :scrub_leftover_instance_variables + + base.setup :begin_gc_deferment + base.teardown :reconsider_gc_deferment end private @@ -14,6 +17,27 @@ module ActiveSupport remove_instance_variable(var) end end + + # Minimum interval, in seconds, at which to run GC. Might be less + # frequently than this, if a single test takes longer than this to + # run. + DEFERRED_GC_THRESHOLD = (ENV['DEFERRED_GC_THRESHOLD'] || 1.0).to_f + + @@last_gc_run = Time.now + + def begin_gc_deferment + GC.disable if DEFERRED_GC_THRESHOLD > 0 + end + + def reconsider_gc_deferment + if DEFERRED_GC_THRESHOLD > 0 && Time.now - @@last_gc_run >= DEFERRED_GC_THRESHOLD + GC.enable + GC.start + GC.disable + + @@last_gc_run = Time.now + end + end end end end diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb index <HASH>..<HASH> 100644 --- a/activesupport/test/test_test.rb +++ b/activesupport/test/test_test.rb @@ -135,9 +135,9 @@ class SetupAndTeardownTest < ActiveSupport::TestCase teardown :foo, :sentinel, :foo def test_inherited_setup_callbacks - assert_equal [:reset_callback_record, :foo], self.class._setup_callbacks.map(&:raw_filter) + assert_equal [:begin_gc_deferment, :reset_callback_record, :foo], self.class._setup_callbacks.map(&:raw_filter) assert_equal [:foo], @called_back - assert_equal [:scrub_leftover_instance_variables, :foo, :sentinel, :foo], self.class._teardown_callbacks.map(&:raw_filter) + assert_equal [:scrub_leftover_instance_variables, :reconsider_gc_deferment, :foo, :sentinel, :foo], self.class._teardown_callbacks.map(&:raw_filter) end def setup @@ -167,9 +167,9 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest teardown :bar def test_inherited_setup_callbacks - assert_equal [:reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:raw_filter) + assert_equal [:begin_gc_deferment, :reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:raw_filter) assert_equal [:foo, :bar], @called_back - assert_equal [:scrub_leftover_instance_variables, :foo, :sentinel, :foo, :bar], self.class._teardown_callbacks.map(&:raw_filter) + assert_equal [:scrub_leftover_instance_variables, :reconsider_gc_deferment, :foo, :sentinel, :foo, :bar], self.class._teardown_callbacks.map(&:raw_filter) end protected
rein in GC during tests by making them run (at most) once per second this can provide a significant performance boost during testing, by preventing the GC from running too frequently.
rails_rails
train
1fbd54e3eb4cb596f31b5656b2e4b83f812aa653
diff --git a/src/crosstab.js b/src/crosstab.js index <HASH>..<HASH> 100644 --- a/src/crosstab.js +++ b/src/crosstab.js @@ -5,10 +5,13 @@ var crosstab = (function () { } // --- Utility --- - var MESSAGE_KEY = 'crosstab.MESSAGE_KEY'; - var TABS_KEY = 'crosstab.TABS_KEY'; - var MASTER_TAB = 'MASTER_TAB'; - var util = {}; + var util = { + keys: { + MESSAGE_KEY: 'crosstab.MESSAGE_KEY', + TABS_KEY: 'crosstab.TABS_KEY', + MASTER_TAB: 'MASTER_TAB' + } + }; util.forEachObj = function (thing, fn) { for (var key in thing) { @@ -172,7 +175,7 @@ var crosstab = (function () { // This is to force IE to behave properly return; } - if (event.key === MESSAGE_KEY) { + if (event.key === util.keys.MESSAGE_KEY) { var message = eventValue.data; // only handle if this message was meant for this tab. if (!message.destination || message.destination === crosstab.id) { @@ -204,7 +207,7 @@ var crosstab = (function () { function beforeUnload() { var numTabs = 0; util.forEach(util.tabs, function (tab, key) { - if (key !== MASTER_TAB) { + if (key !== util.keys.MASTER_TAB) { numTabs++; } }); @@ -232,7 +235,7 @@ var crosstab = (function () { // this is done so that in the case where multiple tabs are being // started at the same time, and there is no current saved tab // information, we will still have a value set for the master tab - util.tabs[MASTER_TAB] = { + util.tabs[util.keys.MASTER_TAB] = { id: madId, lastUpdated: util.now() }; @@ -247,14 +250,14 @@ var crosstab = (function () { delete util.tabs[id]; } - if (!util.tabs[MASTER_TAB] || util.tabs[MASTER_TAB].id === id) { + if (!util.tabs[util.keys.MASTER_TAB] || util.tabs[util.keys.MASTER_TAB].id === id) { // If the master was the closed tab, delete it and the highest // tab ID becomes the new master, which will save the tabs - if (util.tabs[MASTER_TAB]) { - delete util.tabs[MASTER_TAB]; + if (util.tabs[util.keys.MASTER_TAB]) { + delete util.tabs[util.keys.MASTER_TAB]; } masterTabElection(); - } else if (util.tabs[MASTER_TAB].id === crosstab.id) { + } else if (util.tabs[util.keys.MASTER_TAB].id === crosstab.id) { // If I am master, save the new tabs out setStoredTabs(); } @@ -265,14 +268,14 @@ var crosstab = (function () { util.tabs[tab.id] = tab; // If there is no master, hold an election - if (!util.tabs[MASTER_TAB]) { + if (!util.tabs[util.keys.MASTER_TAB]) { masterTabElection(); } - if (util.tabs[MASTER_TAB].id === tab.id) { - util.tabs[MASTER_TAB] = tab; + if (util.tabs[util.keys.MASTER_TAB].id === tab.id) { + util.tabs[util.keys.MASTER_TAB] = tab; } - if (util.tabs[MASTER_TAB].id === crosstab.id) { + if (util.tabs[util.keys.MASTER_TAB].id === crosstab.id) { // If I am master, save the new tabs out setStoredTabs(); } @@ -281,7 +284,7 @@ var crosstab = (function () { eventHandler.addListener(util.eventTypes.tabPromoted, function (message) { var id = message.data; var lastUpdated = message.timestamp; - util.tabs[MASTER_TAB] = { + util.tabs[util.keys.MASTER_TAB] = { id: id, lastUpdated: lastUpdated }; @@ -324,7 +327,7 @@ var crosstab = (function () { // If the destination differs from the origin send it out, otherwise // handle it locally if (message.destination !== message.origin) { - setLocalStorageItem(MESSAGE_KEY, message); + setLocalStorageItem(util.keys.MESSAGE_KEY, message); } if (!message.destination || message.destination === message.origin) { @@ -333,7 +336,7 @@ var crosstab = (function () { } function broadcastMaster(event, data) { - broadcast(event, data, util.tabs[MASTER_TAB].id); + broadcast(event, data, util.tabs[util.keys.MASTER_TAB].id); } // ---- Return ---- @@ -351,13 +354,13 @@ var crosstab = (function () { var TAB_TIMEOUT = 5 * 1000; function getStoredTabs() { - var storedTabs = getLocalStorageItem(TABS_KEY); + var storedTabs = getLocalStorageItem(util.keys.TABS_KEY); util.tabs = storedTabs || util.tabs || {}; return util.tabs; } function setStoredTabs() { - setLocalStorageItem(TABS_KEY, util.tabs); + setLocalStorageItem(util.keys.TABS_KEY, util.tabs); } function keepalive() { @@ -377,7 +380,7 @@ var crosstab = (function () { } function notAlive(tab, key) { - return key !== MASTER_TAB && !stillAlive(tab); + return key !== util.keys.MASTER_TAB && !stillAlive(tab); } var deadTabs = util.filter(util.tabs, notAlive);
Move key strings into util.keys so they can be used by other libraries.
tejacques_crosstab
train
cb18875d46a1bb6a1f63dbf682237a61db899f1d
diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/SasFilter.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/SasFilter.java index <HASH>..<HASH> 100644 --- a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/SasFilter.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/SasFilter.java @@ -43,9 +43,26 @@ public class SasFilter extends ClientFilter { public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - String targetUri; + String targetUri = cr.getURI().toString(); + + cr.getHeaders().remove("Authorization"); + cr.getHeaders().add("Authorization", createSignature(targetUri)); + + String secondaryAuthorizationUri = (String) cr.getHeaders().getFirst( + "ServiceBusSupplementaryAuthorization"); + if ((secondaryAuthorizationUri != null) + && (!secondaryAuthorizationUri.isEmpty())) { + cr.getHeaders().remove("ServiceBusSupplementaryAuthorization"); + cr.getHeaders().add("ServiceBusSupplementaryAuthorization", + createSignature(secondaryAuthorizationUri)); + } + + return this.getNext().handle(cr); + } + + private String createSignature(String targetUri) { try { - targetUri = URLEncoder.encode(cr.getURI().toString().toLowerCase(), "UTF-8").toLowerCase(); + targetUri = URLEncoder.encode(targetUri.toLowerCase(), "UTF-8").toLowerCase(); } catch (UnsupportedEncodingException e) { throw new ClientHandlerException(e); } @@ -56,30 +73,13 @@ public class SasFilter extends ClientFilter { String hmac; try { hmac = URLEncoder.encode(calculateHmac(signature), "UTF-8"); + return String.format("SharedAccessSignature sig=%s&se=%d&skn=%s&sr=%s", + hmac, expiration, this.key, targetUri); } catch (SignatureException e) { throw new ClientHandlerException(e); } catch (UnsupportedEncodingException e) { throw new ClientHandlerException(e); } - - cr.getHeaders().remove("Authorization"); - cr.getHeaders().add("Authorization", - String.format("SharedAccessSignature sig=%s&se=%d&skn=%s&sr=%s", hmac, expiration, this.key, targetUri)); - - return this.getNext().handle(cr); - - /*var targetUri = encodeURIComponent(webResource.uri.toLowerCase()).toLowerCase(); - - var expirationDate = Math.round(date.minutesFromNow(5) / 1000); - var signature = this._generateSignature(targetUri, expirationDate); - - webResource.withHeader(HeaderConstants.AUTHORIZATION, - util.format('SharedAccessSignature sig=%s&se=%s&skn=%s&sr=%s', signature, expirationDate, this.keyName, targetUri)); - - callback(null);*/ - - /*Date expiresUtc = new Date(now.getTime() + wrapResponse.getExpiresIn() - * Timer.ONE_SECOND / 2);*/ } private String valueToSign(String targetUri, int expiration) {
Implemented supplemental auth behavior in SAS filter.
Azure_azure-sdk-for-java
train
9abb31003c0a98c1465e3069f0cef11f3cc054ed
diff --git a/trashcli/trash.py b/trashcli/trash.py index <HASH>..<HASH> 100644 --- a/trashcli/trash.py +++ b/trashcli/trash.py @@ -887,18 +887,8 @@ class ListCmd: self.err = self.output.err self.contents_of = file_reader.contents_of self.version = version - class ListableTrashCan: - def __init__(self, environ, getuid, file_reader): - self.environ = environ - self.getuid = getuid - self.file_reader = file_reader - def list_all_trashinfos_by_volume(self, out): - trashdirs = TrashDirs(self.environ, self.getuid, - self.file_reader, list_volumes) - harvester = Harvester(trashdirs, self.file_reader) - harvester.list_all_trashinfos_by_volume(out) - - self.harvester = ListableTrashCan(environ, getuid, file_reader) + self.trashcan = ListableTrashCan(environ, getuid, file_reader, + list_volumes) def run(self, *argv): parse=Parser() @@ -912,8 +902,7 @@ class ListCmd: on_trashinfo = self._print_trashinfo top_trashdir_skipped_because_parent_not_sticky = self.output.top_trashdir_skipped_because_parent_not_sticky top_trashdir_skipped_because_parent_is_symlink = self.output.top_trashdir_skipped_because_parent_is_symlink - out = Log() - self.harvester.list_all_trashinfos_by_volume(out) + self.trashcan.list_all_trashinfos_by_volume(Log()) def _print_trashinfo(self, path): try: contents = self.contents_of(path) @@ -1044,6 +1033,18 @@ class ExpiryDate: def _delete_unconditionally(self, trashinfo_path): self._trashcan.delete_trashinfo_and_backup_copy(trashinfo_path) +class ListableTrashCan: + def __init__(self, environ, getuid, file_reader, list_volumes): + self.environ = environ + self.getuid = getuid + self.file_reader = file_reader + self.list_volumes = list_volumes + trashdirs = TrashDirs(self.environ, self.getuid, + self.file_reader, self.list_volumes) + self.harvester = Harvester(trashdirs, self.file_reader) + def list_all_trashinfos_by_volume(self, out): + self.harvester.list_all_trashinfos_by_volume(out) + class EmptyCmd: def __init__(self, out, err, environ, list_volumes, now = datetime.now,
Refactor: extracted ListableTrashCan
andreafrancia_trash-cli
train
d0c1a8a803abc7b1c806b7683224315e074d298a
diff --git a/lib/rack/mock_session.rb b/lib/rack/mock_session.rb index <HASH>..<HASH> 100644 --- a/lib/rack/mock_session.rb +++ b/lib/rack/mock_session.rb @@ -26,7 +26,7 @@ module Rack def request(uri, env) env['HTTP_COOKIE'] ||= cookie_jar.for(uri) @last_request = Rack::Request.new(env) - status, headers, body = @app.call(@last_request.env) + status, headers, body = @app.call(@last_request.env).to_a @last_response = MockResponse.new(status, headers, body, env['rack.errors'].flush) diff --git a/spec/rack/test_spec.rb b/spec/rack/test_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rack/test_spec.rb +++ b/spec/rack/test_spec.rb @@ -147,6 +147,15 @@ describe Rack::Test::Session do expect(last_request.env['rack.input'].read).to eq('foo[bar]=1') end + it 'supports a Rack::Response' do + app = lambda do |_env| + Rack::Response.new('', 200, {}) + end + + session = Rack::Test::Session.new(Rack::MockSession.new(app)) + expect(session.request('/')).to be_ok + end + context 'when the response body responds_to?(:close)' do class CloseableBody def initialize
Add compatibility with rack <I> (#<I>) Add support for Rack <I> by fixing a breaking change that affected users of rack-test: - Remove to_ary from Response (in <I>)
rack-test_rack-test
train
71ed45f95101610feff02a078d74c8fe4736e108
diff --git a/src/Model/Integration.php b/src/Model/Integration.php index <HASH>..<HASH> 100644 --- a/src/Model/Integration.php +++ b/src/Model/Integration.php @@ -101,9 +101,8 @@ class Integration extends ApiResourceBase { $response = $exception->getResponse(); if ($response && $response->getStatusCode() === 400) { - $response->getBody()->seek(0); - $data = $response->json(); - if (isset($data['detail']) && is_array($data['detail'])) { + $data = json_decode($response->getBody()->__toString(), true); + if ($data !== null && isset($data['detail']) && is_array($data['detail'])) { return $data['detail']; } }
Fix undefined method $response->json() in integration validation
platformsh_platformsh-client-php
train
69afd8a2800ff69d7002949d44222d7ba52d415c
diff --git a/src/view/items/Interpolator.js b/src/view/items/Interpolator.js index <HASH>..<HASH> 100755 --- a/src/view/items/Interpolator.js +++ b/src/view/items/Interpolator.js @@ -25,7 +25,7 @@ export default class Interpolator extends Mustache { render(target, occupants) { if (inAttributes()) return; - const value = this.getString(); + const value = (this.value = this.getString()); this.rendered = true; @@ -46,7 +46,8 @@ export default class Interpolator extends Mustache { if (this.dirty) { this.dirty = false; if (this.rendered) { - this.node.data = this.getString(); + const value = this.getString(); + if (value !== this.value) this.node.data = this.value = value; } } }
only update interpolator text nodes if the value has actually changed
ractivejs_ractive
train
b6e0b90a8bdbdffc9f5466691497bafdf453553f
diff --git a/TODO b/TODO index <HASH>..<HASH> 100644 --- a/TODO +++ b/TODO @@ -1,13 +1,3 @@ -Implement __hash__ method for BigFloats ---------------------------------------- - This is a little tricky: - - if the BigFloat is an integer, its hash should match that of the integer - - if the BigFloat is exactly representable as a float, its hash should match - that of the float - - equal BigFloats (e.g., with different precisions but the same value) - should hash equal. Perhaps compute the hex string representation, - remove trailing zeros, and get the hash of the result? - Implement floordiv method for BigFloats --------------------------------------- x // y should behave as with any other operation or function, though diff --git a/bigfloat/__init__.py b/bigfloat/__init__.py index <HASH>..<HASH> 100644 --- a/bigfloat/__init__.py +++ b/bigfloat/__init__.py @@ -58,10 +58,11 @@ from pympfr import MPFR_EMAX_MAX, MPFR_EMAX_MIN, MPFR_EMAX_DEFAULT from pympfr import standard_functions, predicates, extra_standard_functions from pympfr import eminmax -# builtin max and min functions are shadowed by BigFloat max and min -# functions later on +# builtin max, min and pow functions are shadowed by BigFloat max, min +# and pow functions later on _builtin_max = max _builtin_min = min +_builtin_pow = pow try: DBL_PRECISION = sys.float_info.mant_dig @@ -514,6 +515,36 @@ class BigFloat(object): """ return mpfr.mpfr_get_d(self._value, 'RoundTiesToEven') + def __hash__(self): + # if self is exactly representable as a float, then its hash + # should match that of the float. Note that this covers the + # case where self == 0. + if self == float(self) or is_nan(self): + return hash(float(self)) + + # now we must ensure that hash(self) == hash(int(self)) in the + # case where self is integral. We use the (undocumented) fact + # that hash(n) == hash(m) for any two nonzero integers n and m + # that are congruent modulo 2**64-1 and have the same sign: + # see the source for long_hash in Objects/longobject.c. An + # alternative would be to convert an integral self to an + # integer and take the hash of that, but that would be + # painfully slow for something like BigFloat('1e1000000000'). + negative, digits, e = mpfr.mpfr_get_str2(self._value, 16, 0, + 'RoundTiesToEven') + e -= len(digits) + # The value of self is (-1)**negative * int(digits, 16) * + # 16**e. Compute a strictly positive integer n such that n is + # congruent to abs(self) modulo 2**64-1 (e.g., in the sense + # that the numerator of n - abs(self) is divisible by + # 2**64-1). + + if e >= 0: + n = int(digits, 16)*_builtin_pow(16, e, 2**64-1) + else: + n = int(digits, 16)*_builtin_pow(2**60, -e, 2**64-1) + return hash(-n if negative else n) + def as_integer_ratio(self): """Return pair n, d of integers such that the value of self is exactly equal to n/d, n and d are relatively prime, and d >= 1. diff --git a/test/test_bigfloat.py b/test/test_bigfloat.py index <HASH>..<HASH> 100644 --- a/test/test_bigfloat.py +++ b/test/test_bigfloat.py @@ -529,6 +529,42 @@ class BigFloatTests(unittest.TestCase): self.assertEqual(float(x), 1.) self.assertEqual(float(y), 1.) + def test_hash(self): + # equal values should hash equal + pos0 = BigFloat('0') + neg0 = BigFloat('-0') + self.assertEqual(hash(pos0), hash(neg0)) + + # hash shouldn't depend on precision + with precision(200): + x1 = BigFloat(123456) + with precision(11): + x2 = BigFloat(123456) + with precision(53): + x3 = BigFloat(123456) + self.assertEqual(hash(x1), hash(x2)) + self.assertEqual(hash(x1), hash(x3)) + + # check that hash(n) matches hash(BigFloat(n)) for integers n + for n in range(-50, 50): + self.assertEqual(hash(n), hash(BigFloat.exact(n))) + + # values near powers of 2 + for e in [30, 31, 32, 33, 34, 62, 63, 64, 65, 66]: + for n in range(2**e-50, 2**e+50): + self.assertEqual(hash(n), hash(BigFloat.exact(n))) + self.assertEqual(hash(BigFloat(n)), hash(int(BigFloat(n)))) + + # check that hash values match those of floats + self.assertEqual(hash(BigFloat('inf')), hash(float('inf'))) + self.assertEqual(hash(BigFloat('-inf')), hash(float('-inf'))) + self.assertEqual(hash(BigFloat('0')), hash(float('0'))) + self.assertEqual(hash(BigFloat('-0')), hash(float('-0'))) + self.assertEqual(hash(BigFloat('1')), hash(float('1'))) + self.assertEqual(hash(BigFloat('-1')), hash(float('-1'))) + self.assertEqual(hash(BigFloat('1.625')), hash(float('1.625'))) + self.assertEqual(hash(BigFloat.exact(1.1)), hash(1.1)) + def test_int(self): # test conversion to int self.assertEqual(int(BigFloat(13.7)), 13)
Implement __hash__ for BigFloats
mdickinson_bigfloat
train
87a4321547d338425fa9e29c896f540cef2ae208
diff --git a/tests/unit/data/observatory/enrichment/test_polygon_enrichment.py b/tests/unit/data/observatory/enrichment/test_polygon_enrichment.py index <HASH>..<HASH> 100644 --- a/tests/unit/data/observatory/enrichment/test_polygon_enrichment.py +++ b/tests/unit/data/observatory/enrichment/test_polygon_enrichment.py @@ -719,10 +719,10 @@ def _clean_query(query): def _get_query(agg, columns, username, view, geo_table, temp_table_name, filters=[]): if agg: - columns = _build_polygons_query_variables_with_aggregation(_GEOM_COLUMN, columns, agg) + columns = _build_polygons_query_variables_with_aggregation(columns, agg) group = 'group by data_table.enrichment_id' else: - columns = _build_polygons_query_variables_without_aggregation(_GEOM_COLUMN, columns) + columns = _build_polygons_query_variables_without_aggregation(columns) group = '' return '''
rm needless enrichment_id and geom_column props from tests
CartoDB_cartoframes
train
957fe6d63bf288079e0211384ecf76a7a23ec456
diff --git a/spec/error_reporters/rollbar_spec.rb b/spec/error_reporters/rollbar_spec.rb index <HASH>..<HASH> 100644 --- a/spec/error_reporters/rollbar_spec.rb +++ b/spec/error_reporters/rollbar_spec.rb @@ -41,6 +41,10 @@ describe Pliny::ErrorReporters::Rollbar do context "given an empty rack_env" do let(:rack_env) { {} } + it "expects rack_env to be a hash" do + assert_kind_of(Hash, rack_env) + end + it "reports to Rollbar with an empty scope" do notify expect(Rollbar).to have_received(:scoped).once.with({})
Document that rack_env must be a Hash
interagent_pliny
train
7a618f69897b5702116484f08dad9687d326101f
diff --git a/js/browser/keystrokeManager.js b/js/browser/keystrokeManager.js index <HASH>..<HASH> 100644 --- a/js/browser/keystrokeManager.js +++ b/js/browser/keystrokeManager.js @@ -6,16 +6,18 @@ exports = Singleton(function(){ this.init = function() { events.add(window, 'keypress', bind(this, '_onKeyPress')); + this._handlerStack = []; } this.requestFocus = function(handler) { + if (this._keystrokeHandler) { this._handlerStack.push(this._keystrokeHandler); } this._keystrokeHandler = handler; return this._keystrokeHandler; } this.release = function(handler) { if (handler != this._keystrokeHandler) { return; } - this._keystrokeHandler = null; + this._keystrokeHandler = this._handlerStack.pop(); } this.handleKeys = function(keyMap) {
Maintain an internal stack of keystroke handlers - when blurring the element with current control, return to the previous element with keystroke control
marcuswestin_fin
train
fab55f1f7ee733a896ea2d95d69cb747dcea4949
diff --git a/tests/phpunit/unit/Logger/ChangeLogTest.php b/tests/phpunit/unit/Logger/ChangeLogTest.php index <HASH>..<HASH> 100644 --- a/tests/phpunit/unit/Logger/ChangeLogTest.php +++ b/tests/phpunit/unit/Logger/ChangeLogTest.php @@ -1,7 +1,6 @@ <?php namespace Bolt\Tests\Logger; -use Bolt\Logger\ChangeLog; use Bolt\Storage; use Bolt\Tests\BoltUnitTest; use Symfony\Component\HttpFoundation\Request; @@ -15,11 +14,14 @@ class ChangeLogTest extends BoltUnitTest { public function setUp() { + $this->resetDb(); $app = $this->getApp(); $app['config']->set('general/changelog/enabled', true); + $this->addSomeContent(); $storage = new Storage($app); $content = $storage->getContentObject('pages'); + $content['contentid'] = 1; $storage->saveContent($content, 'pages'); } @@ -56,8 +58,7 @@ class ChangeLogTest extends BoltUnitTest $count = $this->getLogChangeRepository()->countChangeLogByContentType('pages', ['contentid' => 1]); $this->assertGreaterThan(0, $count); - - $count = $this->getLogChangeRepository()->countChangeLogByContentType('pages', ['id' => 1]); + $count = $this->getLogChangeRepository()->countChangeLogByContentType('pages', ['ownerid' => 1]); $this->assertGreaterThan(0, $count); }
[Tests] Reset the database for change logging tests
bolt_bolt
train
9f52a7b0fe74276a1cff28ac1ca62596fc0c9c8e
diff --git a/core/core.js b/core/core.js index <HASH>..<HASH> 100644 --- a/core/core.js +++ b/core/core.js @@ -442,6 +442,25 @@ exports._setup = function() { return (new Color(spec)).get() } + /** @constructor */ + var DelayedAction = function(action) { + this.action = function() { + this.timeout = undefined + action() + }.bind(this) + } + _globals.core.DelayedAction = DelayedAction + + DelayedAction.prototype.constructor = DelayedAction + + DelayedAction.prototype.schedule = function() { + if (this.timeout !== undefined) + return false + + this.timeout = setTimeout(this.action, 0) + return true + } + _globals.core.Color.prototype.get = function() { return "rgba(" + this.r + "," + this.g + "," + this.b + "," + (this.a / 255) + ")"; }
added qml.core.DelayedAction
pureqml_qmlcore
train
fd4827b25feb11a7273edadfd231a37f02fd87cb
diff --git a/openquake/nrmllib/record.py b/openquake/nrmllib/record.py index <HASH>..<HASH> 100644 --- a/openquake/nrmllib/record.py +++ b/openquake/nrmllib/record.py @@ -178,26 +178,30 @@ class Record(collections.Sequence): def init(self): """To override for post-initialization operations""" - def is_valid(self): - """True if all fields are valid""" - return all(self.check_valid()) - - def check_valid(self): - """Returns a namedtuple of booleans, one for each fields""" - status = {} - for col, field in zip(self.row, self.fields): - try: - field.converter(col) - except ValueError: - status[field.name] = False - else: - status[field.name] = True - return self._ntuple(**status) + def is_valid(self, i=None): + """ + True if the fields `i` is valid; if `i` is None, check all the fields + """ + if i is None: + return all(self.is_valid(i) for i in range(len(self))) + if isinstance(i, str): + i = self._name2index[i] + try: + self.fields[i].converter(self[i]) + except ValueError: + return False + return True def cast(self): """Cast the record into a namedtuple by casting all of the field""" - return self._ntuple._make( - field.converter(col) for col, field in zip(self.row, self.fields)) + cols = [] + for col, field in zip(self.row, self.fields): + try: + cols.append(field.converter(col)) + except ValueError as e: + raise ValueError('Invalid %s.%s: %s' % + (self.__class__.__name__, field.name, e)) + return self._ntuple._make(cols) def to_node(self): """Implement this if you want to convert records into Node objects""" @@ -330,6 +334,19 @@ class Table(collections.MutableSequence): """True if all the records in the table are valid""" return all(rec.is_valid() for rec in self) + def cast(self): + """ + Cast all the rows in the table to namedtuples; + raise a ValueError at the first invalid record + """ + rows = [] + for i, rec in enumerate(self): + try: + rows.append(rec.cast()) + except ValueError as e: + raise ValueError('At row %d: %s' % (i, e)) + return rows + def __str__(self): """CSV representation of the whole table""" return '\n'.join(map(str, self)) diff --git a/tests/csvmanager_test.py b/tests/csvmanager_test.py index <HASH>..<HASH> 100644 --- a/tests/csvmanager_test.py +++ b/tests/csvmanager_test.py @@ -53,3 +53,11 @@ class TableTestCase(unittest.TestCase): with self.assertRaises(MultipleConverterError): man._getconverter() # the case NotInArchive is convered in convert_test.py + + def test_is_valid(self): + tbl = create_table(records.Location, '1,190.0,2.0') + with self.assertRaises(ValueError) as ctxt: + tbl.cast() + self.assertEqual( + str(ctxt.exception), + 'At row 0: Invalid Location.lon: longitude 190.0 > 180')
Added a .cast method at table level
gem_oq-engine
train
e3bd53230f2f3ebaa308953f6f5935704254e1c9
diff --git a/modules/cms/classes/MediaLibrary.php b/modules/cms/classes/MediaLibrary.php index <HASH>..<HASH> 100644 --- a/modules/cms/classes/MediaLibrary.php +++ b/modules/cms/classes/MediaLibrary.php @@ -64,8 +64,6 @@ class MediaLibrary if (!preg_match("/(\/\/|http|https)/", $this->storagePath)) { $this->storagePath = Request::getBasePath() . $this->storagePath; - } else { - $this->storagePath .= '/'; } $this->ignoreNames = Config::get('cms.storage.media.ignore', $this->defaultIgnoreNames);
Revert breaking from #<I>
octobercms_october
train
5337c403d0a00dd68335228839eff5247531b848
diff --git a/src/pointerEvents.js b/src/pointerEvents.js index <HASH>..<HASH> 100644 --- a/src/pointerEvents.js +++ b/src/pointerEvents.js @@ -1,5 +1,4 @@ const scope = require('./scope'); -const InteractEvent = require('./InteractEvent'); const Interaction = require('./Interaction'); const utils = require('./utils'); const browser = require('./utils/browser'); @@ -11,6 +10,14 @@ function preventOriginalDefault () { this.originalEvent.preventDefault(); } +function stopImmediatePropagation () { + this.immediatePropagationStopped = this.propagationStopped = true; +} + +function stopPropagation () { + this.propagationStopped = true; +} + function firePointers (interaction, pointer, event, eventTarget, targets, elements, eventType) { const pointerIndex = interaction.mouse? 0 : utils.indexOf(interaction.pointerIds, utils.getPointerId(pointer)); let pointerEvent = {}; @@ -31,8 +38,8 @@ function firePointers (interaction, pointer, event, eventTarget, targets, elemen } pointerEvent.preventDefault = preventOriginalDefault; - pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation; - pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation; + pointerEvent.stopPropagation = stopPropagation; + pointerEvent.stopImmediatePropagation = stopImmediatePropagation; pointerEvent.interaction = interaction; pointerEvent.timeStamp = new Date().getTime();
pointerEvents: remove dependence on InteractEvent
taye_interact.js
train
8f059d674c5e4f8809f2e3d3ea587b76f217be30
diff --git a/packages/server-socket/src/command-processor.js b/packages/server-socket/src/command-processor.js index <HASH>..<HASH> 100644 --- a/packages/server-socket/src/command-processor.js +++ b/packages/server-socket/src/command-processor.js @@ -14,7 +14,7 @@ function processCommand({ Event, User, logger }) { const eventCreateData = { ...helpers, data: { ...command.data, labels, trackedTimes } }; switch (command.command) { case "ADD_TODO": - return createEvent({ ...eventCreateData, eventType: "ADDED_TODO" }); + return createAddedTodoEvents({ helpers, data: eventCreateData.data }); case "REMOVE_TODO": return createEvent({ ...eventCreateData, eventType: "REMOVED_TODO" }); case "CHANGE_TODO": @@ -34,6 +34,28 @@ function processCommand({ Event, User, logger }) { }; } +async function createAddedTodoEvents({ helpers, data }) { + const labels = setUndefined({ data }, "labels"); + const trackedTimes = setUndefined({ data }, "trackedTimes"); + const parent = await createEvent({ + ...helpers, + data: { ...data, labels, trackedTimes }, + eventType: "ADDED_TODO" + }); + if (data.children) { + const parentId = parent.data.todoId; + return await data.children.reduce(async (p, child) => { + const acc = await p; + const data = { ...child, parentId }; + const labels = setUndefined({ data }, "labels"); + const trackedTimes = setUndefined({ data }, "trackedTimes"); + return [...acc, ...(await createAddedTodoEvents({ helpers, data: { ...data, labels, trackedTimes }, parentId }))]; + }, Promise.resolve([parent])); + } else { + return [parent]; + } +} + function setUndefined(command, fieldName) { // We have to actively set array valued fields to undefined if they aren't set // mongoose otherwise decides, that an empty array is a good idea @@ -56,8 +78,12 @@ function createEvent({ Event, sendEvent, userId, eventType, data, logger }) { }).then( event => { logger.debug(event); - return sendEvent(event); + sendEvent(event); + return event; }, - err => logger.error(err) + err => { + logger.error(err); + throw err; + } ); }
Make todos with children copyable
compose-us_todastic
train
1aa9457e4ac999d7a7174bb3d7195c4c3a4463d6
diff --git a/stellar_sdk/client/aiohttp_client.py b/stellar_sdk/client/aiohttp_client.py index <HASH>..<HASH> 100644 --- a/stellar_sdk/client/aiohttp_client.py +++ b/stellar_sdk/client/aiohttp_client.py @@ -211,7 +211,7 @@ class AiohttpClient(BaseAsyncClient): raise StreamClientError( query_params["cursor"], "Failed to get stream message." ) from e - except asyncio.exceptions.TimeoutError: + except asyncio.TimeoutError: logger.warning( f"We have encountered an timeout error and we will try to reconnect, cursor = {query_params.get('cursor')}" )
fix: make `AiohttpClient` compatible with Python <I> and <I> (#<I>) `asyncio.exceptions.TimeoutError` available in Python <I> and above
StellarCN_py-stellar-base
train
b01f114add00eeed694cc74e90fa8e482aadc67c
diff --git a/lib/EarthIT/CMIPREST/MSSQLStorage.php b/lib/EarthIT/CMIPREST/MSSQLStorage.php index <HASH>..<HASH> 100644 --- a/lib/EarthIT/CMIPREST/MSSQLStorage.php +++ b/lib/EarthIT/CMIPREST/MSSQLStorage.php @@ -216,7 +216,7 @@ class EarthIT_CMIPREST_MSSQLStorage implements EarthIT_CMIPREST_Storage $orderByComponents = $sp->getOrderByComponents(); $limit = $sp->getLimit(); $skip = $sp->getSkip(); - if( $limit !== null or $skip != 0 ) { + if( true /*$limit !== null or $skip != 0*/ ) { // Always order by! // Since offset/skip is part of the order by clause, // we need to make up something to order by if not already specified. if( count($orderByComponents) == 0 ) {
Fix MSSQLStorage to always generate an ORDER BY clause.
EarthlingInteractive_PHPCMIPREST
train
88799e2ed671e36276c6febebf04e14fd30ebacb
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -18,7 +18,7 @@ module.exports = { * * @param {String} folder * @chainable - */ + */ load: function(folder) { /** * Looking in '<project_root>/test/fixtures' by default @@ -26,7 +26,8 @@ module.exports = { if (!folder) folder = process.cwd() + '/test/fixtures'; var files = fs.readdirSync(folder); - for (i in files) { + var i; + for (i = 0; i < files.length; i++) { if (path.extname(files[i]).toLowerCase() === '.json') { var modelName = path.basename(files[i]).split('.')[0].toLowerCase(); @@ -38,7 +39,7 @@ module.exports = { }, /** - * + * * @param {function} done * @param {String} folder * @chainable
Changed for loop to not use for in. see <URL>
bredikhin_barrels
train
8f38410d67887ce98d57f89b1409b381f2ddce50
diff --git a/animanager/argparse.py b/animanager/argparse.py index <HASH>..<HASH> 100644 --- a/animanager/argparse.py +++ b/animanager/argparse.py @@ -70,4 +70,10 @@ def compile_sql_query(args: Iterable[str]) -> str: return '%{}%'.format('%'.join(args)) class CommandError(Exception): - """Error parsing command arguments.""" + """Error parsing command arguments. + + This is raised in place of ArgumentParser's default action of + sys.exit()ing, so Animanager's command line processing can handle it + properly. + + """
Improve CommandError docstring
darkfeline_animanager
train
61545f4b8100a822271a9ac9672fdded5f1b1958
diff --git a/spec/twitter/tweet_spec.rb b/spec/twitter/tweet_spec.rb index <HASH>..<HASH> 100644 --- a/spec/twitter/tweet_spec.rb +++ b/spec/twitter/tweet_spec.rb @@ -310,6 +310,23 @@ describe Twitter::Tweet do Twitter::Tweet.new(:id => 28669546014).urls expect($stderr.string).to match(/To get urls, you must pass `:include_entities => true` when requesting the Twitter::Tweet\./) end + + it "can handle strange urls" do + urls_array = [ + { + :url => "http://with_underscore.example.com/t.co", + :expanded_url => "http://with_underscore.example.com/expanded", + :display_url => "with_underscore.example.com/expanded…", + :indices => [10, 33], + } + ] + tweet = Twitter::Tweet.new(:id => 28669546014, :entities => {:urls => urls_array}) + uri = tweet.uris.first + expect{ uri.url }.to_not raise_error + expect{ uri.expanded_url }.to_not raise_error + expect{ uri.display_url }.to_not raise_error + end + end describe "#uri" do
failing spec for "strange urls"
sferik_twitter
train
bc6eb5ab37587bfa23331c1c87f8bb3b9375b029
diff --git a/taskw/test/test_datas.py b/taskw/test/test_datas.py index <HASH>..<HASH> 100644 --- a/taskw/test/test_datas.py +++ b/taskw/test/test_datas.py @@ -407,6 +407,24 @@ class TestDBShellout(_BaseTestDB): eq_(len(tasks), 1) eq_(tasks[0]['id'], 3) + def test_filtering_qmark(self): + task1 = self.tw.task_add("foobar1") + task2 = self.tw.task_add("foo?bar") + tasks = self.tw.filter_tasks({ + 'description.contains': 'oo?ba', + }) + eq_(len(tasks), 1) + eq_(tasks[0]['id'], 2) + + def test_filtering_qmark_not_contains(self): + task1 = self.tw.task_add("foobar1") + task2 = self.tw.task_add("foo?bar") + tasks = self.tw.filter_tasks({ + 'description': 'foo?bar', + }) + eq_(len(tasks), 1) + eq_(tasks[0]['id'], 2) + def test_filtering_semicolon(self): task1 = self.tw.task_add("foobar1") task2 = self.tw.task_add("foobar2")
Add failing test case for `?` escaping
ralphbean_taskw
train
b19c8614bc78fef2b48148e4ec4ea46274320416
diff --git a/sysconfig.py b/sysconfig.py index <HASH>..<HASH> 100644 --- a/sysconfig.py +++ b/sysconfig.py @@ -93,14 +93,11 @@ def get_python_inc(plat_specific=0, prefix=None): # the build directory may not be the source directory, we # must use "srcdir" from the makefile to find the "Include" # directory. - base = _sys_home or project_base if plat_specific: - return base - if _sys_home: - incdir = os.path.join(_sys_home, 'Include') + return _sys_home or project_base else: incdir = os.path.join(get_config_var('srcdir'), 'Include') - return os.path.normpath(incdir) + return os.path.normpath(incdir) python_dir = 'python' + get_python_version() + build_flags return os.path.join(prefix, "include", python_dir) elif os.name == "nt":
bpo-<I>: update distutils.sysconfig for venv's created from Python (#<I>) compiled out-of-tree (builddir != srcdir). (see also bpo-<I>)
pypa_setuptools
train
663afcea93734fdbdf15b7fda5a3d59f29c29906
diff --git a/fixture/src/org/immutables/generate/silly/SillyOrdinal.java b/fixture/src/org/immutables/generate/silly/SillyOrdinal.java index <HASH>..<HASH> 100644 --- a/fixture/src/org/immutables/generate/silly/SillyOrdinal.java +++ b/fixture/src/org/immutables/generate/silly/SillyOrdinal.java @@ -19,7 +19,7 @@ import org.immutables.annotation.GenerateConstructorParameter; import org.immutables.annotation.GenerateImmutable; import org.immutables.common.collect.OrdinalValue; -@GenerateImmutable(builder = false) +@GenerateImmutable public abstract class SillyOrdinal implements OrdinalValue<SillyOrdinal> { @GenerateConstructorParameter diff --git a/fixture/test/org/immutables/generate/silly/ValuesTest.java b/fixture/test/org/immutables/generate/silly/ValuesTest.java index <HASH>..<HASH> 100644 --- a/fixture/test/org/immutables/generate/silly/ValuesTest.java +++ b/fixture/test/org/immutables/generate/silly/ValuesTest.java @@ -21,7 +21,7 @@ import org.junit.Test; import static org.immutables.check.Checkers.*; public class ValuesTest { - + @Test public void builderInheritence() { check(ImmutableSillyExtendedBuilder.builder().base); @@ -36,13 +36,38 @@ public class ValuesTest { check(Arrays.asList(a.ordinal(), b.ordinal(), c.ordinal())).isOf(0, 1, 2); check(ImmutableSillyOrdinal.of("a")).same(a); check(ImmutableSillyOrdinal.of("b")).same(b); - + check(a.domain().get(1)).same(b); check(a.domain().get(0)).same(a); check(a.domain().length()).is(3); check(a.domain()).isOf(a, b, c); } - + + @Test + public void ordinalDomain() { + ImmutableSillyOrdinal.Domain domain = new ImmutableSillyOrdinal.Domain(); + + ImmutableSillyOrdinal a = ImmutableSillyOrdinal.of("a"); + + ImmutableSillyOrdinal a1 = ImmutableSillyOrdinal.builder() + .domain(domain) + .name("a") + .build(); + + ImmutableSillyOrdinal a2 = ImmutableSillyOrdinal.builder() + .domain(domain) + .name("a") + .build(); + + check(a.domain()).not(domain); + check(a.domain()).same(ImmutableSillyOrdinal.Domain.get()); + check(a1.domain()).same(domain); + + check(a).not(a1); + check(a1).same(a2); + check(domain.length()).is(1); + } + @Test public void ordinalValueSet() { check(ImmutableSillyOrdinalHolder.builder() diff --git a/generate/src/org/immutables/generate/template/immutable.tjs b/generate/src/org/immutables/generate/template/immutable.tjs index <HASH>..<HASH> 100644 --- a/generate/src/org/immutables/generate/template/immutable.tjs +++ b/generate/src/org/immutables/generate/template/immutable.tjs @@ -467,7 +467,7 @@ this.`n` = com.google.common.base.Preconditions.checkNotNull(super.`n`()); [/if] [/let] [/foreach] - [apply generateAfterConstruction(type)] + [apply generateAfterConstruction(type, true)] } [/if] [foreach (let v in getters)] @@ -551,14 +551,14 @@ public String toString() { [/if] [/template] -[template generateAfterConstruction(type, builder)] +[template generateAfterConstruction(type, usingBuilder)] [if (type.usePrehashed)] this.hashCode = this.computeHashCode(); [/if] [if (type.generateOrdinalValue)] [-- Assigning dummy ordinal value to be changed on interning --] this.ordinal = 0; - [if (builder)] + [if (usingBuilder)] this.domain = builder.domain; [else] [-- Default static ordinal domain --]
fixed passing of custom domain for ordinal value
immutables_immutables
train
dd79c9e86cfa65d165e7d2b6c2bd950bba1c2525
diff --git a/lib/dependor/injectable.rb b/lib/dependor/injectable.rb index <HASH>..<HASH> 100644 --- a/lib/dependor/injectable.rb +++ b/lib/dependor/injectable.rb @@ -7,6 +7,7 @@ module Dependor end module InstanceMethods + def inject! Dependor.injector.inject(self) end @@ -14,6 +15,7 @@ module Dependor def isolate! Dependor.injector.isolate(self) end + end module ClassMethods @@ -23,7 +25,11 @@ module Dependor end def depends_on(*dependency_names) - attr_accessor *dependency_names + dependency_names.each do |dependency_name| + attr_reader dependency_name unless instance_methods.include?(dependency_name) + attr_writer dependency_name unless instance_methods.include?(:"#{dependency_name}=") + end + dependency_names.each { |name| dependor_meta_data.add_dependency(name) } end diff --git a/spec/dependor/injectable_spec.rb b/spec/dependor/injectable_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dependor/injectable_spec.rb +++ b/spec/dependor/injectable_spec.rb @@ -12,6 +12,23 @@ describe Dependor::Injectable do it "should inject every object in the hierarchy" do baz.bar.foo.should be_an_instance_of(Foo) end + + class DependencyInheritanceParent + include Dependor::Injectable + + depends_on :foo + end + + class DependencyInheritanceChild < DependencyInheritanceParent + depends_on :bar + end + + it "should inject both inherited and declared dependencies" do + sample = DependencyInheritanceChild.make + + sample.foo.should be_an_instance_of(Foo) + sample.bar.should be_an_instance_of(Bar) + end end describe ".isolated" do @@ -43,24 +60,41 @@ describe Dependor::Injectable do sample.should respond_to(:bar) sample.should respond_to(:baz) end - end - describe "dependency inheritance" do - class DependencyInheritanceParent + it "should add getters for all of the dependencies" do + sample = DeclaringDependenciesSample.new + + sample.should respond_to(:foo=) + sample.should respond_to(:bar=) + sample.should respond_to(:baz=) + end + + class WithAlreadyDefinedGettersAndSetters + def foo + return "foo" + end + + def bar=(new_bar) + @bar = "prefix_#{new_bar}" + end + include Dependor::Injectable - depends_on :foo + depends_on :foo, :bar, :baz end - class DependencyInheritanceChild < DependencyInheritanceParent - depends_on :bar + it "should not override already existing getters" do + sample = WithAlreadyDefinedGettersAndSetters.new + + sample.foo.should == "foo" end - it "should inject both parent and child dependencies" do - sample = DependencyInheritanceChild.make + it "should not override already existing setters" do + sample = WithAlreadyDefinedGettersAndSetters.new - sample.foo.should be_an_instance_of(Foo) - sample.bar.should be_an_instance_of(Bar) + sample.bar = "bar" + + sample.bar.should == "prefix_bar" end end
Existing methods are not overriden by declaring dependencies.
psyho_dependor
train
0e565894d2e3cff41b76fded739845384f857480
diff --git a/Repository/ToolRepository.php b/Repository/ToolRepository.php index <HASH>..<HASH> 100644 --- a/Repository/ToolRepository.php +++ b/Repository/ToolRepository.php @@ -32,7 +32,7 @@ class ToolRepository extends EntityRepository $isAdmin = false; foreach ($roles as $role) { - if ($role === 'ROLE_ADMIN') { + if ($role === 'ROLE_ADMIN' || $role === 'ROLE_WS_MANAGER_' . $workspace->getGuid()) { $isAdmin = true; } }
[CoreBundle] Fixed repository method
claroline_Distribution
train
2889665855ce22ea8980b290a83d305587e32501
diff --git a/src/widgets/InlineMenuWidget.js b/src/widgets/InlineMenuWidget.js index <HASH>..<HASH> 100644 --- a/src/widgets/InlineMenuWidget.js +++ b/src/widgets/InlineMenuWidget.js @@ -69,7 +69,14 @@ OO.ui.InlineMenuWidget.prototype.getMenu = function () { * @param {OO.ui.MenuItemWidget} item Selected menu item */ OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) { - this.setLabel( item.getLabel() ); + var selectedLabel = item.getLabel(); + + // If the label is a DOM element, clone it, because setLabel will append() it + if ( selectedLabel instanceof jQuery ) { + selectedLabel = selectedLabel.clone(); + } + + this.setLabel( selectedLabel ); }; /**
Fixes bug where InlineMenuWidget would "steal" DOM labels on selection To reproduce, create an InlineMenuWidget where the labels are jQuery objects. Selecting one of the options would incorrectly detach the label from the list of options to populate the selected label. Change-Id: I7db<I>d<I>a1cc<I>f<I>cfa4eeadb7b<I>e<I>f6d
wikimedia_oojs-ui
train
b315e2a517867f464b4adb6c589e51ecee64c2bf
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -4,7 +4,7 @@ var each = require('turf-meta').coordEach; * Calculates the extent of all input features and returns a bounding box. * * @module turf/extent - * @param {GeoJSON-Object} input any valid GeoJSON Object + * @param {GeoJSON} input any valid GeoJSON Object * @return {Array<number>} the bounding box of the GeoJSON given * as an array in WSEN order (west, south, east, north) * @example
Fix old-fashioned typedef link
turf-junkyard_turf-extent
train
0a5ee539a507544d9cbf8c4ada175b05d604f47b
diff --git a/lib/sonos.js b/lib/sonos.js index <HASH>..<HASH> 100644 --- a/lib/sonos.js +++ b/lib/sonos.js @@ -49,7 +49,7 @@ var withinEnvelope = function(body) { /** * Encodes characters not allowed within html/xml tags - * @param {String} body + * @param {String} str * @return {String} */ var htmlEntities = function (str) { @@ -107,7 +107,7 @@ Sonos.prototype.request = function(endpoint, action, body, responseTag, callback */ Sonos.prototype.getMusicLibrary = function(searchType, options, callback){ - var _this = this; + var _this = this; var searches = { 'artists': 'A:ARTIST', @@ -119,7 +119,7 @@ Sonos.prototype.getMusicLibrary = function(searchType, options, callback){ 'playlists': 'A:PLAYLISTS', 'share': 'S:' }; - + var defaultOptions = { BrowseFlag: 'BrowseDirectChildren', Filter: '*', @@ -127,37 +127,47 @@ Sonos.prototype.getMusicLibrary = function(searchType, options, callback){ RequestedCount: '100', SortCriteria: '' }; - + var opts = { ObjectID: searches[searchType] }; - + if(options.start !== undefined) opts.StartingIndex = options.start; if(options.total !== undefined) opts.RequestedCount = options.total; opts = _.extend(defaultOptions, opts); - + var contentDirectory = new Services.ContentDirectory(this.host, this.port); return contentDirectory.Browse(opts, function(err, data){ if (err) return callback(err); return (new xml2js.Parser()).parseString(data.Result, function(err, didl) { if (err) return callback(err, data); - + var items = []; - + if ((!didl) || (!didl['DIDL-Lite']) || (!util.isArray(didl['DIDL-Lite'].container))){ callback(new Error('Cannot parse DIDTL result'), data); } - + _.each(didl['DIDL-Lite'].container, function(item){ + + var albumArtURL = null; + + if(util.isArray(item['upnp:albumArtURI'])) { + if(item['upnp:albumArtURI'][0].indexOf('http') !== -1) { + albumArtURL = item['upnp:albumArtURI'][0]; + } + else { + albumArtURL = 'http://' + _this.host + ':' + _this.port + item['upnp:albumArtURI'][0]; + } + + } items.push( { - 'title': util.isArray(item['dc:title']) ? item['dc:title'][0] : null, - 'artist': util.isArray(item['dc:creator']) ? item['dc:creator'][0] : null, - 'albumArtURL': util.isArray(item['upnp:albumArtURI']) ? - (item['upnp:albumArtURI'][0].indexOf('http') !== -1) ? item['upnp:albumArtURI'][0] - : 'http://' + _this.host + ':' + _this.port + item['upnp:albumArtURI'][0] : null, - 'uri': util.isArray(item.res) ? item.res[0]._ : null + 'title': util.isArray(item['dc:title']) ? item['dc:title'][0] : null, + 'artist': util.isArray(item['dc:creator']) ? item['dc:creator'][0] : null, + 'albumArtURL': albumArtURL, + 'uri': util.isArray(item.res) ? item.res[0]._ : null } ); }); @@ -611,7 +621,7 @@ Sonos.prototype.setName = function(name, callback) { /** * Set Play Mode - * @param {String} + * @param {String} playmode * @param {Function} callback (err, data) * @return {[type]} */ @@ -714,7 +724,7 @@ Sonos.prototype.getCurrentState = function(callback) { } else if (JSON.stringify(data[0].CurrentTransportState) === '["PAUSED_PLAYBACK"]') { state = 'paused'; } - + return callback(err, state); }); };
fixed lint warnings and rearranged code for better readability
bencevans_node-sonos
train
0b2f76153764aaefa9da5cbb4a6b23d3c180d749
diff --git a/lib/guard/notifier.rb b/lib/guard/notifier.rb index <HASH>..<HASH> 100644 --- a/lib/guard/notifier.rb +++ b/lib/guard/notifier.rb @@ -174,7 +174,7 @@ module Guard notifier = _get_notifier_module(notifier[:name]).new(notifier[:options]) begin - notifier.notify(message, opts) + notifier.notify(message, opts.dup) rescue Exception => e ::Guard::UI.error "Error sending notification with #{ notifier.name }: #{ e.message }" ::Guard::UI.debug e.backtrace.join("\n")
Fix options changed after pass it to any notifiers
guard_guard
train
5af5d19cd8385e61e9bf2b580a5bf400904d9a0d
diff --git a/controller/src/main/java/org/jboss/as/controller/ReadResourceNameOperationStepHandler.java b/controller/src/main/java/org/jboss/as/controller/ReadResourceNameOperationStepHandler.java index <HASH>..<HASH> 100644 --- a/controller/src/main/java/org/jboss/as/controller/ReadResourceNameOperationStepHandler.java +++ b/controller/src/main/java/org/jboss/as/controller/ReadResourceNameOperationStepHandler.java @@ -41,6 +41,8 @@ public class ReadResourceNameOperationStepHandler implements OperationStepHandle @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { + // Check if the resource exists before return the name + context.readResource(PathAddress.EMPTY_ADDRESS, false); final String name = context.getCurrentAddressValue(); context.getResult().set(name);
[WFCORE-<I>] Check that the resource exists before returning the resource name.
wildfly_wildfly-core
train
3e32452952594cab803d9b635f56a89dab2ab53a
diff --git a/svtyper/singlesample.py b/svtyper/singlesample.py index <HASH>..<HASH> 100644 --- a/svtyper/singlesample.py +++ b/svtyper/singlesample.py @@ -172,8 +172,8 @@ def retrieve_reads_from_db(bam, variant_id, regions, max_reads): if countA > max_reads or countB > max_reads: over_threshold = True msg = ("SKIPPING -- Variant '{}' has a region with too many reads (> {})\n" - "\t\t A: {} : (sample={} chrom={} center={} leftflank={} rightflank={})\n" - "\t\t B: {} : (sample={} chrom={} center={} leftflank={} rightflank={})").format( + "\t\t A: (sample={} chrom={} center={} leftflank={} rightflank={}) : {}\n" + "\t\t B: (sample={} chrom={} center={} leftflank={} rightflank={}) : {}").format( variant_id, max_reads, regionA[0], regionA[1], regionA[2], regionA[3], regionA[4],
+ correct the SKIPPING formatting - there was an off by one issue. i accidentally removed the read count formats stubs
hall-lab_svtyper
train
bd4b73dc9787a62960872f987948fd04ebff3ffa
diff --git a/modules/custom/openy_map/js/map.js b/modules/custom/openy_map/js/map.js index <HASH>..<HASH> 100644 --- a/modules/custom/openy_map/js/map.js +++ b/modules/custom/openy_map/js/map.js @@ -569,7 +569,7 @@ var tag_filter_html = '<label class="btn btn-default" for="tag_' + tag + '">'; tag_filter_html += '<input autocomplete="off" id="tag_' + tag + '" class="tag_' + tag + '" type="checkbox" value="' + tag + '" ' + filter_checked + '/>' + tag; for (var i = 0; i < this.tags[tag].marker_icons.length; i++) { - tag_filter_html += '<img class="tag_icon inline-hidden-sm" src="' + this.tags[tag].marker_icons[i] + '"/>'; + tag_filter_html += '<img class="tag_icon inline-hidden-sm" src="' + this.tags[tag].marker_icons[i] + '" aria-hidden="true" />'; } tag_filter_html += '</label>'; tag_filters_html += tag_filter_html; @@ -1358,7 +1358,7 @@ var tag_filter_html = '<label class="btn btn-default" for="tag_' + tag + '">'; tag_filter_html += '<input autocomplete="off" id="tag_' + tag + '" class="tag_' + tag + '" type="checkbox" value="' + tag + '" ' + filter_checked + '/>' + tag; for (var i = 0; i < this.tags[tag].marker_icons.length; i++) { - tag_filter_html += '<img class="tag_icon inline-hidden-sm" src="' + this.tags[tag].marker_icons[i] + '"/>'; + tag_filter_html += '<img class="tag_icon inline-hidden-sm" src="' + this.tags[tag].marker_icons[i] + '" aria-hidden="true" />'; } tag_filter_html += '</label>'; tag_filters_html += tag_filter_html;
[OS-<I>] Graphics after location types are not labeled. (hide icons at all for screen readers)
ymcatwincities_openy
train
6a8df96e1424ad7f9bd5a65bda20081285107724
diff --git a/src/Bkwld/EloquentUploads/ServiceProvider.php b/src/Bkwld/EloquentUploads/ServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Bkwld/EloquentUploads/ServiceProvider.php +++ b/src/Bkwld/EloquentUploads/ServiceProvider.php @@ -35,19 +35,21 @@ class ServiceProvider extends LaravelServiceProvider { */ public function register() { + // Instantiate the disk for the destination + $this->app->bind('eloquent_uploads.dst', function($app) { + return new Filesystem(new LocalAdapter(public_path().'/uploads')); + }); + // Instantiate Flysystem for this package - $this->app->bind('eloquent_uploads.flysystem_manager', function($app) { + $this->app->bind('eloquent_uploads.manager', function($app) { // Get the temp directory, this is where uploads will be moved from $tmp = ini_get('upload_tmp_dir') ?: sys_get_temp_dir(); - // Get the dst directory from the config - $dst = public_path().'/uploads'; - // Create the MountManger instance return new MountManager([ 'tmp' => new Filesystem(new LocalAdapter($tmp)), - 'dst' => new Filesystem(new LocalAdapter($dst)), + 'dst' => $app['eloquent_uploads.dst'], ]); }); @@ -58,7 +60,7 @@ class ServiceProvider extends LaravelServiceProvider { // Instantiate storage class $this->app->bind('eloquent_uploads.storage', function($app) { - return new Storage($app['eloquent_uploads.flysystem_manager']); + return new Storage($app['eloquent_uploads.manger']); }); } @@ -70,7 +72,8 @@ class ServiceProvider extends LaravelServiceProvider { */ public function provides() { return array( - 'eloquent_uploads.flysystem_manager', + 'eloquent_uploads.dst', + 'eloquent_uploads.manger', 'eloquent_uploads.observer', 'eloquent_uploads.storage', );
Breaking the destination disk in to it's own IoC type
BKWLD_upchuck
train
d200dbc8e456d2e778455240819f9bb0ef0f40db
diff --git a/src/toil/worker.py b/src/toil/worker.py index <HASH>..<HASH> 100644 --- a/src/toil/worker.py +++ b/src/toil/worker.py @@ -147,7 +147,7 @@ def workerScript(jobStore, config, jobName, jobStoreID, redirectOutputToLogFile= except OSError: pass # Exit without doing any of Toil's cleanup - os._exit() + os._exit(0) # We don't need to reap the child. Either it kills us, or we finish # before it does. Either way, init will have to clean it up for us.
Send an argument to exit, as it is required
DataBiosphere_toil
train
d5150bf007298d6646cbefe9229be84a284b0ce9
diff --git a/django_countries/tests/settings.py b/django_countries/tests/settings.py index <HASH>..<HASH> 100644 --- a/django_countries/tests/settings.py +++ b/django_countries/tests/settings.py @@ -10,3 +10,8 @@ DATABASES = { } STATIC_URL = '/static-assets/' + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', +) diff --git a/django_countries/tests/test_fields.py b/django_countries/tests/test_fields.py index <HASH>..<HASH> 100644 --- a/django_countries/tests/test_fields.py +++ b/django_countries/tests/test_fields.py @@ -1,5 +1,7 @@ from __future__ import unicode_literals from django.db import IntegrityError +from django.forms import Select +from django.forms.models import modelform_factory from django.test import TestCase from django.utils.encoding import force_text @@ -30,7 +32,8 @@ class TestCountryField(TestCase): def test_flag(self): person = Person(name='Chris Beaven', country='NZ') with self.settings(STATIC_URL='/static-assets/'): - self.assertEqual(person.country.flag, '/static-assets/flags/nz.gif') + self.assertEqual( + person.country.flag, '/static-assets/flags/nz.gif') def test_custom_field_flag_url(self): person = Person(name='Chris Beaven', country='NZ', other_country='US') @@ -98,6 +101,11 @@ class TestCountryField(TestCase): IntegrityError, Person.objects.create, name='The Outsider', country=None) + def test_create_modelform(self): + Form = modelform_factory(Person, fields=['country']) + form_field = Form().fields['country'] + self.assertTrue(isinstance(form_field.widget, Select)) + class TestCountryObject(TestCase):
Test that a ModelForm can be created correctly Refs #<I>
SmileyChris_django-countries
train
b3f3a20928d2e34e7dba07639db5a2ec1b0b3eac
diff --git a/src/Psalm/Checker/Statements/Expression/AssignmentChecker.php b/src/Psalm/Checker/Statements/Expression/AssignmentChecker.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Checker/Statements/Expression/AssignmentChecker.php +++ b/src/Psalm/Checker/Statements/Expression/AssignmentChecker.php @@ -435,7 +435,7 @@ class AssignmentChecker $class_property_type = Type::getMixed(); } else { - $class_property_type = clone $class_property_type; + $class_property_type = ExpressionChecker::fleshOutTypes($class_property_type, [], $lhs_type_part->value); } $class_property_types[] = $class_property_type; @@ -623,6 +623,8 @@ class AssignmentChecker return null; } + $class_property_type = ExpressionChecker::fleshOutTypes($class_property_type, [], $absolute_class); + if (!$assignment_type->isIn($class_property_type)) { if (IssueBuffer::accepts( new InvalidPropertyAssignment( diff --git a/src/Psalm/Checker/Statements/ExpressionChecker.php b/src/Psalm/Checker/Statements/ExpressionChecker.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Checker/Statements/ExpressionChecker.php +++ b/src/Psalm/Checker/Statements/ExpressionChecker.php @@ -401,17 +401,25 @@ class ExpressionChecker Type\Union $by_ref_type = null, $array_assignment = false ) { - if ($statements_checker->isStatic() && $stmt->name === 'this') { - if (IssueBuffer::accepts( - new InvalidStaticVariable( - 'Invalid reference to $this in a static context', - $statements_checker->getCheckedFileName(), - $stmt->getLine() - ), - $statements_checker->getSuppressedIssues() - )) { - return false; + if ($stmt->name === 'this') { + if ($statements_checker->isStatic()) { + if (IssueBuffer::accepts( + new InvalidStaticVariable( + 'Invalid reference to $this in a static context', + $statements_checker->getCheckedFileName(), + $stmt->getLine() + ), + $statements_checker->getSuppressedIssues() + )) { + return false; + } + + return null; } + + $stmt->inferredType = clone $context->vars_in_scope['$this']; + + return null; } if (!$context->check_variables) { @@ -426,7 +434,7 @@ class ExpressionChecker } if (in_array($stmt->name, [ - '_SERVER', '_GET', '_POST', '_COOKIE', '_REQUEST', '_FILES', '_ENV', 'GLOBALS', 'argv' + '_SERVER', '_GET', '_POST', '_COOKIE', '_REQUEST', '_FILES', '_ENV', 'GLOBALS', 'argv', 'argc' ])) { return null; } @@ -435,10 +443,6 @@ class ExpressionChecker return self::check($statements_checker, $stmt->name, $context); } - if ($stmt->name === 'this') { - return null; - } - if ($passed_by_reference && $by_ref_type) { self::assignByRefParam($statements_checker, $stmt, $by_ref_type, $context); return null; @@ -855,7 +859,7 @@ class ExpressionChecker * @param string|null $method_id * @return Type\Union */ - public static function fleshOutTypes(Type\Union $return_type, array $args, $calling_class, $method_id) + public static function fleshOutTypes(Type\Union $return_type, array $args, $calling_class = null, $method_id = null) { $return_type = clone $return_type; diff --git a/src/Psalm/Checker/StatementsChecker.php b/src/Psalm/Checker/StatementsChecker.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Checker/StatementsChecker.php +++ b/src/Psalm/Checker/StatementsChecker.php @@ -157,8 +157,8 @@ class StatementsChecker } /* - if (isset($context->vars_in_scope['$pos'])) { - var_dump($stmt->getLine() . ' ' . $context->vars_in_scope['$pos']); + if (isset($context->vars_in_scope['$this'])) { + var_dump($stmt->getLine() . ' ' . $context->vars_in_scope['$this']); } */ diff --git a/tests/ReturnTypeTest.php b/tests/ReturnTypeTest.php index <HASH>..<HASH> 100644 --- a/tests/ReturnTypeTest.php +++ b/tests/ReturnTypeTest.php @@ -408,4 +408,20 @@ class ReturnTypeTest extends PHPUnit_Framework_TestCase $context = new Context('somefile.php'); $file_checker->check(true, true, $context); } + + public function testThisReturnType() + { + $stmts = self::$parser->parse('<?php + class A { + /** @return $this */ + public function getThis() { + return $this; + } + } + '); + + $file_checker = new FileChecker('somefile.php', $stmts); + $context = new Context('somefile.php'); + $file_checker->check(true, true, $context); + } }
Correctly evaluate $this and self in property/return types
vimeo_psalm
train
eb83976c58cb4936896a62d31634e824a5c83107
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -23,7 +23,7 @@ function _getResourceUrl(resourceName, id=null) { } module.exports = { - get (resourceName, options={}) { + get: function(resourceName, options={}) { let resourceUrl = _getResourceUrl(resourceName); let req = request .get(resourceUrl) @@ -33,7 +33,7 @@ module.exports = { return promiseYouWill(req); }, - create (resourceName, resource, options={}) { + create: function(resourceName, resource, options={}) { let resourceUrl = _getResourceUrl(resourceName, resource.id); let req = request.post(resourceUrl) .set('Content-Type', 'application/json') @@ -43,7 +43,7 @@ module.exports = { return promiseYouWill(req); }, - update (resourceName, resource, options={}) { + update: function(resourceName, resource, options={}) { let resourceUrl = _getResourceUrl(resourceName, resource.id); let req = request.put(resourceUrl) .set('Content-Type', 'application/json') @@ -53,7 +53,7 @@ module.exports = { return promiseYouWill(req); }, - del (resourceName, resource) { + del: function(resourceName, resource) { let resourceUrl = _getResourceUrl(resourceName, resource.id); let req = request.del(resourceUrl);
ES6 to ES5 Changed library to be es5 compatible.
jthoms1_jsonapi2simple
train
43696d91fcb2f6c94ee7872e01b09870c964b820
diff --git a/upgrades/5.9/scripts/AfterUpgrade.php b/upgrades/5.9/scripts/AfterUpgrade.php index <HASH>..<HASH> 100644 --- a/upgrades/5.9/scripts/AfterUpgrade.php +++ b/upgrades/5.9/scripts/AfterUpgrade.php @@ -35,6 +35,8 @@ class AfterUpgrade protected function fixCollation($container) { + $ignotedEntityList = ['Job', 'LayoutRecord']; + $pdo = $container->get('entityManager')->getPDO(); $ormMeta = $container->get('ormMetadata')->getData(true); @@ -42,6 +44,7 @@ class AfterUpgrade foreach ($ormMeta as $entityName => $entityParams) { + if (in_array($entityName, $ignotedEntityList)) continue; if (!isset($fieldListExceededIndexMaxLength[$entityName])) continue; $tableName = \Espo\Core\Utils\Util::toUnderScore($entityName);
Modification upgrade script <I>
espocrm_espocrm
train
ba9e4a00584afbdf6f4c55151528a4d3c37c667e
diff --git a/rules/predicates.py b/rules/predicates.py index <HASH>..<HASH> 100644 --- a/rules/predicates.py +++ b/rules/predicates.py @@ -151,7 +151,7 @@ class Predicate(object): args = tuple(arg for arg in (obj, target) if arg is not NO_VALUE) _context.stack.append(Context(args)) try: - return self._apply(*args) + return bool(self._apply(*args)) finally: _context.stack.pop() @@ -183,7 +183,7 @@ class Predicate(object): def _combine(self, other, op, args): self_result = self._apply(*args) if self_result is None: - return bool(other._apply(*args)) + return other._apply(*args) # short-circuit evaluation if op is operator.and_ and not self_result: diff --git a/tests/testsuite/test_predicates.py b/tests/testsuite/test_predicates.py index <HASH>..<HASH> 100644 --- a/tests/testsuite/test_predicates.py +++ b/tests/testsuite/test_predicates.py @@ -324,7 +324,7 @@ def test_skip_predicate_deprecation(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') - assert skipped_predicate.test() is None + assert skipped_predicate.test() is False assert len(w) == 1 and 'deprecated' in str(w[-1].message) @@ -365,7 +365,13 @@ def test_skip_predicate(): assert (passthrough | ~requires_two_args).test(False) is False # test that when all predicates are skipped, result is False + assert requires_two_args.test(True) is False assert (requires_two_args | requires_two_args).test(True) is False + assert (requires_two_args & requires_two_args).test(True) is False + + # test that a skipped predicate doesn't alter the result at all + assert (requires_two_args | requires_two_args | passthrough).test(True) is True + assert (requires_two_args & requires_two_args & passthrough).test(True) is True def test_invocation_context():
Better handling of skipped predicates This pins down the semantics of skipping predicates by letting the result propagate up to the initial invocation (that is ``Predicate.test()``)
dfunckt_django-rules
train
bd228de628066162a4054f1ed4b7682b23c42505
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ with open("README.md") as readme_file: setup( name = 'aguaclara', - version = '0.3.2', + version = '0.3.3', description = ( 'An open-source Python package for designing and performing research ' 'on AguaClara water treatment plants.'
update version to <I> (#<I>) * Update Pipfile.lock for urllib and pillow vulnerabilities * Update setup.py * switch to <I> -- <I> was taken
AguaClara_aguaclara
train
2c23ff3153df33f11115dcad81c463bbc5d79140
diff --git a/src/Keboola/StorageApi/Client.php b/src/Keboola/StorageApi/Client.php index <HASH>..<HASH> 100644 --- a/src/Keboola/StorageApi/Client.php +++ b/src/Keboola/StorageApi/Client.php @@ -1007,7 +1007,7 @@ class Client $body = $response->json(); if ($response->getStatusCode() == 503) { - throw new MaintenanceException($body['reason'], $response->getHeader('Retry-After')); + throw new MaintenanceException($body['reason'], $response->getHeader('Retry-After', true)); } throw new ClientException(
Maintenance retry after header bugfix
keboola_storage-api-php-client
train
255303d43d4520f815c671489ecc0a1aebf5eccd
diff --git a/src/Container/Definition/AbstractDefinition.php b/src/Container/Definition/AbstractDefinition.php index <HASH>..<HASH> 100644 --- a/src/Container/Definition/AbstractDefinition.php +++ b/src/Container/Definition/AbstractDefinition.php @@ -145,9 +145,16 @@ abstract class AbstractDefinition implements DefinitionInterface $this->collectRelatedClasses($definitions, $id, $relatedClasses); $relatedClasses = array_reverse($relatedClasses); + $rootDirectory = $autoloadConfig->getRootDirectory(); + $alwaysAutoloadedClasses = array_flip($autoloadConfig->getAlwaysAutoloadedClasses()); + $code = ""; foreach ($relatedClasses as $relatedClass) { - $filename = FileSystemUtil::getRelativeFilename($autoloadConfig->getRootDirectory(), $relatedClass); + if (isset($alwaysAutoloadedClasses[$relatedClass])) { + continue; + } + + $filename = FileSystemUtil::getRelativeFilename($rootDirectory, $relatedClass); if ($filename === "") { continue; }
Do not autoload classes in the definitions which are always autoloaded
woohoolabs_zen
train
9a023d70272e9d0f1e3b7994f2ec8bd309ba43cd
diff --git a/spec/kerplutz/options_spec.rb b/spec/kerplutz/options_spec.rb index <HASH>..<HASH> 100644 --- a/spec/kerplutz/options_spec.rb +++ b/spec/kerplutz/options_spec.rb @@ -54,6 +54,7 @@ module Kerplutz it "configures the parser" do subject.configure(parser, args) expect { parser.parse("--kuato") }.to raise_error(OptionParser::MissingArgument) + args[:kuato].should be_nil parser.parse("--kuato", "George") args[:kuato].should == "George"
Assert required flag property is nil after failure
msassak_kerplutz
train
8a0f1c6b700339cb52656d304d88d334e4319607
diff --git a/kaminari-core/test/models/active_record/paginable_without_count_test.rb b/kaminari-core/test/models/active_record/paginable_without_count_test.rb index <HASH>..<HASH> 100644 --- a/kaminari-core/test/models/active_record/paginable_without_count_test.rb +++ b/kaminari-core/test/models/active_record/paginable_without_count_test.rb @@ -34,7 +34,7 @@ if defined? ActiveRecord end test 'when on the first page' do - @users = User.page(1).without_count.load + @users = User.page(1).without_count assert_equal 25, @users.size assert_equal 25, @users.each.size @@ -43,7 +43,7 @@ if defined? ActiveRecord end test 'when on the first page showing 26 elements' do - @users = User.page(1).per(26).without_count.load + @users = User.page(1).per(26).without_count assert_equal 26, @users.size assert_equal 26, @users.each.size @@ -52,7 +52,7 @@ if defined? ActiveRecord end test 'when on the last page' do - @users = User.page(2).without_count.load + @users = User.page(2).without_count assert_equal 1, @users.size assert_equal 1, @users.each.size @@ -61,7 +61,7 @@ if defined? ActiveRecord end test 'when out of range' do - @users = User.page(3).without_count.load + @users = User.page(3).without_count assert_equal 0, @users.size assert_equal 0, @users.each.size
No need to explicitly load here Relations without_count should work regardless of loaded? or !loaded?
kaminari_kaminari
train
18669bec8bf496daf958ca8c37433dd3d21fe8d6
diff --git a/src/Command/Environment/EnvironmentBranchCommand.php b/src/Command/Environment/EnvironmentBranchCommand.php index <HASH>..<HASH> 100644 --- a/src/Command/Environment/EnvironmentBranchCommand.php +++ b/src/Command/Environment/EnvironmentBranchCommand.php @@ -67,6 +67,11 @@ class EnvironmentBranchCommand extends CommandBase } if ($environment = $this->api()->getEnvironment($branchName, $selectedProject)) { + if (!$this->getProjectRoot()) { + $this->stdErr->writeln("The environment <comment>$branchName</comment> already exists."); + + return 1; + } /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $checkout = $questionHelper->confirm(
Do not prompt for checkout in branch command if it won't be possible
platformsh_platformsh-cli
train
f87ab13b9df5f80e0c148650c59a6e9d4c26b7d0
diff --git a/lib/kafka/protocol/decoder.rb b/lib/kafka/protocol/decoder.rb index <HASH>..<HASH> 100644 --- a/lib/kafka/protocol/decoder.rb +++ b/lib/kafka/protocol/decoder.rb @@ -1,11 +1,11 @@ module Kafka module Protocol - VARINT_MASK = 0b10000000 - # A decoder wraps an IO object, making it easy to read specific data types # from it. The Kafka protocol is not self-describing, so a client must call # these methods in just the right order for things to work. class Decoder + VARINT_MASK = 0b10000000 + def self.from_string(str, **options) new(StringIO.new(str), options) end @@ -91,11 +91,11 @@ module Kafka data = 0 loop do chunk = int8 - data += (chunk & (~VARINT_MASK)) << (group * 7) - group += 1 + data |= (chunk & (~VARINT_MASK)) << group + group += 7 break if (chunk & VARINT_MASK) == 0 end - data + data & 0b1 != 0 ? ~(data >> 1) : (data >> 1) end # Decodes a list of bytes from the IO object. diff --git a/spec/protocol/decoder_spec.rb b/spec/protocol/decoder_spec.rb index <HASH>..<HASH> 100644 --- a/spec/protocol/decoder_spec.rb +++ b/spec/protocol/decoder_spec.rb @@ -39,48 +39,79 @@ describe Kafka::Protocol::Decoder do end end - context 'data is stored in 1 group' do - it do - io = new_io_from_binaries("00001010") - decoder = Kafka::Protocol::Decoder.new(io) + context 'data is positive' do + context 'data is stored in 1 group' do + it do + io = new_io_from_binaries("00010100") + decoder = Kafka::Protocol::Decoder.new(io) + + expect(decoder.varint).to eq 10 + end + end - expect(decoder.varint).to eq 10 + context 'data exceeds max of 1 group' do + it do + io = new_io_from_binaries("01111110") + decoder = Kafka::Protocol::Decoder.new(io) + + expect(decoder.varint).to eq 63 + end end - end - context 'data exceeds max of 1 group' do - it do - io = new_io_from_binaries("01111111") - decoder = Kafka::Protocol::Decoder.new(io) + context 'data is stored in 2 groups' do + it do + io = new_io_from_binaries("11011000", "00000100") + decoder = Kafka::Protocol::Decoder.new(io) - expect(decoder.varint).to eq 127 + expect(decoder.varint).to eq 300 + end end - end - context 'data is stored in 2 groups' do - it do - io = new_io_from_binaries("10101100", "00000010") - decoder = Kafka::Protocol::Decoder.new(io) + context 'data is stored in 3 groups' do + it do + io = new_io_from_binaries("10000010", "10100011", "00011010") + decoder = Kafka::Protocol::Decoder.new(io) - expect(decoder.varint).to eq 300 + expect(decoder.varint).to eq 215233 + end end end - context 'data exceeds the max of 2 groups' do - it do - io = new_io_from_binaries("11111111", "01111111") - decoder = Kafka::Protocol::Decoder.new(io) + context 'data is negative' do + context 'data is stored in 1 group' do + it do + io = new_io_from_binaries("00010011") + decoder = Kafka::Protocol::Decoder.new(io) - expect(decoder.varint).to eq 16383 + expect(decoder.varint).to eq -10 + end end - end - context 'data is stored in 5 groups' do - it do - io = new_io_from_binaries("11110010", "10010000", "10000000", "10011100", "00100101") - decoder = Kafka::Protocol::Decoder.new(io) + context 'data exceeds max of 1 group' do + it do + io = new_io_from_binaries("01111101") + decoder = Kafka::Protocol::Decoder.new(io) + + expect(decoder.varint).to eq -63 + end + end + + context 'data is stored in 2 groups' do + it do + io = new_io_from_binaries("11010111", "00000100") + decoder = Kafka::Protocol::Decoder.new(io) + + expect(decoder.varint).to eq -300 + end + end + + context 'data is stored in 3 groups' do + it do + io = new_io_from_binaries("10000001", "10100011", "00011010") + decoder = Kafka::Protocol::Decoder.new(io) - expect(decoder.varint).to eq 9990834290 + expect(decoder.varint).to eq -215233 + end end end end
Support signed integer for varint decoder
zendesk_ruby-kafka
train
e70291d130c88359af553f775e3bd3b41c7b5386
diff --git a/internal/services/cosmos/validate/cosmos.go b/internal/services/cosmos/validate/cosmos.go index <HASH>..<HASH> 100644 --- a/internal/services/cosmos/validate/cosmos.go +++ b/internal/services/cosmos/validate/cosmos.go @@ -50,9 +50,9 @@ func CosmosMaxThroughput(i interface{}, k string) (warnings []string, errors []e return } - if v < 4000 { + if v < 1000 { errors = append(errors, fmt.Errorf( - "%s must be a minimum of 4000", k)) + "%s must be a minimum of 1000", k)) } if v%1000 != 0 {
fix: 🐛 Adjust minimum limit of max_throughput validation (#<I>) Addresses issue #<I> (fixed #<I>)
terraform-providers_terraform-provider-azurerm
train
4147815785a42bb5336bf839613eb841641251e1
diff --git a/es2015/transaction/ReadOnlyTransaction.js b/es2015/transaction/ReadOnlyTransaction.js index <HASH>..<HASH> 100644 --- a/es2015/transaction/ReadOnlyTransaction.js +++ b/es2015/transaction/ReadOnlyTransaction.js @@ -82,7 +82,9 @@ export default class ReadOnlyTransaction { this.completionPromise = new Promise((resolve, reject) => { this.addCompleteListener(resolve) this.addAbortListener(() => { - reject(new Error("The transaction has been aborted")) + let abortError = new Error("The transaction has been aborted") + abortError.name = "AbortError" + reject(abortError) }) this.addErrorListener(reject) }) diff --git a/test/transaction/ReadOnlyTransactionSpec.js b/test/transaction/ReadOnlyTransactionSpec.js index <HASH>..<HASH> 100644 --- a/test/transaction/ReadOnlyTransactionSpec.js +++ b/test/transaction/ReadOnlyTransactionSpec.js @@ -38,9 +38,13 @@ describe("ReadOnlyTransaction", () => { }) it("should provide promise rejected on abort", (done) => { - transaction.completionPromise. - then(() => fail("The transaction cannot complete if aborted")). - catch(() => done()) + transaction.completionPromise.then(() => { + fail("The transaction cannot complete if aborted") + done() + }).catch((error) => { + expect(error.name).toBe("AbortError") + done() + }) transaction.abort() })
the error used to reject to transaction's completion promise now bears the "AbortError" name to make to "successful rejection error" easier to distinguish from other errors
jurca_indexed-db.es6
train
377980029134b75714ba9a1d448416bd2f3d45a3
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ setup( "Framework :: Django :: 1.11", "Framework :: Django :: 2.1", "Framework :: Django :: 2.2", -# "Framework :: Django :: 3.0", + "Framework :: Django :: 3.0", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: JavaScript",
Re-added trove classifier for Django <I>.
django-crispy-forms_django-crispy-forms
train
503154a553236ae5768fd8f129d98e5f8294394a
diff --git a/src/java/org/archive/wayback/query/UIQueryResults.java b/src/java/org/archive/wayback/query/UIQueryResults.java index <HASH>..<HASH> 100644 --- a/src/java/org/archive/wayback/query/UIQueryResults.java +++ b/src/java/org/archive/wayback/query/UIQueryResults.java @@ -334,4 +334,11 @@ public class UIQueryResults { return exactRequestedTimestamp; } + /** + * @param key + * @return Localized String version of key + */ + public String getLocalized(String key) { + return wbRequest.getLocalized(key); + } } diff --git a/src/java/org/archive/wayback/replay/UIReplayResult.java b/src/java/org/archive/wayback/replay/UIReplayResult.java index <HASH>..<HASH> 100644 --- a/src/java/org/archive/wayback/replay/UIReplayResult.java +++ b/src/java/org/archive/wayback/replay/UIReplayResult.java @@ -155,4 +155,12 @@ public class UIReplayResult { public Properties getHttpHeaders() { return resource.getHttpHeaders(); } + /** + * @param key + * @return Localized String version of key + */ + public String getLocalized(String key) { + return wbRequest.getLocalized(key); + } + }
FEATURE: pass-thru getLocalized() method to expose the localized key lookup functionality in the WaybackRequest to jsp's. git-svn-id: <URL>
iipc_openwayback
train
9fb005b17a515e1a4547f19d4bdcc498eec81aad
diff --git a/lib/sidekiq_unique_jobs/orphans/manager.rb b/lib/sidekiq_unique_jobs/orphans/manager.rb index <HASH>..<HASH> 100644 --- a/lib/sidekiq_unique_jobs/orphans/manager.rb +++ b/lib/sidekiq_unique_jobs/orphans/manager.rb @@ -10,6 +10,8 @@ module SidekiqUniqueJobs module Manager module_function + DRIFT_FACTOR = 0.02 + include SidekiqUniqueJobs::Connection include SidekiqUniqueJobs::Logging @@ -56,6 +58,7 @@ module SidekiqUniqueJobs @task ||= Concurrent::TimerTask.new(timer_task_options) do with_logging_context do redis do |conn| + refresh_reaper_mutex Orphans::Reaper.call(conn) end end @@ -117,7 +120,9 @@ module SidekiqUniqueJobs # @return [true, false] # def registered? - redis { |conn| conn.get(UNIQUE_REAPER) }.to_i == 1 + redis do |conn| + conn.get(UNIQUE_REAPER).to_i + drift_reaper_interval > current_timestamp + end end def disabled? @@ -131,7 +136,17 @@ module SidekiqUniqueJobs # @return [void] # def register_reaper_process - redis { |conn| conn.set(UNIQUE_REAPER, 1) } + redis { |conn| conn.set(UNIQUE_REAPER, current_timestamp, nx: true, ex: drift_reaper_interval) } + end + + # + # Updates mutex key + # + # + # @return [void] + # + def refresh_reaper_mutex + redis { |conn| conn.set(UNIQUE_REAPER, current_timestamp, ex: drift_reaper_interval) } end # @@ -143,6 +158,14 @@ module SidekiqUniqueJobs def unregister_reaper_process redis { |conn| conn.del(UNIQUE_REAPER) } end + + def drift_reaper_interval + reaper_interval + (reaper_interval * DRIFT_FACTOR).to_i + end + + def current_timestamp + Time.now.to_i + end end end end diff --git a/spec/sidekiq_unique_jobs/orphans/manager_spec.rb b/spec/sidekiq_unique_jobs/orphans/manager_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sidekiq_unique_jobs/orphans/manager_spec.rb +++ b/spec/sidekiq_unique_jobs/orphans/manager_spec.rb @@ -7,6 +7,12 @@ RSpec.describe SidekiqUniqueJobs::Orphans::Manager do describe ".start" do subject(:start) { described_class.start } + let(:frozen_time) { Time.new(1982, 6, 8, 14, 15, 34) } + + around do |example| + Timecop.freeze(frozen_time, &example) + end + before do allow(SidekiqUniqueJobs::Orphans::Observer).to receive(:new).and_return(observer) @@ -18,7 +24,7 @@ RSpec.describe SidekiqUniqueJobs::Orphans::Manager do end context "when registered?" do - before { redis { |conn| conn.set(SidekiqUniqueJobs::UNIQUE_REAPER, 1) } } + before { described_class.register_reaper_process } it { is_expected.to eq(nil) } end @@ -29,7 +35,7 @@ RSpec.describe SidekiqUniqueJobs::Orphans::Manager do it "sets a mutex" do start - expect(get(SidekiqUniqueJobs::UNIQUE_REAPER)).to eq("1") + expect(get(SidekiqUniqueJobs::UNIQUE_REAPER)).to eq(frozen_time.to_i.to_s) end it "logs a start message" do @@ -111,6 +117,23 @@ RSpec.describe SidekiqUniqueJobs::Orphans::Manager do it { is_expected.to eq(SidekiqUniqueJobs.config.reaper_timeout) } end + describe ".register_reaper_process" do + subject(:register_reaper_process) { described_class.register_reaper_process } + + let(:frozen_time) { Time.new(1982, 6, 8, 14, 15, 34) } + + around do |example| + Timecop.freeze(frozen_time, &example) + end + + it "writes a redis key with timestamp" do + expect { register_reaper_process }.to change { get(SidekiqUniqueJobs::UNIQUE_REAPER) } + .from(nil).to(frozen_time.to_i.to_s) + + expect(ttl(SidekiqUniqueJobs::UNIQUE_REAPER)).to be_within(20).of(SidekiqUniqueJobs.config.reaper_interval) + end + end + describe ".logging_context" do subject(:logging_context) { described_class.logging_context } diff --git a/spec/sidekiq_unique_jobs/web/helpers_spec.rb b/spec/sidekiq_unique_jobs/web/helpers_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sidekiq_unique_jobs/web/helpers_spec.rb +++ b/spec/sidekiq_unique_jobs/web/helpers_spec.rb @@ -10,9 +10,9 @@ RSpec.describe SidekiqUniqueJobs::Web::Helpers do let(:time) { Time.now.to_f } let(:stamp) { Time.now.getutc.iso8601 } - before { Timecop.freeze(frozen_time) } - - after { Timecop.return } + around do |example| + Timecop.freeze(frozen_time, &example) + end it "returns relative time html" do expect(safe_relative_time).to eq(<<~HTML.chop) @@ -26,9 +26,9 @@ RSpec.describe SidekiqUniqueJobs::Web::Helpers do let(:frozen_time) { Time.new(1982, 6, 8, 14, 15, 34) } - before { Timecop.freeze(frozen_time) } - - after { Timecop.return } + around do |example| + Timecop.freeze(frozen_time, &example) + end context "when time is an Integer" do let(:time) { Time.now.to_i }
Expire reaper when not checking in (#<I>) Close #<I>
mhenrixon_sidekiq-unique-jobs
train
5573ca642a66a04ca5422a381d868ff0c082e39d
diff --git a/core/resource/ResourceServiceProvider.php b/core/resource/ResourceServiceProvider.php index <HASH>..<HASH> 100644 --- a/core/resource/ResourceServiceProvider.php +++ b/core/resource/ResourceServiceProvider.php @@ -40,6 +40,7 @@ class ResourceServiceProvider implements ContainerServiceProviderInterface $services ->set(ClassRepository::class, ClassRepository::class) + ->public() ->args( [ service(Ontology::SERVICE_ID), @@ -49,6 +50,7 @@ class ResourceServiceProvider implements ContainerServiceProviderInterface $services ->set(ResourceRepository::class, ResourceRepository::class) + ->public() ->args( [ service(Ontology::SERVICE_ID), diff --git a/test/unit/core/kernel/persistence/OntologyRdfsTest.php b/test/unit/core/kernel/persistence/OntologyRdfsTest.php index <HASH>..<HASH> 100755 --- a/test/unit/core/kernel/persistence/OntologyRdfsTest.php +++ b/test/unit/core/kernel/persistence/OntologyRdfsTest.php @@ -109,19 +109,6 @@ class OntologyRdfsTest extends GenerisTestCase $this->assertNotEquals($resource, $resourceClone); } - /** - * @dataProvider getOntologies - */ - public function testDeleteInstance(Ontology $model) - { - $class = $model->getClass('http://testing#class'); - $resource = $class->createInstance('sample'); - $this->assertInstanceOf(\core_kernel_classes_Resource::class, $resource); - $this->assertTrue($resource->exists()); - $resource->delete(); - $this->assertFalse($resource->exists()); - } - public function getOntologies() { return [
refactor: make repositories public
oat-sa_generis
train
153b1303a0fd4cc2aed7ffbd056a02b222b0491d
diff --git a/tests/cases/data/source/mongo_db/ExporterTest.php b/tests/cases/data/source/mongo_db/ExporterTest.php index <HASH>..<HASH> 100644 --- a/tests/cases/data/source/mongo_db/ExporterTest.php +++ b/tests/cases/data/source/mongo_db/ExporterTest.php @@ -310,6 +310,21 @@ class ExporterTest extends \lithium\test\Unit { $this->assertEqual($result['update'], $data); } + public function testWithArraySchemaReusedName() { + $model = $this->_model; + $model::schema(array( + '_id' => array('type' => 'id'), + 'foo' => array('array' => true), + 'foo.foo' => array('type' => 'integer'), + 'foo.bar' => array('type' => 'integer') + )); + $doc = new Document(compact('model')); + $doc->foo[] = array('foo' => 1, 'bar' => 100); + + $expected = array('foo' => array(array('foo' => 1, 'bar' => 100))); + $this->assertEqual($expected, $doc->data()); + } + /** * @todo Implement me. */
Adding tests for an issue regarding schema's defined as an array. The issue is that if a parents name is reused as a child, it's also defined as an array type.
UnionOfRAD_lithium
train
81ef5927d5b79c7d6ae7a7f3b0262a09f7f05281
diff --git a/crane/container.go b/crane/container.go index <HASH>..<HASH> 100644 --- a/crane/container.go +++ b/crane/container.go @@ -242,7 +242,10 @@ func (r *RunParameters) Cmd() []string { func (c *container) Id() string { if len(c.id) == 0 { - c.id = inspectString(c.Name(), "{{.Id}}") + // `docker inspect` works both for image or containers, make sure this is a + // container payload we get back, otherwise we might end up getting the Id + // of the image of the same name + c.id = inspectString(c.Name(), "{{if .State}}{{.Id}}{{else}}{{end}}") } return c.id } @@ -282,7 +285,7 @@ func (c *container) ImageExists() bool { func (c *container) Status() []string { fields := []string{c.Name(), c.Image(), "-", "-", "-", "-", "-"} - output := inspectString(c.Name(), "{{.Id}}\t{{.Image}}\t{{if .NetworkSettings.IPAddress}}{{.NetworkSettings.IPAddress}}{{else}}-{{end}}\t{{range $k,$v := $.NetworkSettings.Ports}}{{$k}},{{else}}-{{end}}\t{{.State.Running}}") + output := inspectString(c.Id(), "{{.Id}}\t{{.Image}}\t{{if .NetworkSettings.IPAddress}}{{.NetworkSettings.IPAddress}}{{else}}-{{end}}\t{{range $k,$v := $.NetworkSettings.Ports}}{{$k}},{{else}}-{{end}}\t{{.State.Running}}") if output != "" { copy(fields[2:], strings.Split(output, "\t")) // we asked for the image id the container was created from
make sure we inspect containers, not images
michaelsauter_crane
train
a6d61cb5d66ede0370cde88e0af842e67f4cfef4
diff --git a/lxd/db/network_acls.go b/lxd/db/network_acls.go index <HASH>..<HASH> 100644 --- a/lxd/db/network_acls.go +++ b/lxd/db/network_acls.go @@ -266,3 +266,11 @@ func (c *Cluster) RenameNetworkACL(id int64, newName string) error { return err }) } + +// DeleteNetworkACL deletes the Network ACL. +func (c *Cluster) DeleteNetworkACL(id int64) error { + return c.Transaction(func(tx *ClusterTx) error { + _, err := tx.tx.Exec("DELETE FROM networks_acls WHERE id=?", id) + return err + }) +}
lxd/db/network/acls: Adds DeleteNetworkACL function
lxc_lxd
train
10a70b21baac01cdc2c613904d7bae715d3c4358
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -114,8 +114,6 @@ def run_apidoc(_): # such. def skip_loader_hooks(app, what, name, obj, skip, options): if name == 'get_node' or name == 'get_single_node': - app.info('running hook: {} {} {}'.format(name, type(obj), dir(obj))) - app.info('{}'.format(obj.__qualname__)) return True return skip
Remove debug output in doc build
yatiml_yatiml
train
d0e319eb740051c685b711374815679483136cae
diff --git a/app/helpers/sufia/sufia_helper_behavior.rb b/app/helpers/sufia/sufia_helper_behavior.rb index <HASH>..<HASH> 100644 --- a/app/helpers/sufia/sufia_helper_behavior.rb +++ b/app/helpers/sufia/sufia_helper_behavior.rb @@ -220,7 +220,7 @@ module Sufia else "default.png" end - options[:alt] = " " + options[:alt] = "" image_tag path, options end end
Fixed open alt tag that I incorrectly set previously to address accessibility
samvera_hyrax
train
ab50ec1215042ceb21804efd6ab30fa56214d312
diff --git a/user/editadvanced_form.php b/user/editadvanced_form.php index <HASH>..<HASH> 100644 --- a/user/editadvanced_form.php +++ b/user/editadvanced_form.php @@ -35,14 +35,11 @@ class user_editadvanced_form extends moodleform { $mform->setAdvanced('auth'); $mform->addElement('passwordunmask', 'newpassword', get_string('newpassword'), 'size="20"'); - $mform->setHelpButton('newpassword', array(false, get_string('leavetokeep'), - false, true, false, get_string('leavetokeep'))); + $mform->setHelpButton('newpassword',array('newpassword', get_string('leavetokeep'))); $mform->setType('newpassword', PARAM_RAW); $mform->addElement('advcheckbox', 'preference_auth_forcepasswordchange', get_string('forcepasswordchange')); - $mform->setHelpButton('preference_auth_forcepasswordchange', array(false, get_string('forcepasswordchangehelp'), - false, true, false, get_string('forcepasswordchangehelp'))); - + $mform->setHelpButton('preference_auth_forcepasswordchange',array('forcepasswordchange', get_string('forcepasswordchange'))); /// shared fields useredit_shared_definition($mform); diff --git a/user/editlib.php b/user/editlib.php index <HASH>..<HASH> 100644 --- a/user/editlib.php +++ b/user/editlib.php @@ -224,8 +224,8 @@ function useredit_shared_definition(&$mform) { if ( !empty($CFG->usetags) && has_capability('moodle/tag:create', get_context_instance(CONTEXT_SYSTEM)) ) { $mform->addElement('header', 'moodle_interests', get_string('interests')); $mform->addElement('textarea', 'interests', get_string('interestslist'), 'cols="45" rows="3"'); - $mform->setHelpButton('interests', array(false, get_string('helpinterestslist'), - false, true, false, get_string('helpinterestslist'))); + $mform->setHelpButton('interests', array('interestslist', get_string('helpinterestslist'), + false, true, false)); } /// Moodle optional fields
MDL-<I> fix user profil help icons, merged from <I>
moodle_moodle
train
30d634f59bcfb0f0609c2206eca58328994e6100
diff --git a/src/DynamoDbClientInterface.php b/src/DynamoDbClientInterface.php index <HASH>..<HASH> 100644 --- a/src/DynamoDbClientInterface.php +++ b/src/DynamoDbClientInterface.php @@ -4,6 +4,9 @@ namespace BaoPham\DynamoDb; interface DynamoDbClientInterface { + /** + * @param string @name + */ function getClient($name = null); function getMarshaler(); diff --git a/src/DynamoDbClientService.php b/src/DynamoDbClientService.php index <HASH>..<HASH> 100644 --- a/src/DynamoDbClientService.php +++ b/src/DynamoDbClientService.php @@ -39,6 +39,7 @@ class DynamoDbClientService implements DynamoDbClientInterface } /** + * @param string $name * @return \Aws\DynamoDb\DynamoDbClient */ public function getClient($name = null) diff --git a/src/DynamoDbModel.php b/src/DynamoDbModel.php index <HASH>..<HASH> 100644 --- a/src/DynamoDbModel.php +++ b/src/DynamoDbModel.php @@ -351,6 +351,9 @@ abstract class DynamoDbModel extends Model return $key; } + /** + * Get the key for this model whether composite or simple. + */ protected static function getModelKey($id, $model) { if (is_array($id)) {
Reformatted for psr-2; Refactor the DynamoDbModel and create getModelKey(); Add support for multiple client configurations;
baopham_laravel-dynamodb
train
7d5d7a523897f904a4cf1e9bc5ec4a0c9699e082
diff --git a/lib/rufus/edo/cabinet/abstract.rb b/lib/rufus/edo/cabinet/abstract.rb index <HASH>..<HASH> 100644 --- a/lib/rufus/edo/cabinet/abstract.rb +++ b/lib/rufus/edo/cabinet/abstract.rb @@ -109,8 +109,6 @@ module Rufus::Edo # * :apow size of record alignment by power of 2 (defaults to 4) # * :fpow maximum number of elements of the free block pool by # power of 2 (defaults to 10) - # * :mutex when set to true, makes sure only 1 thread at a time - # accesses the table (well, Ruby, global thread lock, ...) # # * :rcnum specifies the maximum number of records to be cached. # If it is not more than 0, the record cache is disabled.
no way to setmutex via Hirabayashi-san's ruby code. Commented out :mutex mention.
jmettraux_rufus-tokyo
train
dfe1e237d3756c77923c05fcf77904d811b51f73
diff --git a/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java b/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java index <HASH>..<HASH> 100644 --- a/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java +++ b/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java @@ -1507,6 +1507,12 @@ public abstract class ProvFactory implements LiteralConstructor, ModelConstructo if (statement instanceof HasType) result.addAll(((HasType)statement).getType()); if (statement instanceof HasLocation) result.addAll(((HasLocation)statement).getLocation()); if (statement instanceof HasRole) result.addAll(((HasRole)statement).getRole()); + if (statement instanceof HasValue) { + Value val=((HasValue)statement).getValue(); + if (val!=null) { + result.add(val); + } + } if (statement instanceof HasOther) { for (Other o: ((HasOther)statement).getOther()) { result.add((Attribute)o);
add prov:value to the list of attributes to return (fixing omission)
lucmoreau_ProvToolbox
train
5b8fc3c492aa96e6622b2b523553c0aebf3d9af2
diff --git a/lib/protobuf/version.rb b/lib/protobuf/version.rb index <HASH>..<HASH> 100644 --- a/lib/protobuf/version.rb +++ b/lib/protobuf/version.rb @@ -1,4 +1,4 @@ module Protobuf VERSION = '2.7.11' - PROTOC_VERSION = '2.4.1' + PROTOC_VERSION = '2.5.0' end
Set PROTOC_VERSION to <I>
ruby-protobuf_protobuf
train
bff80c0abe4ddef6f610c0c6d6ebd663992841d9
diff --git a/Gemfile b/Gemfile index <HASH>..<HASH> 100644 --- a/Gemfile +++ b/Gemfile @@ -28,7 +28,7 @@ end # installed on Travis CI # group :test do - gem 'rack-test', '~> 0.5.4' - gem 'test-unit', '~> 2.3' - gem 'shoulda', '~> 2.11.3' + gem 'rack-test' + gem 'test-unit' + gem 'shoulda' end diff --git a/test/helper.rb b/test/helper.rb index <HASH>..<HASH> 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -13,7 +13,7 @@ class Test::Unit::TestCase def app; Rack::Lint.new(@app); end - def mock_app(options = {}) + def mock_app(options_or_options_array = {}) main_app = lambda { |env| request = Rack::Request.new(env) headers = {'Content-Type' => "text/html"} @@ -22,7 +22,10 @@ class Test::Unit::TestCase } builder = Rack::Builder.new - builder.use Rack::SslEnforcer, options + options_or_options_array = [options_or_options_array] unless options_or_options_array.is_a?(Array) + Array(options_or_options_array).each do |options| + builder.use Rack::SslEnforcer, options + end builder.run main_app @app = builder.to_app end diff --git a/test/rack-ssl-enforcer_test.rb b/test/rack-ssl-enforcer_test.rb index <HASH>..<HASH> 100644 --- a/test/rack-ssl-enforcer_test.rb +++ b/test/rack-ssl-enforcer_test.rb @@ -949,4 +949,43 @@ class TestRackSslEnforcer < Test::Unit::TestCase end end + context 'complex example with multiple statements' do + setup { + mock_app([ + { :only_hosts => %r{api.example.org} }, + { :except_hosts => %r{api.example.com}, :only => %r{^/users}, :ignore => %r{^/assets}, :strict => true } + ]) + } + + should 'redirect to HTTPS for http://api.example.org' do + get 'http://api.example.org' + assert_equal 301, last_response.status + assert_equal 'https://api.example.org/', last_response.location + end + + should 'redirect to HTTPS for http://example.org/users/foo' do + get 'http://www.example.org/users/foo' + assert_equal 301, last_response.status + assert_equal 'https://www.example.org/users/foo', last_response.location + end + + should 'leave HTTP as is for /assets' do + get 'http://www.example.org/assets' + assert_equal 200, last_response.status + assert_equal 'Hello world!', last_response.body + end + + should 'leave HTTPS as is for /assets' do + get 'https://www.example.org/assets' + assert_equal 200, last_response.status + assert_equal 'Hello world!', last_response.body + end + + should 'redirect to HTTP for other paths' do + get 'https://www.example.org/foo' + assert_equal 301, last_response.status + assert_equal 'http://www.example.org/foo', last_response.location + end + end + end
Add a complex example to represent #<I> use-case
tobmatth_rack-ssl-enforcer
train
21551c2378b1f56f358d72beb814befb38ff0b25
diff --git a/jax/version.py b/jax/version.py index <HASH>..<HASH> 100644 --- a/jax/version.py +++ b/jax/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.1.57" +__version__ = "0.1.58"
Bump JAX version to <I>.
tensorflow_probability
train
5aaab806968fe49304e4d0d6396de1231a4890d7
diff --git a/lib/core.js b/lib/core.js index <HASH>..<HASH> 100644 --- a/lib/core.js +++ b/lib/core.js @@ -19,7 +19,9 @@ module.exports = function(opts, cb) { return raja; }; -function Raja(opts) { this.opts = opts || {}; } +function Raja(opts) { + this.opts = opts || {}; +} Raja.prototype.init = function(cb) { q(2) diff --git a/lib/proxies/dom.js b/lib/proxies/dom.js index <HASH>..<HASH> 100644 --- a/lib/proxies/dom.js +++ b/lib/proxies/dom.js @@ -73,7 +73,11 @@ function DomProxy(raja, dom) { dom.Handler.prototype.loadLocal = this.local.get.bind(this.local); dom.Handler.prototype.loadRemote = this.remote.get.bind(this.remote); - dom.Handler.prototype.build = CacheOnDemand(dom.Handler.prototype.build, function(inst) { + var build = dom.Handler.prototype.build; + dom.Handler.prototype.build = CacheOnDemand(function(inst, req, res, cb) { + res.set('X-Raja', raja.opts.namespace); + build.call(this, inst, req, res, cb); + },function(inst) { return inst.url; }); diff --git a/lib/proxies/express.js b/lib/proxies/express.js index <HASH>..<HASH> 100644 --- a/lib/proxies/express.js +++ b/lib/proxies/express.js @@ -19,6 +19,7 @@ ExpressProxy.prototype.middleware = function(req, res, next) { if (req.method == "GET") { this.raja.store.get(url, function(err, resource) { if (err) raja.error(err); // fall through + res.set('X-Raja', raja.opts.namespace); if (resource && resource.valid) { res.set('Last-Modified', resource.mtime.toUTCString()); if (resource.mime) res.type(resource.mime); diff --git a/lib/proxies/static.js b/lib/proxies/static.js index <HASH>..<HASH> 100644 --- a/lib/proxies/static.js +++ b/lib/proxies/static.js @@ -15,6 +15,7 @@ function StaticProxy(raja, root) { } StaticProxy.prototype.middleware = function(req, res, next) { + res.set('X-Raja', this.raja.opts.namespace); var url = req.protocol + "://" + req.get('Host') + req.url; var path = this.root + req.url;
Output X-Raja header when a resource is tracked
kapouer_raja
train