content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | remove unused test class | 9b487b939c93e64204401a9c7f7fbb3797876dd7 | <ide><path>activesupport/test/test_case_test.rb
<ide> def test_assert_no_changes_with_message
<ide> end
<ide> end
<ide>
<del>class AlsoDoingNothingTest < ActiveSupport::TestCase
<del>end
<del>
<ide> # Setup and teardown callbacks.
<ide> class SetupAndTeardownTest < ActiveSupport::TestCase
<ide> setup :reset_callback_record, :foo | 1 |
Ruby | Ruby | avoid unnecessary string interpolation | 8ab2fb6868497023e369df939690af2a101ecafc | <ide><path>Library/Homebrew/utils/analytics.rb
<ide> def report_analytics(type, metadata={})
<ide> # https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
<ide> system ENV["HOMEBREW_CURL"], "https://www.google-analytics.com/collect",
<ide> "-d", "v=1", "--silent", "--max-time", "3", "--output", "/dev/null",
<del> "--user-agent", "#{HOMEBREW_USER_AGENT_CURL}",
<add> "--user-agent", HOMEBREW_USER_AGENT_CURL,
<ide> "-d", "tid=#{ENV["HOMEBREW_ANALYTICS_ID"]}",
<ide> "-d", "cid=#{ENV["HOMEBREW_ANALYTICS_USER_UUID"]}",
<ide> "-d", "aip=1", | 1 |
Text | Text | add missing step to npm release process | 21b739fb69850763f5d18ef864f592cc9a843de4 | <ide><path>doc/guides/maintaining-npm.md
<ide> or if you already have npm cloned make sure the repo is up to date
<ide>
<ide> ```console
<ide> $ git remote update -p
<del>$ git reset --hard origin latest
<add>$ git reset --hard origin/latest
<ide> ```
<ide>
<ide> ## Step 2: Build release
<ide>
<ide> ```console
<ide> $ git checkout vX.Y.Z
<add>$ make
<ide> $ make release
<ide> ```
<ide> | 1 |
Javascript | Javascript | increase epsilon for min_max tests | effe9ce7e9ec2e95b971898e5f01e6d660522a2e | <ide><path>test/moment/min_max.js
<ide> exports.min_max = {
<ide>
<ide> var now = moment(),
<ide> future = now.clone().add(1, 'month'),
<del> past = now.clone().subtract(1, 'month');
<add> past = now.clone().subtract(1, 'month'),
<add> eps = 10;
<ide>
<del> // we use Math.abs(a.diff(b)) < 2 to prevent issues where
<add> // we use Math.abs(a.diff(b)) < eps to prevent issues where
<ide> // two moments are off by a millisecond.
<ide>
<del> test.ok(Math.abs(past.min(now).diff(now)) < 2, "A past date with the minimum of now should be now");
<del> test.ok(Math.abs(past.min().diff(now)) < 2, "A past date with the minimum of implied now should be now");
<del> test.ok(Math.abs(past.min(future).diff(future)) < 2, "A past date with the minimum of the future should be the future date");
<add> test.ok(Math.abs(past.min(now).diff(now)) < eps, "A past date with the minimum of now should be now");
<add> test.ok(Math.abs(past.min().diff(now)) < eps, "A past date with the minimum of implied now should be now");
<add> test.ok(Math.abs(past.min(future).diff(future)) < eps, "A past date with the minimum of the future should be the future date");
<ide>
<del> test.ok(Math.abs(future.min(now).diff(future)) < 2, "A future date with the minimum of now should be the future");
<del> test.ok(Math.abs(future.min().diff(future)) < 2, "A future date with the minimum of implied now should be the future");
<del> test.ok(Math.abs(future.min(past).diff(future)) < 2, "A future date with the minimum of the past should be the future");
<add> test.ok(Math.abs(future.min(now).diff(future)) < eps, "A future date with the minimum of now should be the future");
<add> test.ok(Math.abs(future.min().diff(future)) < eps, "A future date with the minimum of implied now should be the future");
<add> test.ok(Math.abs(future.min(past).diff(future)) < eps, "A future date with the minimum of the past should be the future");
<ide>
<del> test.ok(Math.abs(now.min(past).diff(now)) < 2, "Now with the minimum of the past should be now");
<del> test.ok(Math.abs(now.min(future).diff(future)) < 2, "Now with the minimum of the future should be the future");
<add> test.ok(Math.abs(now.min(past).diff(now)) < eps, "Now with the minimum of the past should be now");
<add> test.ok(Math.abs(now.min(future).diff(future)) < eps, "Now with the minimum of the future should be the future");
<ide>
<ide> test.done();
<ide> },
<ide> exports.min_max = {
<ide>
<ide> var now = moment(),
<ide> future = now.clone().add(1, 'month'),
<del> past = now.clone().subtract(1, 'month');
<add> past = now.clone().subtract(1, 'month'),
<add> eps = 10;
<ide>
<del> // we use Math.abs(a.diff(b)) < 2 to prevent issues where
<add> // we use Math.abs(a.diff(b)) < eps to prevent issues where
<ide> // two moments are off by a millisecond.
<ide>
<del> test.ok(Math.abs(past.max(now).diff(past)) < 2, "A past date with the maximum of now should be the past");
<del> test.ok(Math.abs(past.max().diff(past)) < 2, "A past date with the maximum of implied now should be the past");
<del> test.ok(Math.abs(past.max(future).diff(past)) < 2, "A past date with the maximum of the future should be the past");
<add> test.ok(Math.abs(past.max(now).diff(past)) < eps, "A past date with the maximum of now should be the past");
<add> test.ok(Math.abs(past.max().diff(past)) < eps, "A past date with the maximum of implied now should be the past");
<add> test.ok(Math.abs(past.max(future).diff(past)) < eps, "A past date with the maximum of the future should be the past");
<ide>
<del> test.ok(Math.abs(future.max(now).diff(now)) < 2, "A future date with the maximum of now should be now");
<del> test.ok(Math.abs(future.max().diff(now)) < 2, "A future date with the maximum of implied now should be now");
<del> test.ok(Math.abs(future.max(past).diff(past)) < 2, "A future date with the maximum of the past should be the past");
<add> test.ok(Math.abs(future.max(now).diff(now)) < eps, "A future date with the maximum of now should be now");
<add> test.ok(Math.abs(future.max().diff(now)) < eps, "A future date with the maximum of implied now should be now");
<add> test.ok(Math.abs(future.max(past).diff(past)) < eps, "A future date with the maximum of the past should be the past");
<ide>
<del> test.ok(Math.abs(now.max(past).diff(past)) < 2, "Now with the maximum of the past should be the past");
<del> test.ok(Math.abs(now.max(future).diff(now)) < 2, "Now with the maximum of the future should be now");
<add> test.ok(Math.abs(now.max(past).diff(past)) < eps, "Now with the maximum of the past should be the past");
<add> test.ok(Math.abs(now.max(future).diff(now)) < eps, "Now with the maximum of the future should be now");
<ide>
<ide> test.done();
<ide> } | 1 |
Python | Python | specify column length | 234d76641f1b23887fd60fe90fc4a1126e2a5d67 | <ide><path>airflow/models.py
<ide> class XCom(Base):
<ide> __tablename__ = "xcom"
<ide>
<ide> id = Column(Integer, primary_key=True)
<del> key = Column(String)
<add> key = Column(String(512))
<ide> value = Column(PickleType(pickler=dill))
<ide> timestamp = Column(DateTime, server_default=func.current_timestamp())
<ide> execution_date = Column(DateTime, nullable=False) | 1 |
Javascript | Javascript | maintain rootid for lazily crawled trees | f352fe2625bc91e65f563def0b351dd5d915c11c | <ide><path>src/backend/legacy/renderer.js
<ide> export function attach(
<ide> idToInternalInstanceMap.delete(id);
<ide> }
<ide>
<del> function crawlAndRecordInitialMounts(id: number, parentID: number) {
<add> function crawlAndRecordInitialMounts(
<add> id: number,
<add> parentID: number,
<add> rootID: number
<add> ) {
<ide> const internalInstance = idToInternalInstanceMap.get(id);
<ide>
<ide> if (__DEBUG__) {
<ide> console.group('crawlAndRecordInitialMounts() id:', id);
<ide> }
<ide>
<add> internalInstanceToRootIDMap.set(internalInstance, rootID);
<ide> recordMount(internalInstance, id, parentID);
<ide> getChildren(internalInstance).forEach(child =>
<del> crawlAndRecordInitialMounts(getID(child), id)
<add> crawlAndRecordInitialMounts(getID(child), id, rootID)
<ide> );
<ide>
<ide> if (__DEBUG__) {
<ide> export function attach(
<ide> for (let key in roots) {
<ide> const internalInstance = roots[key];
<ide> const id = getID(internalInstance);
<del> crawlAndRecordInitialMounts(id, 0);
<add> crawlAndRecordInitialMounts(id, 0, id);
<ide> flushPendingEvents(id);
<ide> }
<ide> } | 1 |
Python | Python | add header attribute to iresponse | 278ae183e039f00f18f70350a531df0797e4ce81 | <ide><path>libcloud/interface.py
<ide> class IResponse(Interface):
<ide>
<ide> tree = Attribute("""The processed response tree, e.g. via lxml""")
<ide> body = Attribute("""Unparsed response body""")
<del> status_code = Attribute("""response status code""")
<add> status = Attribute("""Response status code""")
<add> headers = Attribute("""Response headers""")
<ide> error = Attribute("""Response error, L{None} if no error.""")
<ide>
<ide> def parse_body(): | 1 |
Ruby | Ruby | pass the requested spec into the formula instance | 5beaa512e61f7222d4f19569b8118f9e1f02a18f | <ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide>
<ide> attr_accessor :local_bottle_path
<ide>
<del> def initialize(name, path)
<add> def initialize(name, path, spec)
<ide> @name = name
<ide> @path = path
<ide> @homepage = self.class.homepage
<ide><path>Library/Homebrew/formulary.rb
<ide> def initialize(name, path)
<ide> end
<ide>
<ide> # Gets the formula instance.
<del> def get_formula
<del> klass.new(name, path)
<add> def get_formula(spec)
<add> klass.new(name, path, spec)
<ide> end
<ide>
<ide> # Return the Class for this formula, `require`-ing it if
<ide> def initialize bottle_name
<ide> super name, Formula.path(name)
<ide> end
<ide>
<del> def get_formula
<add> def get_formula(spec)
<ide> formula = super
<ide> formula.local_bottle_path = @bottle_filename
<ide> formula
<ide> def fetch
<ide> end
<ide> end
<ide>
<del> def get_formula
<add> def get_formula(spec)
<ide> fetch
<ide> super
<ide> end
<ide> def initialize tapped_name
<ide> super name, path
<ide> end
<ide>
<del> def get_formula
<add> def get_formula(spec)
<ide> super
<ide> rescue FormulaUnavailableError
<ide> raise TapFormulaUnavailableError.new(tapped_name)
<ide> def get_formula
<ide> # * a formula pathname
<ide> # * a formula URL
<ide> # * a local bottle reference
<del> def self.factory ref
<del> loader_for(ref).get_formula
<add> def self.factory(ref, spec=:stable)
<add> loader_for(ref).get_formula(spec)
<ide> end
<ide>
<ide> def self.canonical_name(ref)
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_formula_instantiation
<ide> klass = Class.new(Formula) { url "http://example.com/foo-1.0.tar.gz" }
<ide> name = "formula_name"
<ide> path = Formula.path(name)
<add> spec = :stable
<ide>
<del> f = klass.new(name, path)
<add> f = klass.new(name, path, spec)
<ide> assert_equal name, f.name
<ide> assert_equal path, f.path
<ide> assert_raises(ArgumentError) { klass.new }
<ide> def test_formula_spec_integration
<ide> bottle { sha1 TEST_SHA1 => bottle_tag }
<ide>
<ide> def initialize
<del> super "test", Pathname.new(__FILE__).expand_path
<add> super "test", Pathname.new(__FILE__).expand_path, :stable
<ide> end
<ide> end.new
<ide>
<ide><path>Library/Homebrew/test/test_formula_install.rb
<ide> def test_script_install
<ide> url "file://#{File.expand_path(__FILE__)}"
<ide> version "1"
<ide> def initialize
<del> super "test_script_formula", Pathname.new(__FILE__).expand_path
<add> super "test_script_formula", Pathname.new(__FILE__).expand_path, :stable
<ide> end
<ide> end.new
<ide>
<ide><path>Library/Homebrew/test/testball.rb
<ide> require 'formula'
<ide>
<ide> class TestBall < Formula
<del> def initialize(name="test_ball", path=Pathname.new(__FILE__).expand_path)
<add> def initialize(name="test_ball", path=Pathname.new(__FILE__).expand_path, spec=:stable)
<ide> self.class.instance_eval do
<ide> stable.url "file://#{TEST_DIRECTORY}/tarballs/testball-0.1.tbz"
<ide> stable.sha1 "482e737739d946b7c8cbaf127d9ee9c148b999f5"
<ide><path>Library/Homebrew/test/testing_env.rb
<ide> class TestCase < ::Minitest::Test
<ide> TEST_SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<ide> TEST_SHA256 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<ide>
<del> def formula(name="formula_name", path=Formula.path(name), &block)
<del> @_f = Class.new(Formula, &block).new(name, path)
<add> def formula(name="formula_name", path=Formula.path(name), spec=:stable, &block)
<add> @_f = Class.new(Formula, &block).new(name, path, spec)
<ide> end
<ide>
<ide> def shutup | 6 |
PHP | PHP | add early return to save some tabs | 5e7f1ffc9708298d87fe8fe0c361b8bf12055f35 | <ide><path>src/Console/Command/Task/FixtureTask.php
<ide> protected function _generateSchema($table) {
<ide> * @return array Formatted values
<ide> */
<ide> protected function _values($values) {
<del> $vals = array();
<del> if (is_array($values)) {
<del> foreach ($values as $key => $val) {
<del> if (is_array($val)) {
<del> $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
<add> $vals = [];
<add> if (!is_array($values)) {
<add> return $vals;
<add> }
<add> foreach ($values as $key => $val) {
<add> if (is_array($val)) {
<add> $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
<add> } else {
<add> $val = var_export($val, true);
<add> if ($val === 'NULL') {
<add> $val = 'null';
<add> }
<add> if (!is_numeric($key)) {
<add> $vals[] = "'{$key}' => {$val}";
<ide> } else {
<del> $val = var_export($val, true);
<del> if ($val === 'NULL') {
<del> $val = 'null';
<del> }
<del> if (!is_numeric($key)) {
<del> $vals[] = "'{$key}' => {$val}";
<del> } else {
<del> $vals[] = "{$val}";
<del> }
<add> $vals[] = "{$val}";
<ide> }
<ide> }
<ide> }
<ide> protected function _getRecordsFromTable($modelName, $useTable = null) {
<ide> }
<ide> $records = $model->find('all', [
<ide> 'conditions' => $conditions,
<del> 'recursive' => -1,
<ide> 'limit' => $recordCount
<ide> ]);
<ide> | 1 |
Javascript | Javascript | add the update for real now | 47010c1918c3ec5b0530d94b2b632390589d1e1f | <ide><path>utils/build.js
<ide> function buildIncludes(files, filename){
<ide> output(text.join("\n"), filename + '.js');
<ide> }
<ide>
<add>function getFileNames(){
<add> "use strict";
<add> var fileName = "utils/files.json";
<add> var data = JSON.parse(fs.readFileSync(fileName,'utf8'));
<add> return data;
<add>}
<ide>
<ide> function parse_args(){
<ide> "use strict";
<ide> function main(){
<ide> var args = parse_args();
<ide> var debug = args.debug;
<ide> var minified = args.minified;
<add> var files = getFileNames();
<ide>
<ide> var config = [
<del> ['Three', 'includes', '', COMMON_FILES.concat(EXTRAS_FILES), args.common],
<del> ['ThreeCanvas', 'includes_canvas', '', CANVAS_FILES, args.canvas],
<del> ['ThreeWebGL', 'includes_webgl', '', WEBGL_FILES, args.webgl],
<del> ['ThreeExtras', 'includes_extras', 'externs_extras', EXTRAS_FILES, args.extras]
<add> ['Three', 'includes', '', files["COMMON"].concat(files["EXTRAS"]), args.common],
<add> ['ThreeCanvas', 'includes_canvas', '', files["CANVAS"], args.canvas],
<add> ['ThreeWebGL', 'includes_webgl', '', files["WEBGL"], args.webgl],
<add> ['ThreeExtras', 'includes_extras', 'externs_extras', files["EXTRAS"], args.extras]
<ide> ];
<ide>
<ide> | 1 |
PHP | PHP | fix exception name | 253f22ad2e9687e6a5e3ee36e82846dfca943b89 | <ide><path>src/Illuminate/Foundation/Console/OptimizeCommand.php
<ide> <?php namespace Illuminate\Foundation\Console;
<ide>
<del>use InvalidParamException;
<add>use InvalidArgumentException;
<ide> use Illuminate\Console\Command;
<ide> use Illuminate\Foundation\Composer;
<ide> use Illuminate\View\Engines\CompilerEngine; | 1 |
Java | Java | restore use of tcpconfiguration method | 96bbec7ab2de85f26850127619623ef689e39400 | <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpConnector.java
<ide> public ReactorClientHttpConnector(ReactorResourceFactory factory, Function<HttpC
<ide> this.httpClient = defaultInitializer.andThen(mapper).apply(initHttpClient(factory));
<ide> }
<ide>
<add> @SuppressWarnings("deprecation")
<ide> private static HttpClient initHttpClient(ReactorResourceFactory resourceFactory) {
<ide> ConnectionProvider provider = resourceFactory.getConnectionProvider();
<ide> LoopResources resources = resourceFactory.getLoopResources();
<ide> Assert.notNull(provider, "No ConnectionProvider: is ReactorResourceFactory not initialized yet?");
<ide> Assert.notNull(resources, "No LoopResources: is ReactorResourceFactory not initialized yet?");
<del> return HttpClient.create(provider).runOn(resources);
<add> return HttpClient.create(provider).tcpConfiguration(tcpClient -> tcpClient.runOn(resources));
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | support unbounded time ranges for postgresql | 4479d811349db4cb0c35aa99d947f603d4bb49be | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb
<ide> def cast_value(value)
<ide> if !infinity?(from) && extracted[:exclude_start]
<ide> raise ArgumentError, "The Ruby Range object does not support excluding the beginning of a Range. (unsupported value: '#{value}')"
<ide> end
<del> ::Range.new(from, to, extracted[:exclude_end])
<add> ::Range.new(*sanitize_bounds(from, to), extracted[:exclude_end])
<ide> end
<ide>
<ide> def serialize(value)
<ide> def extract_bounds(value)
<ide> }
<ide> end
<ide>
<add> INFINITE_FLOAT_RANGE = (-::Float::INFINITY)..(::Float::INFINITY) # :nodoc:
<add>
<add> def sanitize_bounds(from, to)
<add> [
<add> (from == -::Float::INFINITY && !INFINITE_FLOAT_RANGE.cover?(to)) ? nil : from,
<add> (to == ::Float::INFINITY && !INFINITE_FLOAT_RANGE.cover?(from)) ? nil : to
<add> ]
<add> end
<add>
<ide> # When formatting the bound values of range types, PostgreSQL quotes
<ide> # the bound value using double-quotes in certain conditions. Within
<ide> # a double-quoted string, literal " and \ characters are themselves
<ide><path>activerecord/test/cases/adapters/postgresql/range_test.rb
<ide> def test_tsrange_values
<ide> tz = ::ActiveRecord.default_timezone
<ide> assert_equal Time.public_send(tz, 2010, 1, 1, 14, 30, 0)..Time.public_send(tz, 2011, 1, 1, 14, 30, 0), @first_range.ts_range
<ide> assert_equal Time.public_send(tz, 2010, 1, 1, 14, 30, 0)...Time.public_send(tz, 2011, 1, 1, 14, 30, 0), @second_range.ts_range
<add> assert_equal Time.public_send(tz, 2010, 1, 1, 14, 30, 0)...nil, @third_range.ts_range
<ide> assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.ts_range)
<ide> assert_nil @empty_range.ts_range
<ide> end
<ide>
<ide> def test_tstzrange_values
<ide> assert_equal Time.parse("2010-01-01 09:30:00 UTC")..Time.parse("2011-01-01 17:30:00 UTC"), @first_range.tstz_range
<ide> assert_equal Time.parse("2010-01-01 09:30:00 UTC")...Time.parse("2011-01-01 17:30:00 UTC"), @second_range.tstz_range
<add> assert_equal Time.parse("2010-01-01 09:30:00 UTC")...nil, @third_range.tstz_range
<ide> assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.tstz_range)
<ide> assert_nil @empty_range.tstz_range
<ide> end
<ide> def test_escaped_tstzrange
<ide> Time.parse("-1000-01-01 14:30:00 CDT")...Time.parse("2020-02-02 14:30:00 CET"))
<ide> end
<ide>
<add> def test_unbounded_tstzrange
<add> assert_equal_round_trip @first_range, :tstz_range, Time.parse("2010-01-01 14:30:00 CDT")...nil
<add> assert_equal_round_trip @first_range, :tstz_range, nil..Time.parse("2010-01-01 14:30:00 CDT")
<add> end
<add>
<ide> def test_create_tsrange
<ide> tz = ::ActiveRecord.default_timezone
<ide> assert_equal_round_trip(@new_range, :ts_range,
<ide> def test_escaped_tsrange
<ide> Time.public_send(tz, -1000, 1, 1, 14, 30, 0)...Time.public_send(tz, 2020, 2, 2, 14, 30, 0))
<ide> end
<ide>
<add> def test_unbounded_tsrange
<add> tz = ::ActiveRecord.default_timezone
<add> assert_equal_round_trip @first_range, :ts_range, Time.public_send(tz, 2010, 1, 1, 14, 30, 0)...nil
<add> assert_equal_round_trip @first_range, :ts_range, nil..Time.public_send(tz, 2010, 1, 1, 14, 30, 0)
<add> end
<add>
<ide> def test_timezone_awareness_tsrange
<ide> tz = "Pacific Time (US & Canada)"
<ide> | 2 |
Text | Text | fix broken links to buffer.from(string) | 8895c314ac0270196072fa1217006b95379e265b | <ide><path>doc/api/buffer.md
<ide> console.log(buf);
<ide> [`Buffer.from(array)`]: #buffer_class_method_buffer_from_array
<ide> [`Buffer.from(arrayBuffer)`]: #buffer_class_method_buffer_from_arraybuffer_byteoffset_length
<ide> [`Buffer.from(buffer)`]: #buffer_class_method_buffer_from_buffer
<del>[`Buffer.from(string)`]: #buffer_class_method_buffer_from_str_encoding
<add>[`Buffer.from(string)`]: #buffer_class_method_buffer_from_string_encoding
<ide> [`Buffer.poolSize`]: #buffer_class_property_buffer_poolsize
<ide> [`RangeError`]: errors.html#errors_class_rangeerror
<ide> [`util.inspect()`]: util.html#util_util_inspect_object_options | 1 |
Javascript | Javascript | add webgl2 option to webglrenderer | 325d8e9c371332f5695e56318f0098655f38e619 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide> _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
<ide> _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
<ide> _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
<add> _webgl2 = parameters.webgl2 !== undefined ? parameters.webgl2 : false,
<ide> _autoWebgl2 = parameters.autoWebgl2 !== undefined ? parameters.autoWebgl2 : false;
<ide>
<ide> var currentRenderList = null;
<ide> function WebGLRenderer( parameters ) {
<ide> _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
<ide> _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
<ide>
<del> var webglVersion = _autoWebgl2 && typeof WebGL2RenderingContext !== 'undefined' ? 'webgl2' : 'webgl';
<add> var webglVersion = _webgl2 || ( _autoWebgl2 && typeof WebGL2RenderingContext !== 'undefined' ) ? 'webgl2' : 'webgl';
<ide>
<ide> _gl = _context || _canvas.getContext( webglVersion, contextAttributes );
<ide> | 1 |
Text | Text | add dashboard link | 79dc95cca6f79551d9d95617d2325aa43df3d6f2 | <ide><path>README.md
<ide> it makes development fun!
<ide> * API Docs: http://docs.angularjs.org/api
<ide> * Developer Guide: http://docs.angularjs.org/guide
<ide> * Contribution guidelines: http://docs.angularjs.org/misc/contribute
<add>* Dashboard: http://dashboard.angularjs.org
<ide>
<ide> Building AngularJS
<ide> --------- | 1 |
Text | Text | fix typo in entity_linker docs | 6f565cf39dc5ca494344883643f98373ebe2654c | <ide><path>website/docs/api/entitylinker.md
<ide> applied to the `Doc` in order. Both [`__call__`](/api/entitylinker#call) and
<ide> | `batch_size` | The number of documents to buffer. Defaults to `128`. ~~int~~ |
<ide> | **YIELDS** | The processed documents in order. ~~Doc~~ |
<ide>
<del>## EntityLinker.set_kb {#initialize tag="method" new="3"}
<add>## EntityLinker.set_kb {#set_kb tag="method" new="3"}
<ide>
<ide> The `kb_loader` should be a function that takes a `Vocab` instance and creates
<ide> the `KnowledgeBase`, ensuring that the strings of the knowledge base are synced | 1 |
PHP | PHP | apply fixes from styleci | 0ccd8687e010c7d335cc34e48a618a7c7722ad38 | <ide><path>tests/Integration/Queue/CallQueuedHandlerTest.php
<ide> public function middleware()
<ide> public function handle($command, $next)
<ide> {
<ide> CallQueuedHandlerTestJobWithMiddleware::$middlewareCommand = $command;
<add>
<ide> return $next($command);
<ide> }
<del> }
<add> },
<ide> ];
<ide> }
<ide> }
<ide> class TestJobMiddleware
<ide> public function handle($command, $next)
<ide> {
<ide> $_SERVER['__test.dispatchMiddleware'] = true;
<add>
<ide> return $next($command);
<ide> }
<ide> } | 1 |
Go | Go | provide a function unregisterdevice() | 442247927b8e6c102ce1f94de58c7f93aab3d271 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) lookupDevice(hash string) (*DevInfo, error) {
<ide> return info, nil
<ide> }
<ide>
<del>func (devices *DeviceSet) registerDevice(id int, hash string, size uint64) (*DevInfo, error) {
<add>func (devices *DeviceSet) unregisterDevice(id int, hash string) error {
<add> log.Debugf("unregisterDevice(%v, %v)", id, hash)
<add> info := &DevInfo{
<add> Hash: hash,
<add> DeviceId: id,
<add> }
<add>
<add> devices.devicesLock.Lock()
<add> delete(devices.Devices, hash)
<add> devices.devicesLock.Unlock()
<add>
<add> if err := devices.removeMetadata(info); err != nil {
<add> log.Debugf("Error removing meta data: %s", err)
<add> return err
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (devices *DeviceSet) registerDevice(id int, hash string, size uint64, transactionId uint64) (*DevInfo, error) {
<ide> log.Debugf("registerDevice(%v, %v)", id, hash)
<ide> info := &DevInfo{
<ide> Hash: hash,
<ide> DeviceId: id,
<ide> Size: size,
<del> TransactionId: devices.allocateTransactionId(),
<add> TransactionId: transactionId,
<ide> Initialized: false,
<ide> devices: devices,
<ide> }
<ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64) (*Dev
<ide> return nil, err
<ide> }
<ide>
<del> if err := devices.updatePoolTransactionId(); err != nil {
<del> // Remove unused device
<del> devices.devicesLock.Lock()
<del> delete(devices.Devices, hash)
<del> devices.devicesLock.Unlock()
<del> devices.removeMetadata(info)
<del> return nil, err
<del> }
<del>
<ide> return info, nil
<ide> }
<ide>
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> return err
<ide> }
<ide>
<add> transactionId := devices.allocateTransactionId()
<ide> log.Debugf("Registering base device (id %v) with FS size %v", deviceId, devices.baseFsSize)
<del> info, err := devices.registerDevice(deviceId, "", devices.baseFsSize)
<add> info, err := devices.registerDevice(deviceId, "", devices.baseFsSize, transactionId)
<ide> if err != nil {
<ide> _ = devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId)
<ide> return err
<ide> }
<ide>
<add> if err := devices.updatePoolTransactionId(); err != nil {
<add> devices.unregisterDevice(deviceId, "")
<add> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId)
<add> return err
<add> }
<add>
<ide> log.Debugf("Creating filesystem on base device-mapper thin volume")
<ide>
<ide> if err = devices.activateDeviceIfNeeded(info); err != nil {
<ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error {
<ide> return err
<ide> }
<ide>
<del> if _, err := devices.registerDevice(deviceId, hash, baseInfo.Size); err != nil {
<add> transactionId := devices.allocateTransactionId()
<add> if _, err := devices.registerDevice(deviceId, hash, baseInfo.Size, transactionId); err != nil {
<ide> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId)
<ide> log.Debugf("Error registering device: %s", err)
<ide> return err
<ide> }
<add>
<add> if err := devices.updatePoolTransactionId(); err != nil {
<add> devices.unregisterDevice(deviceId, hash)
<add> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId)
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide> func (devices *DeviceSet) deleteDevice(info *DevInfo) error {
<ide> return err
<ide> }
<ide>
<del> devices.devicesLock.Lock()
<del> delete(devices.Devices, info.Hash)
<del> devices.devicesLock.Unlock()
<del>
<del> if err := devices.removeMetadata(info); err != nil {
<del> log.Debugf("Error removing meta data: %s", err)
<add> if err := devices.unregisterDevice(info.DeviceId, info.Hash); err != nil {
<ide> return err
<ide> }
<ide> | 1 |
PHP | PHP | apply suggestions from code review | d913422151f0347bd31fa8b27a1bb03500ec4866 | <ide><path>src/I18n/DateFormatTrait.php
<ide> public function nice($timezone = null, $locale = null)
<ide> * $time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'
<ide> * ```
<ide> *
<del> * You can control the default format used by setting through `Time::setToStringFormat()`.
<add> * You can control the default format used through `Time::setToStringFormat()`.
<ide> *
<ide> * You can read about the available IntlDateFormatter constants at
<ide> * https://secure.php.net/manual/en/class.intldateformatter.php
<ide> public function nice($timezone = null, $locale = null)
<ide> * $time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');
<ide> * ```
<ide> *
<del> * You can control the default locale used by setting through `Time::setDefaultLocale()`.
<add> * You can control the default locale used through `Time::setDefaultLocale()`.
<ide> * If empty, the default will be taken from the `intl.default_locale` ini config.
<ide> *
<ide> * @param string|int|null $format Format string. | 1 |
Go | Go | attach optional user data to a container | 11b65a00c66422a11d114260057384c59f5be4e2 | <ide><path>container.go
<ide> func loadContainer(containerPath string) (*Container, error) {
<ide> return container, nil
<ide> }
<ide>
<add>func (container *Container) loadUserData() (map[string]string, error) {
<add> jsonData, err := ioutil.ReadFile(path.Join(container.Root, "userdata.json"))
<add> if err != nil {
<add> if os.IsNotExist(err) {
<add> return make(map[string]string), nil
<add> }
<add> return nil, err
<add> }
<add> data := make(map[string]string)
<add> if err := json.Unmarshal(jsonData, &data); err != nil {
<add> return nil, err
<add> }
<add> return data, nil
<add>}
<add>
<add>func (container *Container) saveUserData(data map[string]string) error {
<add> jsonData, err := json.Marshal(data)
<add> if err != nil {
<add> return err
<add> }
<add> return ioutil.WriteFile(path.Join(container.Root, "userdata.json"), jsonData, 0700)
<add>}
<add>
<add>func (container *Container) SetUserData(key, value string) error {
<add> data, err := container.loadUserData()
<add> if err != nil {
<add> return err
<add> }
<add> data[key] = value
<add> return container.saveUserData(data)
<add>}
<add>
<add>func (container *Container) GetUserData(key string) (string) {
<add> data, err := container.loadUserData()
<add> if err != nil {
<add> return ""
<add> }
<add> if value, exists := data[key]; exists {
<add> return value
<add> }
<add> return ""
<add>}
<add>
<add>
<ide> func (container *Container) save() (err error) {
<ide> data, err := json.Marshal(container)
<ide> if err != nil { | 1 |
Text | Text | add developer instructions in readme.md | 4b58b66381b2a4b6861b29e7fc7cb8dbc9acfacb | <ide><path>readme.md
<ide> Develop [
<ide>
<ide> Master [](https://travis-ci.org/moment/moment)
<ide>
<add>For developers
<add>==============
<add>
<add>You need [node](http://nodejs.org/), use [nvm](https://github.com/creationix/nvm) or [nenv](https://github.com/ryuone/nenv) to install it.
<add>
<add>Then, in your shell
<add>
<add>```bash
<add>git clone https://github.com/moment/moment.git
<add>cd moment
<add>npm install -g grunt-cli
<add>npm install
<add>git checkout develop # all patches against develop branch, please!
<add>grunt # this runs tests and jshint
<add>```
<add>
<ide> Changelog
<ide> =========
<ide> | 1 |
Text | Text | correct version number in release notes | 7f16ed772720509b476e3cc4208c01b3972fa99b | <ide><path>docs/community/release-notes.md
<ide> You can determine your currently installed version using `pip show`:
<ide>
<ide> ## 3.9.x series
<ide>
<del>### 3.9.2
<add>### 3.9.3
<ide>
<ide> **Date**: [29th April 2019]
<ide> | 1 |
Mixed | Javascript | add extends for derived classes | c746ba4982d3ec17cd7ce38468e6cea662462a84 | <ide><path>doc/api/crypto.md
<ide> console.log(cert.verifySpkac(Buffer.from(spkac)));
<ide> added: v0.1.94
<ide> -->
<ide>
<add>* Extends: {stream.Transform}
<add>
<ide> Instances of the `Cipher` class are used to encrypt data. The class can be
<ide> used in one of two ways:
<ide>
<ide> The `cipher.update()` method can be called multiple times with new data until
<ide> added: v0.1.94
<ide> -->
<ide>
<add>* Extends: {stream.Transform}
<add>
<ide> Instances of the `Decipher` class are used to decrypt data. The class can be
<ide> used in one of two ways:
<ide>
<ide> console.log(aliceSecret === bobSecret);
<ide> added: v0.1.92
<ide> -->
<ide>
<add>* Extends: {stream.Transform}
<add>
<ide> The `Hash` class is a utility for creating hash digests of data. It can be
<ide> used in one of two ways:
<ide>
<ide> This can be called many times with new data as it is streamed.
<ide> added: v0.1.94
<ide> -->
<ide>
<add>* Extends: {stream.Transform}
<add>
<ide> The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
<ide> be used in one of two ways:
<ide>
<ide> or `'private'` for private (asymmetric) keys.
<ide> added: v0.1.92
<ide> -->
<ide>
<add>* Extends: {stream.Writable}
<add>
<ide> The `Sign` class is a utility for generating signatures. It can be used in one
<ide> of two ways:
<ide>
<ide> This can be called many times with new data as it is streamed.
<ide> added: v0.1.92
<ide> -->
<ide>
<add>* Extends: {stream.Writable}
<add>
<ide> The `Verify` class is a utility for verifying signatures. It can be used in one
<ide> of two ways:
<ide>
<ide><path>tools/doc/type-parser.js
<ide> const customTypesMap = {
<ide> 'Stream': 'stream.html#stream_stream',
<ide> 'stream.Duplex': 'stream.html#stream_class_stream_duplex',
<ide> 'stream.Readable': 'stream.html#stream_class_stream_readable',
<add> 'stream.Transform': 'stream.html#stream_class_stream_transform',
<ide> 'stream.Writable': 'stream.html#stream_class_stream_writable',
<ide>
<ide> 'Immediate': 'timers.html#timers_class_immediate', | 2 |
Javascript | Javascript | drop the root parameter of jquery.fn.init | d2436df36a4b2ef556907e734a90771f0dbdbcaf | <ide><path>src/core/init.js
<ide> var rootjQuery,
<ide> // Shortcut simple #id case for speed
<ide> rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
<ide>
<del> init = jQuery.fn.init = function( selector, context, root ) {
<add> init = jQuery.fn.init = function( selector, context ) {
<ide> var match, elem;
<ide>
<ide> // HANDLE: $(""), $(null), $(undefined), $(false)
<ide> if ( !selector ) {
<ide> return this;
<ide> }
<ide>
<del> // Method init() accepts an alternate rootjQuery
<del> // so migrate can support jQuery.sub (gh-2101)
<del> root = root || rootjQuery;
<del>
<ide> // HANDLE: $(DOMElement)
<ide> if ( selector.nodeType ) {
<ide> this[ 0 ] = selector;
<ide> var rootjQuery,
<ide> // HANDLE: $(function)
<ide> // Shortcut for document ready
<ide> } else if ( typeof selector === "function" ) {
<del> return root.ready !== undefined ?
<del> root.ready( selector ) :
<add> return rootjQuery.ready !== undefined ?
<add> rootjQuery.ready( selector ) :
<ide>
<ide> // Execute immediately if ready is not present
<ide> selector( jQuery );
<ide> var rootjQuery,
<ide>
<ide> // HANDLE: $(expr) & $(expr, $(...))
<ide> } else if ( !context || context.jquery ) {
<del> return ( context || root ).find( selector );
<add> return ( context || rootjQuery ).find( selector );
<ide>
<ide> // HANDLE: $(expr, context)
<ide> // (which is just equivalent to: $(context).find(expr) | 1 |
Javascript | Javascript | fix history sniffing in chrome packaged apps | 9f5526f861f2f60f0d0f9fddfc484a9cd9d9b594 | <ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide> var cachedState, lastHistoryState,
<ide> lastBrowserUrl = location.href,
<ide> baseElement = document.find('base'),
<del> pendingLocation = null;
<add> pendingLocation = null,
<add> getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
<add> try {
<add> return history.state;
<add> } catch (e) {
<add> // MSIE can reportedly throw when there is no state (UNCONFIRMED).
<add> }
<add> };
<ide>
<ide> cacheState();
<ide> lastHistoryState = cachedState;
<ide> function Browser(window, document, $log, $sniffer) {
<ide> fireUrlChange();
<ide> }
<ide>
<del> function getCurrentState() {
<del> try {
<del> return history.state;
<del> } catch (e) {
<del> // MSIE can reportedly throw when there is no state (UNCONFIRMED).
<del> }
<del> }
<del>
<ide> // This variable should be used *only* inside the cacheState function.
<ide> var lastCachedState = null;
<ide> function cacheState() {
<ide><path>src/ng/sniffer.js
<ide> function $SnifferProvider() {
<ide> this.$get = ['$window', '$document', function($window, $document) {
<ide> var eventSupport = {},
<add> // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
<add> // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
<add> isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
<add> hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
<ide> android =
<ide> toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
<ide> boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
<ide> function $SnifferProvider() {
<ide> // so let's not use the history API also
<ide> // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
<ide> // jshint -W018
<del> history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
<add> history: !!(hasHistoryPushState && !(android < 4) && !boxee),
<ide> // jshint +W018
<ide> hasEvent: function(event) {
<ide> // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
<ide><path>test/ng/browserSpecs.js
<ide> describe('browser', function() {
<ide> currentHref = fakeWindow.location.href;
<ide> });
<ide>
<add> it('should not access `history.state` when `$sniffer.history` is false', function() {
<add> // In the context of a Chrome Packaged App, although `history.state` is present, accessing it
<add> // is not allowed and logs an error in the console. We should not try to access
<add> // `history.state` in contexts where `$sniffer.history` is false.
<add>
<add> var historyStateAccessed = false;
<add> var mockSniffer = {histroy: false};
<add> var mockWindow = new MockWindow();
<add>
<add> var _state = mockWindow.history.state;
<add> Object.defineProperty(mockWindow.history, 'state', {
<add> get: function() {
<add> historyStateAccessed = true;
<add> return _state;
<add> }
<add> });
<add>
<add> var browser = new Browser(mockWindow, fakeDocument, fakeLog, mockSniffer);
<add>
<add> expect(historyStateAccessed).toBe(false);
<add> });
<add>
<ide> describe('in IE', runTests({msie: true}));
<ide> describe('not in IE', runTests({msie: false}));
<ide>
<add>
<ide> function runTests(options) {
<ide> return function() {
<ide> beforeEach(function() {
<ide><path>test/ng/snifferSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$sniffer', function() {
<del>
<ide> function sniffer($window, $document) {
<ide> /* global $SnifferProvider: false */
<del> $window.navigator = {};
<add> $window.navigator = $window.navigator || {};
<ide> $document = jqLite($document || {});
<ide> if (!$document[0].body) {
<ide> $document[0].body = window.document.body;
<ide> }
<ide> return new $SnifferProvider().$get[2]($window, $document);
<ide> }
<ide>
<add>
<ide> describe('history', function() {
<ide> it('should be true if history.pushState defined', function() {
<del> expect(sniffer({history: {pushState: noop, replaceState: noop}}).history).toBe(true);
<add> var mockWindow = {
<add> history: {
<add> pushState: noop,
<add> replaceState: noop
<add> }
<add> };
<add>
<add> expect(sniffer(mockWindow).history).toBe(true);
<ide> });
<ide>
<add>
<ide> it('should be false if history or pushState not defined', function() {
<del> expect(sniffer({history: {}}).history).toBe(false);
<ide> expect(sniffer({}).history).toBe(false);
<add> expect(sniffer({history: {}}).history).toBe(false);
<add> });
<add>
<add>
<add> it('should be false on Boxee box with an older version of Webkit', function() {
<add> var mockWindow = {
<add> history: {
<add> pushState: noop
<add> },
<add> navigator: {
<add> userAgent: 'boxee (alpha/Darwin 8.7.1 i386 - 0.9.11.5591)'
<add> }
<add> };
<add>
<add> expect(sniffer(mockWindow).history).toBe(false);
<add> });
<add>
<add>
<add> it('should be false on Chrome Packaged Apps', function() {
<add> // Chrome Packaged Apps are not allowed to access `window.history.pushState`.
<add> // In Chrome, `window.app` might be available in "normal" webpages, but `window.app.runtime`
<add> // only exists in the context of a packaged app.
<add>
<add> expect(sniffer(createMockWindow()).history).toBe(true);
<add> expect(sniffer(createMockWindow(true)).history).toBe(true);
<add> expect(sniffer(createMockWindow(true, true)).history).toBe(false);
<add>
<add> function createMockWindow(isChrome, isPackagedApp) {
<add> var mockWindow = {
<add> history: {
<add> pushState: noop
<add> }
<add> };
<add>
<add> if (isChrome) {
<add> var chromeAppObj = isPackagedApp ? {runtime: {}} : {};
<add> mockWindow.chrome = {app: chromeAppObj};
<add> }
<add>
<add> return mockWindow;
<add> }
<add> });
<add>
<add>
<add> it('should not try to access `history.pushState` in Chrome Packaged Apps', function() {
<add> var pushStateAccessCount = 0;
<add>
<add> var mockHistory = Object.create(Object.prototype, {
<add> pushState: {get: function() { pushStateAccessCount++; return noop; }}
<add> });
<add> var mockWindow = {
<add> chrome: {
<add> app: {
<add> runtime: {}
<add> }
<add> },
<add> history: mockHistory
<add> };
<add>
<add> sniffer(mockWindow);
<add>
<add> expect(pushStateAccessCount).toBe(0);
<ide> });
<ide> });
<ide>
<ide> describe('$sniffer', function() {
<ide> var mockDocument, mockDivElement, $sniffer;
<ide>
<ide> beforeEach(function() {
<del> mockDocument = {createElement: jasmine.createSpy('createElement')};
<del> mockDocument.createElement.and.callFake(function(elm) {
<del> if (elm === 'div') return mockDivElement;
<del> });
<add> var mockCreateElementFn = function(elm) { if (elm === 'div') return mockDivElement; };
<add> var createElementSpy = jasmine.createSpy('createElement').and.callFake(mockCreateElementFn);
<ide>
<add> mockDocument = {createElement: createElementSpy};
<ide> $sniffer = sniffer({}, mockDocument);
<ide> });
<ide>
<ide> describe('$sniffer', function() {
<ide>
<ide>
<ide> describe('vendorPrefix', function() {
<del>
<ide> it('should return the correct vendor prefix based on the browser', function() {
<ide> inject(function($sniffer, $window) {
<ide> var expectedPrefix;
<ide> describe('$sniffer', function() {
<ide> });
<ide> });
<ide>
<add>
<ide> it('should still work for an older version of Webkit', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> WebkitOpacity: '0'
<del> }
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> WebkitOpacity: '0'
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.vendorPrefix).toBe('webkit');
<del> });
<del> });
<add> }
<add> };
<ide>
<add> expect(sniffer({}, mockDocument).vendorPrefix).toBe('webkit');
<add> });
<ide> });
<ide>
<add>
<ide> describe('animations', function() {
<del> it('should be either true or false', function() {
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).not.toBeUndefined();
<del> });
<del> });
<add> it('should be either true or false', inject(function($sniffer) {
<add> expect($sniffer.animations).toBeDefined();
<add> }));
<add>
<ide>
<ide> it('should be false when there is no animation style', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {}
<del> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).toBe(false);
<del> });
<add> var mockDocument = {
<add> body: {
<add> style: {}
<add> }
<add> };
<add>
<add> expect(sniffer({}, mockDocument).animations).toBe(false);
<ide> });
<ide>
<add>
<ide> it('should be true with vendor-specific animations', function() {
<del> module(function($provide) {
<del> var animationStyle = 'some_animation 2s linear';
<del> var doc = {
<del> body: {
<del> style: {
<del> WebkitAnimation: animationStyle,
<del> MozAnimation: animationStyle
<del> }
<add> var animationStyle = 'some_animation 2s linear';
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> WebkitAnimation: animationStyle,
<add> MozAnimation: animationStyle
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).toBe(true);
<del> });
<add> }
<add> };
<add>
<add> expect(sniffer({}, mockDocument).animations).toBe(true);
<ide> });
<ide>
<add>
<ide> it('should be true with w3c-style animations', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> animation: 'some_animation 2s linear'
<del> }
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> animation: 'some_animation 2s linear'
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).toBe(true);
<del> });
<add> }
<add> };
<add>
<add> expect(sniffer({}, mockDocument).animations).toBe(true);
<ide> });
<ide>
<add>
<ide> it('should be true on android with older body style properties', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> webkitAnimation: ''
<del> }
<del> }
<del> };
<del> var win = {
<del> navigator: {
<del> userAgent: 'android 2'
<add> var mockWindow = {
<add> navigator: {
<add> userAgent: 'android 2'
<add> }
<add> };
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> webkitAnimation: ''
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> $provide.value('$window', win);
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).toBe(true);
<del> });
<add> }
<add> };
<add>
<add> expect(sniffer(mockWindow, mockDocument).animations).toBe(true);
<ide> });
<ide>
<add>
<ide> it('should be true when an older version of Webkit is used', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> WebkitOpacity: '0'
<del> }
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> WebkitOpacity: '0'
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.animations).toBe(false);
<del> });
<del> });
<add> }
<add> };
<ide>
<add> expect(sniffer({}, mockDocument).animations).toBe(false);
<add> });
<ide> });
<ide>
<add>
<ide> describe('transitions', function() {
<add> it('should be either true or false', inject(function($sniffer) {
<add> expect($sniffer.transitions).toBeOneOf(true, false);
<add> }));
<ide>
<del> it('should be either true or false', function() {
<del> inject(function($sniffer) {
<del> expect($sniffer.transitions).not.toBeUndefined();
<del> });
<del> });
<ide>
<ide> it('should be false when there is no transition style', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {}
<del> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.transitions).toBe(false);
<del> });
<add> var mockDocument = {
<add> body: {
<add> style: {}
<add> }
<add> };
<add>
<add> expect(sniffer({}, mockDocument).transitions).toBe(false);
<ide> });
<ide>
<add>
<ide> it('should be true with vendor-specific transitions', function() {
<del> module(function($provide) {
<del> var transitionStyle = '1s linear all';
<del> var doc = {
<del> body: {
<del> style: {
<del> WebkitTransition: transitionStyle,
<del> MozTransition: transitionStyle
<del> }
<add> var transitionStyle = '1s linear all';
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> WebkitTransition: transitionStyle,
<add> MozTransition: transitionStyle
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.transitions).toBe(true);
<del> });
<add> }
<add> };
<add>
<add> expect(sniffer({}, mockDocument).transitions).toBe(true);
<ide> });
<ide>
<add>
<ide> it('should be true with w3c-style transitions', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> transition: '1s linear all'
<del> }
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> transition: '1s linear all'
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.transitions).toBe(true);
<del> });
<del> });
<add> }
<add> };
<ide>
<del> it('should be true on android with older body style properties', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {
<del> webkitTransition: ''
<del> }
<del> }
<del> };
<del> var win = {
<del> navigator: {
<del> userAgent: 'android 2'
<del> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> $provide.value('$window', win);
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.transitions).toBe(true);
<del> });
<add> expect(sniffer({}, mockDocument).transitions).toBe(true);
<ide> });
<ide>
<del> });
<del>
<ide>
<del> describe('history', function() {
<del> it('should be true on Boxee box with an older version of Webkit', function() {
<del> module(function($provide) {
<del> var doc = {
<del> body: {
<del> style: {}
<del> }
<del> };
<del> var win = {
<del> history: {
<del> pushState: noop
<del> },
<del> navigator: {
<del> userAgent: 'boxee (alpha/Darwin 8.7.1 i386 - 0.9.11.5591)'
<add> it('should be true on android with older body style properties', function() {
<add> var mockWindow = {
<add> navigator: {
<add> userAgent: 'android 2'
<add> }
<add> };
<add> var mockDocument = {
<add> body: {
<add> style: {
<add> webkitTransition: ''
<ide> }
<del> };
<del> $provide.value('$document', jqLite(doc));
<del> $provide.value('$window', win);
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.history).toBe(false);
<del> });
<add> }
<add> };
<add>
<add> expect(sniffer(mockWindow, mockDocument).transitions).toBe(true);
<ide> });
<ide> });
<ide>
<del> it('should provide the android version', function() {
<del> module(function($provide) {
<del> var win = {
<add>
<add> describe('android', function() {
<add> it('should provide the android version', function() {
<add> var mockWindow = {
<ide> navigator: {
<ide> userAgent: 'android 2'
<ide> }
<ide> };
<del> $provide.value('$document', jqLite({}));
<del> $provide.value('$window', win);
<del> });
<del> inject(function($sniffer) {
<del> expect($sniffer.android).toBe(2);
<add>
<add> expect(sniffer(mockWindow).android).toBe(2);
<ide> });
<ide> });
<ide> }); | 4 |
PHP | PHP | allow guests in authorize middleware | 55afaaa248d2e7092f99963762150f397fbbaba3 | <ide><path>src/Illuminate/Auth/Middleware/Authorize.php
<ide> use Closure;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Contracts\Auth\Access\Gate;
<del>use Illuminate\Contracts\Auth\Factory as Auth;
<ide>
<ide> class Authorize
<ide> {
<del> /**
<del> * The authentication factory instance.
<del> *
<del> * @var \Illuminate\Contracts\Auth\Factory
<del> */
<del> protected $auth;
<del>
<ide> /**
<ide> * The gate instance.
<ide> *
<ide> class Authorize
<ide> /**
<ide> * Create a new middleware instance.
<ide> *
<del> * @param \Illuminate\Contracts\Auth\Factory $auth
<ide> * @param \Illuminate\Contracts\Auth\Access\Gate $gate
<ide> * @return void
<ide> */
<del> public function __construct(Auth $auth, Gate $gate)
<add> public function __construct(Gate $gate)
<ide> {
<del> $this->auth = $auth;
<ide> $this->gate = $gate;
<ide> }
<ide>
<ide> public function __construct(Auth $auth, Gate $gate)
<ide> */
<ide> public function handle($request, Closure $next, $ability, ...$models)
<ide> {
<del> $this->auth->authenticate();
<del>
<ide> $this->gate->authorize($ability, $this->getGateArguments($request, $models));
<ide>
<ide> return $next($request);
<ide><path>tests/Auth/AuthorizeMiddlewareTest.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Auth\Middleware\Authorize;
<ide> use Illuminate\Contracts\Routing\Registrar;
<del>use Illuminate\Contracts\Auth\Factory as Auth;
<ide> use Illuminate\Routing\Middleware\SubstituteBindings;
<ide> use Illuminate\Contracts\Auth\Access\Gate as GateContract;
<ide>
<ide> public function setUp()
<ide>
<ide> Container::setInstance($this->container = new Container);
<ide>
<del> $this->container->singleton(Auth::class, function () {
<del> $auth = m::mock(Auth::class);
<del> $auth->shouldReceive('authenticate')->once()->andReturn(null);
<del>
<del> return $auth;
<del> });
<del>
<ide> $this->container->singleton(GateContract::class, function () {
<ide> return new Gate($this->container, function () {
<ide> return $this->user;
<ide> public function testModelInstanceAsParameter()
<ide> $nextParam = $param;
<ide> };
<ide>
<del> (new Authorize($this->container->make(Auth::class), $this->gate()))
<add> (new Authorize($this->gate()))
<ide> ->handle($request, $next, 'success', $instance);
<ide> }
<ide> | 2 |
Ruby | Ruby | use more and cleanup new args apis | e3ac94fc5dee89a4037e2b857be2dbce67adeb57 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide> ENV.activate_extensions!
<ide> ENV.setup_build_environment
<ide>
<del> if Homebrew.args.named.blank?
<add> if args.no_named?
<ide> ff = Formula
<ide> files = Tap.map(&:formula_dir)
<ide> else
<del> ff = Homebrew.args.resolved_formulae
<del> files = Homebrew.args.resolved_formulae.map(&:path)
<add> ff = args.resolved_formulae
<add> files = args.resolved_formulae.map(&:path)
<ide> end
<ide>
<ide> only_cops = args.only_cops
<ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_args
<ide> switch :verbose
<ide> switch :debug
<ide> conflicts "--no-rebuild", "--keep-old"
<add> min_named 1
<ide> end
<ide> end
<ide>
<ide> def bottle
<ide> bottle_args.parse
<ide>
<ide> return merge if args.merge?
<del> raise KegUnspecifiedError if args.remaining.empty?
<ide>
<ide> ensure_relocation_formulae_installed! unless args.skip_relocation?
<del> Homebrew.args.resolved_formulae.each do |f|
<add> args.resolved_formulae.each do |f|
<ide> bottle_formula f
<ide> end
<ide> end
<ide> def bottle_formula(f)
<ide> end
<ide>
<ide> def merge
<del> write = args.write?
<del> raise UsageError, "--merge requires a JSON file path argument" if Homebrew.args.named.blank?
<del>
<del> bottles_hash = Homebrew.args.named.reduce({}) do |hash, json_file|
<add> bottles_hash = args.named.reduce({}) do |hash, json_file|
<ide> hash.deep_merge(JSON.parse(IO.read(json_file))) do |key, first, second|
<ide> if key == "cellar"
<ide> # Prioritize HOMEBREW_CELLAR over :any over :any_skip_relocation
<ide> def merge
<ide>
<ide> output = bottle_output bottle
<ide>
<del> if write
<add> if args.write?
<ide> path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s)
<ide> update_or_add = nil
<ide>
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide> # Use the user's browser, too.
<ide> ENV["BROWSER"] = ENV["HOMEBREW_BROWSER"]
<ide>
<del> formula = Homebrew.args.formulae.first
<add> formula = args.formulae.first
<ide>
<ide> if formula
<ide> tap_full_name, origin_branch, previous_branch = use_correct_linux_tap(formula)
<ide> def bump_formula_pr
<ide> new_formula_version = formula_version(formula, requested_spec, new_contents)
<ide>
<ide> if !new_mirrors && !formula_spec.mirrors.empty?
<del> if Homebrew.args.force?
<add> if args.force?
<ide> opoo "#{formula}: Removing all mirrors because a --mirror= argument was not specified."
<ide> else
<ide> odie <<~EOS
<ide> def inreplace_pairs(path, replacement_pairs)
<ide> contents = path.open("r") { |f| Formulary.ensure_utf8_encoding(f).read }
<ide> contents.extend(StringInreplaceExtension)
<ide> replacement_pairs.each do |old, new|
<del> ohai "replace #{old.inspect} with #{new.inspect}" unless Homebrew.args.quiet?
<add> ohai "replace #{old.inspect} with #{new.inspect}" unless args.quiet?
<ide> raise "No old value for new value #{new}! Did you pass the wrong arguments?" unless old
<ide>
<ide> contents.gsub!(old, new)
<ide> def inreplace_pairs(path, replacement_pairs)
<ide> else
<ide> Utils::Inreplace.inreplace(path) do |s|
<ide> replacement_pairs.each do |old, new|
<del> ohai "replace #{old.inspect} with #{new.inspect}" unless Homebrew.args.quiet?
<add> ohai "replace #{old.inspect} with #{new.inspect}" unless args.quiet?
<ide> raise "No old value for new value #{new}! Did you pass the wrong arguments?" unless old
<ide>
<ide> s.gsub!(old, new)
<ide> def check_for_duplicate_pull_requests(formula, tap_full_name)
<ide> #{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")}
<ide> EOS
<ide> error_message = "Duplicate PRs should not be opened. Use --force to override this error."
<del> if Homebrew.args.force? && !Homebrew.args.quiet?
<add> if args.force? && !args.quiet?
<ide> opoo duplicates_message
<del> elsif !Homebrew.args.force? && Homebrew.args.quiet?
<add> elsif !args.force? && args.quiet?
<ide> odie error_message
<del> elsif !Homebrew.args.force?
<add> elsif !args.force?
<ide> odie <<~EOS
<ide> #{duplicates_message.chomp}
<ide> #{error_message}
<ide><path>Library/Homebrew/dev-cmd/bump-revision.rb
<ide> def bump_revision
<ide> # user path, too.
<ide> ENV["PATH"] = ENV["HOMEBREW_PATH"]
<ide>
<del> formulae = Homebrew.args.formulae
<add> formulae = args.formulae
<ide> raise FormulaUnspecifiedError if formulae.empty?
<ide>
<ide> formula = formulae.first
<ide> def bump_revision
<ide> end
<ide>
<ide> if args.dry_run?
<del> ohai "replace #{old.inspect} with #{replacement.inspect}" unless Homebrew.args.quiet?
<add> ohai "replace #{old.inspect} with #{replacement.inspect}" unless args.quiet?
<ide> else
<ide> Utils::Inreplace.inreplace(formula.path) do |s|
<ide> s.gsub!(old, replacement)
<ide><path>Library/Homebrew/dev-cmd/create.rb
<ide> def create_args
<ide> switch :verbose
<ide> switch :debug
<ide> conflicts "--autotools", "--cmake", "--go", "--meson", "--perl", "--python", "--rust"
<del> max_named 1
<add> named 1
<ide> end
<ide> end
<ide>
<ide> # Create a formula from a tarball URL
<ide> def create
<ide> create_args.parse
<ide>
<del> raise UsageError if ARGV.named.empty?
<del>
<ide> # Ensure that the cache exists so we can fetch the tarball
<ide> HOMEBREW_CACHE.mkpath
<ide>
<del> url = ARGV.named.first # Pull the first (and only) url from ARGV
<add> url = args.named.first # Pull the first (and only) url from ARGV
<ide>
<ide> version = args.set_version
<ide> name = args.set_name
<ide><path>Library/Homebrew/dev-cmd/edit.rb
<ide> def edit
<ide> end
<ide>
<ide> # If no brews are listed, open the project root in an editor.
<del> paths = [HOMEBREW_REPOSITORY] if ARGV.named.empty?
<add> paths = [HOMEBREW_REPOSITORY] if args.no_named?
<ide>
<del> # Don't use ARGV.formulae as that will throw if the file doesn't parse
<del> paths ||= ARGV.named.map do |name|
<add> # Don't use args.formulae as that will throw if the file doesn't parse
<add> paths ||= args.named.map do |name|
<ide> path = Formulary.path(name)
<ide> raise FormulaUnavailableError, name if !path.file? && !args.force?
<ide>
<ide><path>Library/Homebrew/dev-cmd/extract.rb
<ide> def extract_args
<ide> description: "Extract the specified <version> of <formula> instead of the most recent."
<ide> switch :force
<ide> switch :debug
<del> max_named 2
<add> named 2
<ide> end
<ide> end
<ide>
<ide> def extract
<ide> extract_args.parse
<ide>
<del> # Expect exactly two named arguments: formula and tap
<del> raise UsageError, "This command requires formula and tap arguments" if args.remaining.length != 2
<del>
<del> if args.remaining.first !~ HOMEBREW_TAP_FORMULA_REGEX
<del> name = args.remaining.first.downcase
<add> if args.named.first !~ HOMEBREW_TAP_FORMULA_REGEX
<add> name = args.named.first.downcase
<ide> source_tap = CoreTap.instance
<ide> else
<ide> name = Regexp.last_match(3).downcase
<ide> source_tap = Tap.fetch(Regexp.last_match(1), Regexp.last_match(2))
<ide> raise TapFormulaUnavailableError.new(source_tap, name) unless source_tap.installed?
<ide> end
<ide>
<del> destination_tap = Tap.fetch(args.remaining.second)
<add> destination_tap = Tap.fetch(args.named.second)
<ide> unless ARGV.homebrew_developer?
<ide> odie "Cannot extract formula to homebrew/core!" if destination_tap.core_tap?
<ide> odie "Cannot extract formula to the same tap!" if destination_tap == source_tap
<ide> def extract
<ide>
<ide> path = destination_tap.path/"Formula/#{name}@#{version}.rb"
<ide> if path.exist?
<del> unless Homebrew.args.force?
<add> unless args.force?
<ide> odie <<~EOS
<ide> Destination formula already exists: #{path}
<ide> To overwrite it and continue anyways, run:
<ide><path>Library/Homebrew/dev-cmd/formula.rb
<ide> def formula_args
<ide> EOS
<ide> switch :verbose
<ide> switch :debug
<add> min_named :formula
<ide> end
<ide> end
<ide>
<ide> def formula
<ide> formula_args.parse
<ide>
<del> raise FormulaUnspecifiedError if Homebrew.args.named.blank?
<del>
<del> Homebrew.args.resolved_formulae.each { |f| puts f.path }
<add> args.resolved_formulae.each { |f| puts f.path }
<ide> end
<ide> end
<ide><path>Library/Homebrew/dev-cmd/linkage.rb
<ide> def linkage
<ide> linkage_args.parse
<ide>
<ide> CacheStoreDatabase.use(:linkage) do |db|
<del> kegs = if Homebrew.args.kegs.empty?
<add> kegs = if args.kegs.empty?
<ide> Formula.installed.map(&:opt_or_installed_prefix_keg).reject(&:nil?)
<ide> else
<del> Homebrew.args.kegs
<add> args.kegs
<ide> end
<ide> kegs.each do |keg|
<ide> ohai "Checking #{keg.name} linkage" if kegs.size > 1
<ide><path>Library/Homebrew/dev-cmd/mirror.rb
<ide> def mirror_args
<ide> switch :verbose
<ide> switch :debug
<ide> hide_from_man_page!
<add> min_named :formula
<ide> end
<ide> end
<ide>
<ide> def mirror
<ide> mirror_args.parse
<ide>
<del> raise FormulaUnspecifiedError if args.remaining.empty?
<del>
<ide> bintray_user = ENV["HOMEBREW_BINTRAY_USER"]
<ide> bintray_key = ENV["HOMEBREW_BINTRAY_KEY"]
<ide> raise "Missing HOMEBREW_BINTRAY_USER or HOMEBREW_BINTRAY_KEY variables!" if !bintray_user || !bintray_key
<ide>
<del> Homebrew.args.formulae.each do |f|
<add> args.formulae.each do |f|
<ide> bintray_package = Utils::Bottles::Bintray.package f.name
<ide> bintray_repo_url = "https://api.bintray.com/packages/homebrew/mirror"
<ide> package_url = "#{bintray_repo_url}/#{bintray_package}"
<ide><path>Library/Homebrew/dev-cmd/pull.rb
<ide> def pull_args
<ide> description: "Pull the bottle block commit from the specified <user> on GitHub."
<ide> switch :verbose
<ide> switch :debug
<add> min_named 1
<ide> end
<ide> end
<ide>
<ide> def pull
<ide>
<ide> pull_args.parse
<ide>
<del> if ARGV.named.empty?
<del> raise UsageError, "This command requires at least one argument containing a URL or pull request number"
<del> end
<del>
<ide> # Passthrough Git environment variables for e.g. git am
<ide> ENV["GIT_COMMITTER_NAME"] = ENV["HOMEBREW_GIT_NAME"] if ENV["HOMEBREW_GIT_NAME"]
<ide> ENV["GIT_COMMITTER_EMAIL"] = ENV["HOMEBREW_GIT_EMAIL"] if ENV["HOMEBREW_GIT_EMAIL"]
<ide> def pull
<ide>
<ide> tap = nil
<ide>
<del> ARGV.named.each do |arg|
<add> args.named.each do |arg|
<ide> arg = "#{CoreTap.instance.default_remote}/pull/#{arg}" if arg.to_i.positive?
<ide> if (testing_match = arg.match %r{/job/Homebrew.*Testing/(\d+)})
<ide> tap = ARGV.value("tap")
<ide><path>Library/Homebrew/dev-cmd/release-notes.rb
<ide> def release_notes_args
<ide> def release_notes
<ide> release_notes_args.parse
<ide>
<del> previous_tag = ARGV.named.first
<add> previous_tag = args.named.first
<ide> previous_tag ||= Utils.popen_read(
<ide> "git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname"
<ide> ).lines.first.chomp
<ide> odie "Could not find any previous tags!" unless previous_tag
<ide>
<del> end_ref = ARGV.named.second || "origin/master"
<add> end_ref = args.named.second || "origin/master"
<ide>
<ide> [previous_tag, end_ref].each do |ref|
<ide> next if quiet_system "git", "-C", HOMEBREW_REPOSITORY, "rev-parse", "--verify", "--quiet", ref
<ide><path>Library/Homebrew/dev-cmd/tap-new.rb
<ide> def tap_new_args
<ide> EOS
<ide> switch :verbose
<ide> switch :debug
<del> max_named 1
<add> named 1
<ide> end
<ide> end
<ide>
<ide> def tap_new
<ide> tap_new_args.parse
<ide>
<del> raise UsageError, "This command requires a tap argument" if ARGV.named.empty?
<del>
<del> tap = Tap.fetch(ARGV.named.first)
<add> tap = Tap.fetch(args.named.first)
<ide> titleized_user = tap.user.dup
<ide> titleized_repo = tap.repo.dup
<ide> titleized_user[0] = titleized_user[0].upcase
<ide><path>Library/Homebrew/dev-cmd/test.rb
<ide> def test_args
<ide> switch :verbose
<ide> switch :debug
<ide> conflicts "--devel", "--HEAD"
<add> min_named :formula
<ide> end
<ide> end
<ide>
<ide> def test
<ide> test_args.parse
<ide>
<del> raise FormulaUnspecifiedError if ARGV.named.empty?
<del>
<ide> require "formula_assertions"
<ide>
<del> Homebrew.args.resolved_formulae.each do |f|
<add> args.resolved_formulae.each do |f|
<ide> # Cannot test uninstalled formulae
<ide> unless f.latest_version_installed?
<ide> ofail "Testing requires the latest version of #{f.full_name}"
<ide> def test
<ide> end
<ide>
<ide> # Don't test unlinked formulae
<del> if !Homebrew.args.force? && !f.keg_only? && !f.linked?
<add> if !args.force? && !f.keg_only? && !f.linked?
<ide> ofail "#{f.full_name} is not linked"
<ide> next
<ide> end
<ide> def test
<ide> env = ENV.to_hash
<ide>
<ide> begin
<del> args = %W[
<add> exec_args = %W[
<ide> #{RUBY_PATH}
<ide> -W0
<ide> -I #{$LOAD_PATH.join(File::PATH_SEPARATOR)}
<ide> --
<ide> #{HOMEBREW_LIBRARY_PATH}/test.rb
<ide> #{f.path}
<del> ].concat(Homebrew.args.options_only)
<add> ].concat(args.options_only)
<ide>
<ide> if f.head?
<del> args << "--HEAD"
<add> exec_args << "--HEAD"
<ide> elsif f.devel?
<del> args << "--devel"
<add> exec_args << "--devel"
<ide> end
<ide>
<ide> Utils.safe_fork do
<ide> def test
<ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/homebrew/locks")
<ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/log")
<ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/run")
<del> sandbox.exec(*args)
<add> sandbox.exec(*exec_args)
<ide> else
<del> exec(*args)
<add> exec(*exec_args)
<ide> end
<ide> end
<ide> rescue Exception => e # rubocop:disable Lint/RescueException | 14 |
Javascript | Javascript | update legend imports | 771fe520957199b32a26205c14f4816002842bcb | <ide><path>src/plugins/plugin.legend.js
<ide>
<ide> import defaults from '../core/core.defaults';
<ide> import Element from '../core/core.element';
<del>import helpers from '../helpers';
<ide> import layouts from '../core/core.layouts';
<del>
<del>const getRtlHelper = helpers.rtl.getRtlAdapter;
<del>const valueOrDefault = helpers.valueOrDefault;
<add>import {drawPoint} from '../helpers/helpers.canvas';
<add>import {callback as call, extend, mergeIf, valueOrDefault} from '../helpers/helpers.core';
<add>import {_parseFont, toPadding} from '../helpers/helpers.options';
<add>import {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl';
<ide>
<ide> defaults._set('legend', {
<ide> display: true,
<ide> class Legend extends Element {
<ide> super();
<ide>
<ide> const me = this;
<del> helpers.extend(me, config);
<add> extend(me, config);
<ide>
<ide> // Contains hit boxes for each dataset (in dataset order)
<ide> me.legendHitBoxes = [];
<ide> class Legend extends Element {
<ide> buildLabels() {
<ide> var me = this;
<ide> var labelOpts = me.options.labels || {};
<del> var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
<add> var legendItems = call(labelOpts.generateLabels, [me.chart], me) || [];
<ide>
<ide> if (labelOpts.filter) {
<ide> legendItems = legendItems.filter(function(item) {
<ide> class Legend extends Element {
<ide> const display = opts.display;
<ide>
<ide> const ctx = me.ctx;
<del> const labelFont = helpers.options._parseFont(labelOpts);
<add> const labelFont = _parseFont(labelOpts);
<ide> const fontSize = labelFont.size;
<ide>
<ide> // Reset hit boxes
<ide> class Legend extends Element {
<ide> }
<ide>
<ide> me._drawTitle();
<del> const rtlHelper = getRtlHelper(opts.rtl, me.left, me._minSize.width);
<add> const rtlHelper = getRtlAdapter(opts.rtl, me.left, me._minSize.width);
<ide> const ctx = me.ctx;
<ide> const fontColor = valueOrDefault(labelOpts.fontColor, defaults.fontColor);
<del> const labelFont = helpers.options._parseFont(labelOpts);
<add> const labelFont = _parseFont(labelOpts);
<ide> const fontSize = labelFont.size;
<ide> let cursor;
<ide>
<ide> class Legend extends Element {
<ide> var centerY = y + fontSize / 2;
<ide>
<ide> // Draw pointStyle as legend symbol
<del> helpers.canvas.drawPoint(ctx, drawOptions, centerX, centerY);
<add> drawPoint(ctx, drawOptions, centerX, centerY);
<ide> } else {
<ide> // Draw box as legend symbol
<ide> ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
<ide> class Legend extends Element {
<ide> };
<ide> }
<ide>
<del> helpers.rtl.overrideTextDirection(me.ctx, opts.textDirection);
<add> overrideTextDirection(me.ctx, opts.textDirection);
<ide>
<ide> var itemHeight = fontSize + labelOpts.padding;
<ide> me.legendItems.forEach(function(legendItem, i) {
<ide> class Legend extends Element {
<ide> }
<ide> });
<ide>
<del> helpers.rtl.restoreTextDirection(me.ctx, opts.textDirection);
<add> restoreTextDirection(me.ctx, opts.textDirection);
<ide> }
<ide>
<ide> _drawTitle() {
<ide> const me = this;
<ide> const opts = me.options;
<ide> const titleOpts = opts.title;
<del> const titleFont = helpers.options._parseFont(titleOpts);
<del> const titlePadding = helpers.options.toPadding(titleOpts.padding);
<add> const titleFont = _parseFont(titleOpts);
<add> const titlePadding = toPadding(titleOpts.padding);
<ide>
<ide> if (!titleOpts.display) {
<ide> return;
<ide> }
<ide>
<del> const rtlHelper = getRtlHelper(opts.rtl, me.left, me.minSize.width);
<add> const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.minSize.width);
<ide> const ctx = me.ctx;
<ide> const fontColor = valueOrDefault(titleOpts.fontColor, defaults.fontColor);
<ide> const position = titleOpts.position;
<ide> class Legend extends Element {
<ide>
<ide> _computeTitleHeight() {
<ide> const titleOpts = this.options.title;
<del> const titleFont = helpers.options._parseFont(titleOpts);
<del> const titlePadding = helpers.options.toPadding(titleOpts.padding);
<add> const titleFont = _parseFont(titleOpts);
<add> const titlePadding = toPadding(titleOpts.padding);
<ide> return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
<ide> }
<ide>
<ide> export default {
<ide> var legend = chart.legend;
<ide>
<ide> if (legendOpts) {
<del> helpers.mergeIf(legendOpts, defaults.legend);
<add> mergeIf(legendOpts, defaults.legend);
<ide>
<ide> if (legend) {
<ide> layouts.configure(chart, legend, legendOpts); | 1 |
Javascript | Javascript | set an abbreviation for ordinal numbers >1 | 47da67e51f5777d7b4ae867badca5186aab0f6d7 | <ide><path>src/locale/fr-ca.js
<ide> export default moment.defineLocale('fr-ca', {
<ide> y : 'un an',
<ide> yy : '%d ans'
<ide> },
<del> ordinalParse: /\d{1,2}(er|)/,
<add> ordinalParse: /\d{1,2}(er|e)/,
<ide> ordinal : function (number) {
<del> return number + (number === 1 ? 'er' : '');
<add> return number + (number === 1 ? 'er' : 'e');
<ide> }
<ide> });
<ide>
<ide><path>src/locale/fr.js
<ide> export default moment.defineLocale('fr', {
<ide> y : 'un an',
<ide> yy : '%d ans'
<ide> },
<del> ordinalParse: /\d{1,2}(er|)/,
<add> ordinalParse: /\d{1,2}(er|e)/,
<ide> ordinal : function (number) {
<del> return number + (number === 1 ? 'er' : '');
<add> return number + (number === 1 ? 'er' : 'e');
<ide> },
<ide> week : {
<ide> dow : 1, // Monday is the first day of the week.
<ide><path>src/test/locale/fr-ca.js
<ide> test('parse', function (assert) {
<ide>
<ide> test('format', function (assert) {
<ide> var a = [
<del> ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, février 14 2010, 3:25:50 pm'],
<add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, février 14e 2010, 3:25:50 pm'],
<ide> ['ddd, hA', 'dim., 3PM'],
<del> ['M Mo MM MMMM MMM', '2 2 02 février févr.'],
<add> ['M Mo MM MMMM MMM', '2 2e 02 février févr.'],
<ide> ['YYYY YY', '2010 10'],
<del> ['D Do DD', '14 14 14'],
<del> ['d do dddd ddd dd', '0 0 dimanche dim. Di'],
<del> ['DDD DDDo DDDD', '45 45 045'],
<del> ['w wo ww', '8 8 08'],
<add> ['D Do DD', '14 14e 14'],
<add> ['d do dddd ddd dd', '0 0e dimanche dim. Di'],
<add> ['DDD DDDo DDDD', '45 45e 045'],
<add> ['w wo ww', '8 8e 08'],
<ide> ['h hh', '3 03'],
<ide> ['H HH', '15 15'],
<ide> ['m mm', '25 25'],
<ide> ['s ss', '50 50'],
<ide> ['a A', 'pm PM'],
<del> ['[the] DDDo [day of the year]', 'the 45 day of the year'],
<add> ['[the] DDDo [day of the year]', 'the 45e day of the year'],
<ide> ['LTS', '15:25:50'],
<ide> ['L', '2010-02-14'],
<ide> ['LL', '14 février 2010'],
<ide> test('format', function (assert) {
<ide>
<ide> test('format ordinal', function (assert) {
<ide> assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er');
<del> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2');
<del> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3');
<del> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4');
<del> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5');
<del> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6');
<del> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7');
<del> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8');
<del> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9');
<del> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10');
<del>
<del> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11');
<del> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12');
<del> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13');
<del> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14');
<del> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15');
<del> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16');
<del> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17');
<del> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18');
<del> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19');
<del> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20');
<del>
<del> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21');
<del> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22');
<del> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23');
<del> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24');
<del> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25');
<del> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26');
<del> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27');
<del> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28');
<del> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29');
<del> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30');
<del>
<del> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2e', '2e');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21e', '21e');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22e', '22e');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31e', '31e');
<ide> });
<ide>
<ide> test('format month', function (assert) {
<ide> test('weeks year starting saturday', function (assert) {
<ide> test('weeks year starting sunday format', function (assert) {
<ide> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1er', 'Jan 1 2012 should be week 1');
<ide> assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1er', 'Jan 7 2012 should be week 1');
<del> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2');
<del> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2');
<del> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3');
<add> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2e', 'Jan 8 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2e', 'Jan 14 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3e', 'Jan 15 2012 should be week 3');
<ide> });
<ide>
<ide> test('lenient ordinal parsing', function (assert) {
<ide><path>src/test/locale/fr.js
<ide> test('parse', function (assert) {
<ide>
<ide> test('format', function (assert) {
<ide> var a = [
<del> ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, février 14 2010, 3:25:50 pm'],
<add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, février 14e 2010, 3:25:50 pm'],
<ide> ['ddd, hA', 'dim., 3PM'],
<del> ['M Mo MM MMMM MMM', '2 2 02 février févr.'],
<add> ['M Mo MM MMMM MMM', '2 2e 02 février févr.'],
<ide> ['YYYY YY', '2010 10'],
<del> ['D Do DD', '14 14 14'],
<del> ['d do dddd ddd dd', '0 0 dimanche dim. Di'],
<del> ['DDD DDDo DDDD', '45 45 045'],
<del> ['w wo ww', '6 6 06'],
<add> ['D Do DD', '14 14e 14'],
<add> ['d do dddd ddd dd', '0 0e dimanche dim. Di'],
<add> ['DDD DDDo DDDD', '45 45e 045'],
<add> ['w wo ww', '6 6e 06'],
<ide> ['h hh', '3 03'],
<ide> ['H HH', '15 15'],
<ide> ['m mm', '25 25'],
<ide> ['s ss', '50 50'],
<ide> ['a A', 'pm PM'],
<del> ['[the] DDDo [day of the year]', 'the 45 day of the year'],
<add> ['[the] DDDo [day of the year]', 'the 45e day of the year'],
<ide> ['LTS', '15:25:50'],
<ide> ['L', '14/02/2010'],
<ide> ['LL', '14 février 2010'],
<ide> test('format', function (assert) {
<ide>
<ide> test('format ordinal', function (assert) {
<ide> assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er');
<del> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2');
<del> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3');
<del> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4');
<del> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5');
<del> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6');
<del> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7');
<del> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8');
<del> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9');
<del> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10');
<del>
<del> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11');
<del> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12');
<del> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13');
<del> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14');
<del> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15');
<del> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16');
<del> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17');
<del> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18');
<del> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19');
<del> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20');
<del>
<del> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21');
<del> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22');
<del> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23');
<del> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24');
<del> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25');
<del> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26');
<del> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27');
<del> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28');
<del> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29');
<del> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30');
<del>
<del> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2e', '2e');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21e', '21e');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22e', '22e');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31e', '31e');
<ide> });
<ide>
<ide> test('format month', function (assert) {
<ide> test('weeks year starting saturday', function (assert) {
<ide> });
<ide>
<ide> test('weeks year starting sunday formatted', function (assert) {
<del> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52');
<add> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52e', 'Jan 1 2012 should be week 52');
<ide> assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1er', 'Jan 2 2012 should be week 1');
<ide> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1er', 'Jan 8 2012 should be week 1');
<del> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2');
<del> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2e', 'Jan 9 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2e', 'Jan 15 2012 should be week 2');
<ide> });
<ide>
<ide> test('lenient ordinal parsing', function (assert) { | 4 |
Ruby | Ruby | use strftime to convert datetime to numeric | 210cd756a628cc19c0d6e44bee8c33dfb2d9d598 | <ide><path>activesupport/lib/active_support/core_ext/date_time/conversions.rb
<ide> def to_i
<ide> private
<ide>
<ide> def seconds_since_unix_epoch
<del> seconds_per_day = 86_400
<del> (self - ::DateTime.civil(1970)) * seconds_per_day
<add> strftime('%s')
<ide> end
<ide> end | 1 |
Python | Python | add sentrec shortcut to language | e1b493ae8521af36fd1f0dfeafe7d9eb0408fe75 | <ide><path>spacy/language.py
<ide> def entity(self):
<ide> def linker(self):
<ide> return self.get_pipe("entity_linker")
<ide>
<add> @property
<add> def sentrec(self):
<add> return self.get_pipe("sentrec")
<add>
<ide> @property
<ide> def matcher(self):
<ide> return self.get_pipe("matcher") | 1 |
Javascript | Javascript | use es6 default parameter wherever possible | 2be3c32b34f63af631aaa39bb3c41b5d16afd106 | <ide><path>packages/@ember/runloop/tests/later_test.js
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
<ide> import { assign } from '@ember/polyfills';
<del>import { isNone } from 'ember-metal';
<ide> import { run, later, backburner, hasScheduledTimers, getCurrentRunLoop } from '..';
<ide>
<ide> const originalSetTimeout = window.setTimeout;
<ide> const originalDateValueOf = Date.prototype.valueOf;
<ide> const originalPlatform = backburner._platform;
<ide>
<del>function wait(callback, maxWaitCount) {
<del> maxWaitCount = isNone(maxWaitCount) ? 100 : maxWaitCount;
<del>
<add>function wait(callback, maxWaitCount = 100) {
<ide> originalSetTimeout(() => {
<ide> if (maxWaitCount > 0 && (hasScheduledTimers() || getCurrentRunLoop())) {
<ide> wait(callback, maxWaitCount - 1);
<ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> import {
<ide> objectAt,
<ide> replaceInNativeArray,
<ide> computed,
<del> isNone,
<ide> aliasMethod,
<ide> Mixin,
<ide> hasListeners,
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> @return {Array} New array with specified slice
<ide> @public
<ide> */
<del> slice(beginIndex, endIndex) {
<add> slice(beginIndex = 0, endIndex) {
<ide> let ret = A();
<ide> let length = this.length;
<ide>
<del> if (isNone(beginIndex)) {
<del> beginIndex = 0;
<del> } else if (beginIndex < 0) {
<add> if (beginIndex < 0) {
<ide> beginIndex = length + beginIndex;
<ide> }
<ide>
<del> if (isNone(endIndex) || endIndex > length) {
<add> if (endIndex === undefined || endIndex > length) {
<ide> endIndex = length;
<ide> } else if (endIndex < 0) {
<ide> endIndex = length + endIndex;
<ide><path>packages/ember-runtime/lib/mixins/observable.js
<ide> import {
<ide> addObserver,
<ide> removeObserver,
<ide> getCachedValueFor,
<del> isNone,
<ide> } from 'ember-metal';
<ide> import { assert } from '@ember/debug';
<ide>
<ide> export default Mixin.create({
<ide> @return {Number} The new property value
<ide> @public
<ide> */
<del> incrementProperty(keyName, increment) {
<del> if (isNone(increment)) {
<del> increment = 1;
<del> }
<add> incrementProperty(keyName, increment = 1) {
<ide> assert(
<ide> 'Must pass a numeric value to incrementProperty',
<ide> !isNaN(parseFloat(increment)) && isFinite(increment)
<ide> export default Mixin.create({
<ide> @return {Number} The new property value
<ide> @public
<ide> */
<del> decrementProperty(keyName, decrement) {
<del> if (isNone(decrement)) {
<del> decrement = 1;
<del> }
<add> decrementProperty(keyName, decrement = 1) {
<ide> assert(
<ide> 'Must pass a numeric value to decrementProperty',
<ide> !isNaN(parseFloat(decrement)) && isFinite(decrement) | 3 |
Go | Go | improve the checksum process | c7a7983fcbe28d67648b32e37029ac84482cffcf | <ide><path>registry.go
<ide> func (graph *Graph) PushRepository(stdout io.Writer, remote string, localRepo Re
<ide> // Retrieve the checksum of an image
<ide> // Priority:
<ide> // - Check on the stored checksums
<del>// - Check if the archive is exists, if it does not, ask the registry
<add>// - Check if the archive exists, if it does not, ask the registry
<ide> // - If the archive does exists, process the checksum from it
<ide> // - If the archive does not exists and not found on registry, process checksum from layer
<ide> func (graph *Graph) getChecksum(imageId string) (string, error) {
<add> // FIXME: Use in-memory map instead of reading the file each time
<add> if sums, err := graph.getStoredChecksums(); err != nil {
<add> return "", err
<add> } else if checksum, exists := sums[imageId]; exists {
<add> return checksum, nil
<add> }
<add>
<ide> img, err := graph.Get(imageId)
<ide> if err != nil {
<ide> return "", err
<ide> }
<add>
<add> if _, err := os.Stat(layerArchivePath(graph.imageRoot(imageId))); err != nil {
<add> if os.IsNotExist(err) {
<add> // TODO: Ask the registry for the checksum
<add> // As the archive is not there, it is supposed to come from a pull.
<add> } else {
<add> return "", err
<add> }
<add> }
<add>
<ide> checksum, err := img.Checksum()
<ide> if err != nil {
<ide> return "", err | 1 |
Go | Go | add dockercmdwithstdoutstderr function | c6cde91b7d2cb3671dc55cafc5ab693f9cb17cc8 | <ide><path>integration-cli/docker_utils.go
<ide> func dockerCmdWithError(c *check.C, args ...string) (string, int, error) {
<ide> return runCommandWithOutput(exec.Command(dockerBinary, args...))
<ide> }
<ide>
<add>func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
<add> stdout, stderr, status, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, args...))
<add> c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), stderr, err))
<add> return stdout, stderr, status
<add>}
<add>
<ide> func dockerCmd(c *check.C, args ...string) (string, int) {
<ide> out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
<ide> c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)) | 1 |
Mixed | Javascript | add resourcetiming buffer limit | 798a6edddff79af461c80ceabba88559ca4c1ebc | <ide><path>doc/api/perf_hooks.md
<ide> added: v8.5.0
<ide> Returns the current high resolution millisecond timestamp, where 0 represents
<ide> the start of the current `node` process.
<ide>
<add>### `performance.setResourceTimingBufferSize(maxSize)`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>Sets the global performance resource timing buffer size to the specified number
<add>of "resource" type performance entry objects.
<add>
<add>By default the max buffer size is set to 250.
<add>
<ide> ### `performance.timeOrigin`
<ide>
<ide> <!-- YAML
<ide> added: v16.1.0
<ide> An object which is JSON representation of the `performance` object. It
<ide> is similar to [`window.performance.toJSON`][] in browsers.
<ide>
<add>#### Event: `'resourcetimingbufferfull'`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>The `'resourcetimingbufferfull'` event is fired when the global performance
<add>resource timing buffer is full. Adjust resource timing buffer size with
<add>`performance.setResourceTimingBufferSize()` or clear the buffer with
<add>`performance.clearResourceTimings()` in the event listener to allow
<add>more entries to be added to the performance timeline buffer.
<add>
<ide> ## Class: `PerformanceEntry`
<ide>
<ide> <!-- YAML
<ide><path>lib/internal/bootstrap/browser.js
<ide> defineOperation(globalThis, 'btoa', buffer.btoa);
<ide> exposeInterface(globalThis, 'Blob', buffer.Blob);
<ide>
<ide> // https://www.w3.org/TR/hr-time-2/#the-performance-attribute
<add>const perf_hooks = require('perf_hooks');
<add>exposeInterface(globalThis, 'Performance', perf_hooks.Performance);
<ide> defineReplacableAttribute(globalThis, 'performance',
<del> require('perf_hooks').performance);
<add> perf_hooks.performance);
<ide>
<ide> function createGlobalConsole() {
<ide> const consoleFromNode =
<ide><path>lib/internal/perf/observe.js
<ide> const {
<ide> ArrayPrototypeSort,
<ide> ArrayPrototypeConcat,
<ide> Error,
<add> MathMax,
<add> MathMin,
<ide> ObjectDefineProperties,
<ide> ObjectFreeze,
<ide> ObjectKeys,
<ide> const kSupportedEntryTypes = ObjectFreeze([
<ide> let markEntryBuffer = [];
<ide> let measureEntryBuffer = [];
<ide> let resourceTimingBuffer = [];
<del>const kMaxPerformanceEntryBuffers = 1e6;
<add>let resourceTimingSecondaryBuffer = [];
<add>const kPerformanceEntryBufferWarnSize = 1e6;
<add>// https://www.w3.org/TR/timing-entrytypes-registry/#registry
<add>// Default buffer limit for resource timing entries.
<add>let resourceTimingBufferSizeLimit = 250;
<add>let dispatchBufferFull;
<add>let resourceTimingBufferFullPending = false;
<add>
<ide> const kClearPerformanceEntryBuffers = ObjectFreeze({
<ide> 'mark': 'performance.clearMarks',
<ide> 'measure': 'performance.clearMeasures',
<del> 'resource': 'performance.clearResourceTimings',
<ide> });
<ide> const kWarnedEntryTypes = new SafeMap();
<ide>
<ide> class PerformanceObserver {
<ide> }
<ide> }
<ide>
<add>/**
<add> * https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
<add> *
<add> * Add the performance entry to the interested performance observer's queue.
<add> */
<ide> function enqueue(entry) {
<ide> if (!isPerformanceEntry(entry))
<ide> throw new ERR_INVALID_ARG_TYPE('entry', 'PerformanceEntry', entry);
<ide>
<ide> for (const obs of kObservers) {
<ide> obs[kMaybeBuffer](entry);
<ide> }
<add>}
<ide>
<add>/**
<add> * Add the user timing entry to the global buffer.
<add> */
<add>function bufferUserTiming(entry) {
<ide> const entryType = entry.entryType;
<ide> let buffer;
<ide> if (entryType === 'mark') {
<ide> buffer = markEntryBuffer;
<ide> } else if (entryType === 'measure') {
<ide> buffer = measureEntryBuffer;
<del> } else if (entryType === 'resource') {
<del> buffer = resourceTimingBuffer;
<ide> } else {
<ide> return;
<ide> }
<ide>
<ide> ArrayPrototypePush(buffer, entry);
<ide> const count = buffer.length;
<ide>
<del> if (count > kMaxPerformanceEntryBuffers &&
<add> if (count > kPerformanceEntryBufferWarnSize &&
<ide> !kWarnedEntryTypes.has(entryType)) {
<ide> kWarnedEntryTypes.set(entryType, true);
<ide> // No error code for this since it is a Warning
<ide> function enqueue(entry) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Add the resource timing entry to the global buffer if the buffer size is not
<add> * exceeding the buffer limit, or dispatch a buffer full event on the global
<add> * performance object.
<add> *
<add> * See also https://www.w3.org/TR/resource-timing-2/#dfn-add-a-performanceresourcetiming-entry
<add> */
<add>function bufferResourceTiming(entry) {
<add> if (resourceTimingBuffer.length < resourceTimingBufferSizeLimit && !resourceTimingBufferFullPending) {
<add> ArrayPrototypePush(resourceTimingBuffer, entry);
<add> return;
<add> }
<add>
<add> if (!resourceTimingBufferFullPending) {
<add> resourceTimingBufferFullPending = true;
<add> setImmediate(() => {
<add> while (resourceTimingSecondaryBuffer.length > 0) {
<add> const excessNumberBefore = resourceTimingSecondaryBuffer.length;
<add> dispatchBufferFull('resourcetimingbufferfull');
<add>
<add> // Calculate the number of items to be pushed to the global buffer.
<add> const numbersToPreserve = MathMax(
<add> MathMin(resourceTimingBufferSizeLimit - resourceTimingBuffer.length, resourceTimingSecondaryBuffer.length),
<add> 0
<add> );
<add> const excessNumberAfter = resourceTimingSecondaryBuffer.length - numbersToPreserve;
<add> for (let idx = 0; idx < numbersToPreserve; idx++) {
<add> ArrayPrototypePush(resourceTimingBuffer, resourceTimingSecondaryBuffer[idx]);
<add> }
<add>
<add> if (excessNumberBefore <= excessNumberAfter) {
<add> resourceTimingSecondaryBuffer = [];
<add> }
<add> }
<add> resourceTimingBufferFullPending = false;
<add> });
<add> }
<add>
<add> ArrayPrototypePush(resourceTimingSecondaryBuffer, entry);
<add>}
<add>
<add>// https://w3c.github.io/resource-timing/#dom-performance-setresourcetimingbuffersize
<add>function setResourceTimingBufferSize(maxSize) {
<add> // If the maxSize parameter is less than resource timing buffer current
<add> // size, no PerformanceResourceTiming objects are to be removed from the
<add> // performance entry buffer.
<add> resourceTimingBufferSizeLimit = maxSize;
<add>}
<add>
<add>function setDispatchBufferFull(fn) {
<add> dispatchBufferFull = fn;
<add>}
<add>
<ide> function clearEntriesFromBuffer(type, name) {
<ide> if (type !== 'mark' && type !== 'measure' && type !== 'resource') {
<ide> return;
<ide> module.exports = {
<ide> filterBufferMapByNameAndType,
<ide> startPerf,
<ide> stopPerf,
<add>
<add> bufferUserTiming,
<add> bufferResourceTiming,
<add> setResourceTimingBufferSize,
<add> setDispatchBufferFull,
<ide> };
<ide><path>lib/internal/perf/performance.js
<ide> const {
<ide>
<ide> const {
<ide> EventTarget,
<add> Event,
<add> kTrustEvent,
<ide> } = require('internal/event_target');
<ide>
<ide> const { now } = require('internal/perf/utils');
<ide> const {
<ide> const {
<ide> clearEntriesFromBuffer,
<ide> filterBufferMapByNameAndType,
<add> setResourceTimingBufferSize,
<add> setDispatchBufferFull,
<ide> } = require('internal/perf/observe');
<ide>
<ide> const { eventLoopUtilization } = require('internal/perf/event_loop_utilization');
<ide> ObjectDefineProperties(Performance.prototype, {
<ide> enumerable: false,
<ide> value: now,
<ide> },
<add> setResourceTimingBufferSize: {
<add> __proto__: null,
<add> configurable: true,
<add> enumerable: false,
<add> value: setResourceTimingBufferSize
<add> },
<ide> timerify: {
<ide> __proto__: null,
<ide> configurable: true,
<ide> function refreshTimeOrigin() {
<ide> });
<ide> }
<ide>
<add>const performance = new InternalPerformance();
<add>
<add>function dispatchBufferFull(type) {
<add> const event = new Event(type, {
<add> [kTrustEvent]: true
<add> });
<add> performance.dispatchEvent(event);
<add>}
<add>setDispatchBufferFull(dispatchBufferFull);
<add>
<ide> module.exports = {
<del> InternalPerformance,
<add> Performance,
<add> performance,
<ide> refreshTimeOrigin
<ide> };
<ide><path>lib/internal/perf/resource_timing.js
<ide> const { InternalPerformanceEntry } = require('internal/perf/performance_entry');
<ide> const { SymbolToStringTag } = primordials;
<ide> const assert = require('internal/assert');
<del>const { enqueue } = require('internal/perf/observe');
<add>const { enqueue, bufferResourceTiming } = require('internal/perf/observe');
<ide> const { Symbol, ObjectSetPrototypeOf } = primordials;
<ide>
<ide> const kCacheMode = Symbol('kCacheMode');
<ide> function markResourceTiming(
<ide>
<ide> ObjectSetPrototypeOf(resource, PerformanceResourceTiming.prototype);
<ide> enqueue(resource);
<add> bufferResourceTiming(resource);
<ide> return resource;
<ide> }
<ide>
<ide><path>lib/internal/perf/usertiming.js
<ide> const {
<ide>
<ide> const { InternalPerformanceEntry } = require('internal/perf/performance_entry');
<ide> const { now } = require('internal/perf/utils');
<del>const { enqueue } = require('internal/perf/observe');
<add>const { enqueue, bufferUserTiming } = require('internal/perf/observe');
<ide> const nodeTiming = require('internal/perf/nodetiming');
<ide>
<ide> const {
<ide> class PerformanceMeasure extends InternalPerformanceEntry {
<ide> function mark(name, options = kEmptyObject) {
<ide> const mark = new PerformanceMark(name, options);
<ide> enqueue(mark);
<add> bufferUserTiming(mark);
<ide> return mark;
<ide> }
<ide>
<ide> function measure(name, startOrMeasureOptions, endMark) {
<ide> detail = detail != null ? structuredClone(detail) : null;
<ide> const measure = new PerformanceMeasure(name, start, duration, detail);
<ide> enqueue(measure);
<add> bufferUserTiming(measure);
<ide> return measure;
<ide> }
<ide>
<ide><path>lib/perf_hooks.js
<ide> const {
<ide> PerformanceMark,
<ide> PerformanceMeasure,
<ide> } = require('internal/perf/usertiming');
<del>const { InternalPerformance } = require('internal/perf/performance');
<add>const {
<add> Performance,
<add> performance,
<add>} = require('internal/perf/performance');
<ide>
<ide> const {
<ide> createHistogram
<ide> const {
<ide> const monitorEventLoopDelay = require('internal/perf/event_loop_delay');
<ide>
<ide> module.exports = {
<add> Performance,
<ide> PerformanceEntry,
<ide> PerformanceMark,
<ide> PerformanceMeasure,
<ide> module.exports = {
<ide> PerformanceResourceTiming,
<ide> monitorEventLoopDelay,
<ide> createHistogram,
<del> performance: new InternalPerformance(),
<add> performance,
<ide> };
<ide>
<ide> ObjectDefineProperty(module.exports, 'constants', {
<ide><path>test/common/index.js
<ide> if (global.gc) {
<ide> knownGlobals.push(global.gc);
<ide> }
<ide>
<add>if (global.Performance) {
<add> knownGlobals.push(global.Performance);
<add>}
<ide> if (global.performance) {
<ide> knownGlobals.push(global.performance);
<ide> }
<ide><path>test/parallel/test-performance-resourcetimingbufferfull.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<add>const { performance } = require('perf_hooks');
<add>
<add>function createTimingInfo(startTime) {
<add> const timingInfo = {
<add> startTime: startTime,
<add> endTime: startTime,
<add> finalServiceWorkerStartTime: 0,
<add> redirectStartTime: 0,
<add> redirectEndTime: 0,
<add> postRedirectStartTime: 0,
<add> finalConnectionTimingInfo: {
<add> domainLookupStartTime: 0,
<add> domainLookupEndTime: 0,
<add> connectionStartTime: 0,
<add> connectionEndTime: 0,
<add> secureConnectionStartTime: 0,
<add> ALPNNegotiatedProtocol: 0,
<add> },
<add> finalNetworkRequestStartTime: 0,
<add> finalNetworkResponseStartTime: 0,
<add> encodedBodySize: 0,
<add> decodedBodySize: 0,
<add> };
<add> return timingInfo;
<add>}
<add>const requestedUrl = 'https://nodejs.org';
<add>const initiatorType = '';
<add>const cacheMode = '';
<add>
<add>async function main() {
<add> performance.setResourceTimingBufferSize(1);
<add> performance.markResourceTiming(createTimingInfo(1), requestedUrl, initiatorType, globalThis, cacheMode);
<add> // Trigger a resourcetimingbufferfull event.
<add> performance.markResourceTiming(createTimingInfo(2), requestedUrl, initiatorType, globalThis, cacheMode);
<add> performance.markResourceTiming(createTimingInfo(3), requestedUrl, initiatorType, globalThis, cacheMode);
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 1);
<add>
<add> // Clear resource timings on resourcetimingbufferfull event.
<add> await new Promise((resolve) => {
<add> const listener = common.mustCall((event) => {
<add> assert.strictEqual(event.type, 'resourcetimingbufferfull');
<add> performance.removeEventListener('resourcetimingbufferfull', listener);
<add>
<add> performance.clearResourceTimings();
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 0);
<add>
<add> resolve();
<add> });
<add> performance.addEventListener('resourcetimingbufferfull', listener);
<add> });
<add>
<add> // Secondary buffer has been added to the global buffer.
<add> {
<add> const entries = performance.getEntriesByType('resource');
<add> assert.strictEqual(entries.length, 1);
<add> assert.strictEqual(entries[0].startTime, 2);
<add> // The last item is discarded.
<add> }
<add>
<add>
<add> performance.clearResourceTimings();
<add> performance.setResourceTimingBufferSize(1);
<add> performance.markResourceTiming(createTimingInfo(4), requestedUrl, initiatorType, globalThis, cacheMode);
<add> // Trigger a resourcetimingbufferfull event.
<add> performance.markResourceTiming(createTimingInfo(5), requestedUrl, initiatorType, globalThis, cacheMode);
<add> performance.markResourceTiming(createTimingInfo(6), requestedUrl, initiatorType, globalThis, cacheMode);
<add>
<add> // Increase the buffer size on resourcetimingbufferfull event.
<add> await new Promise((resolve) => {
<add> const listener = common.mustCall((event) => {
<add> assert.strictEqual(event.type, 'resourcetimingbufferfull');
<add> performance.removeEventListener('resourcetimingbufferfull', listener);
<add>
<add> performance.setResourceTimingBufferSize(2);
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 1);
<add>
<add> resolve();
<add> });
<add> performance.addEventListener('resourcetimingbufferfull', listener);
<add> });
<add>
<add> // Secondary buffer has been added to the global buffer.
<add> {
<add> const entries = performance.getEntriesByType('resource');
<add> assert.strictEqual(entries.length, 2);
<add> assert.strictEqual(entries[0].startTime, 4);
<add> assert.strictEqual(entries[1].startTime, 5);
<add> // The last item is discarded.
<add> }
<add>
<add>
<add> performance.clearResourceTimings();
<add> performance.setResourceTimingBufferSize(2);
<add> performance.markResourceTiming(createTimingInfo(7), requestedUrl, initiatorType, globalThis, cacheMode);
<add> performance.markResourceTiming(createTimingInfo(8), requestedUrl, initiatorType, globalThis, cacheMode);
<add> // Trigger a resourcetimingbufferfull event.
<add> performance.markResourceTiming(createTimingInfo(9), requestedUrl, initiatorType, globalThis, cacheMode);
<add>
<add> // Decrease the buffer size on resourcetimingbufferfull event.
<add> await new Promise((resolve) => {
<add> const listener = common.mustCall((event) => {
<add> assert.strictEqual(event.type, 'resourcetimingbufferfull');
<add> performance.removeEventListener('resourcetimingbufferfull', listener);
<add>
<add> performance.setResourceTimingBufferSize(1);
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 2);
<add>
<add> resolve();
<add> });
<add> performance.addEventListener('resourcetimingbufferfull', listener);
<add> });
<add>
<add> // Secondary buffer has been added to the global buffer.
<add> {
<add> const entries = performance.getEntriesByType('resource');
<add> assert.strictEqual(entries.length, 2);
<add> assert.strictEqual(entries[0].startTime, 7);
<add> assert.strictEqual(entries[1].startTime, 8);
<add> // The last item is discarded.
<add> }
<add>}
<add>
<add>main();
<ide><path>test/parallel/test-performance-resourcetimingbuffersize.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<add>const { performance } = require('perf_hooks');
<add>
<add>const timingInfo = {
<add> startTime: 0,
<add> endTime: 0,
<add> finalServiceWorkerStartTime: 0,
<add> redirectStartTime: 0,
<add> redirectEndTime: 0,
<add> postRedirectStartTime: 0,
<add> finalConnectionTimingInfo: {
<add> domainLookupStartTime: 0,
<add> domainLookupEndTime: 0,
<add> connectionStartTime: 0,
<add> connectionEndTime: 0,
<add> secureConnectionStartTime: 0,
<add> ALPNNegotiatedProtocol: 0,
<add> },
<add> finalNetworkRequestStartTime: 0,
<add> finalNetworkResponseStartTime: 0,
<add> encodedBodySize: 0,
<add> decodedBodySize: 0,
<add>};
<add>const requestedUrl = 'https://nodejs.org';
<add>const initiatorType = '';
<add>const cacheMode = '';
<add>
<add>async function main() {
<add> performance.setResourceTimingBufferSize(1);
<add> performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, globalThis, cacheMode);
<add> // Trigger a resourcetimingbufferfull event.
<add> performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, globalThis, cacheMode);
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 1);
<add> await waitBufferFullEvent();
<add>
<add> // Apply a new buffer size limit
<add> performance.setResourceTimingBufferSize(0);
<add> // Buffer is not cleared on `performance.setResourceTimingBufferSize`.
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 1);
<add>
<add> performance.clearResourceTimings();
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 0);
<add> // Trigger a resourcetimingbufferfull event.
<add> performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, globalThis, cacheMode);
<add> // New entry is not added to the global buffer.
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 0);
<add> await waitBufferFullEvent();
<add>
<add> // Apply a new buffer size limit
<add> performance.setResourceTimingBufferSize(1);
<add> performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, globalThis, cacheMode);
<add> assert.strictEqual(performance.getEntriesByType('resource').length, 1);
<add>}
<add>
<add>function waitBufferFullEvent() {
<add> return new Promise((resolve) => {
<add> const listener = common.mustCall((event) => {
<add> assert.strictEqual(event.type, 'resourcetimingbufferfull');
<add> performance.removeEventListener('resourcetimingbufferfull', listener);
<add> resolve();
<add> });
<add> performance.addEventListener('resourcetimingbufferfull', listener);
<add> });
<add>}
<add>
<add>main(); | 10 |
Ruby | Ruby | enable tmp_restart plugin for puma | 685203917378dbdf8c836d5bdaabccd31f4e5f98 | <ide><path>railties/lib/rails/generators/rails/app/templates/config/puma.rb
<ide> # on_worker_boot do
<ide> # ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
<ide> # end
<add>
<add># Allow puma to be restarted by `rails restart` command.
<add>plugin :tmp_restart | 1 |
Javascript | Javascript | prevent accidental misuse of properties on $event | e057a9aa398ead209bd6bbf76e22d2d5562904fb | <ide><path>src/ng/directive/ngEventDirs.js
<ide> forEach(
<ide> return {
<ide> restrict: 'A',
<ide> compile: function($element, attr) {
<del> var fn = $parse(attr[directiveName]);
<add> // We expose the powerful $event object on the scope that provides access to the Window,
<add> // etc. that isn't protected by the fast paths in $parse. We explicitly request better
<add> // checks at the cost of speed since event handler expressions are not executed as
<add> // frequently as regular change detection.
<add> var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
<ide> return function ngEventHandler(scope, element) {
<ide> element.on(eventName, function(event) {
<ide> var callback = function() {
<ide><path>src/ng/parse.js
<ide> function setter(obj, path, setValue, fullExp) {
<ide> return setValue;
<ide> }
<ide>
<del>var getterFnCache = createMap();
<add>var getterFnCacheDefault = createMap();
<add>var getterFnCacheExpensive = createMap();
<ide>
<ide> function isPossiblyDangerousMemberName(name) {
<ide> return name == 'constructor';
<ide> function isPossiblyDangerousMemberName(name) {
<ide> * - http://jsperf.com/angularjs-parse-getter/4
<ide> * - http://jsperf.com/path-evaluation-simplified/7
<ide> */
<del>function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) {
<add>function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
<ide> ensureSafeMemberName(key0, fullExp);
<ide> ensureSafeMemberName(key1, fullExp);
<ide> ensureSafeMemberName(key2, fullExp);
<ide> function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) {
<ide> var eso = function(o) {
<ide> return ensureSafeObject(o, fullExp);
<ide> };
<del> var eso0 = isPossiblyDangerousMemberName(key0) ? eso : identity;
<del> var eso1 = isPossiblyDangerousMemberName(key1) ? eso : identity;
<del> var eso2 = isPossiblyDangerousMemberName(key2) ? eso : identity;
<del> var eso3 = isPossiblyDangerousMemberName(key3) ? eso : identity;
<del> var eso4 = isPossiblyDangerousMemberName(key4) ? eso : identity;
<add> var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
<add> var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
<add> var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
<add> var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
<add> var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
<ide>
<ide> return function cspSafeGetter(scope, locals) {
<ide> var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
<ide> function getterFnWithEnsureSafeObject(fn, fullExpression) {
<ide> }
<ide>
<ide> function getterFn(path, options, fullExp) {
<add> var expensiveChecks = options.expensiveChecks;
<add> var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
<ide> var fn = getterFnCache[path];
<del>
<ide> if (fn) return fn;
<ide>
<add>
<ide> var pathKeys = path.split('.'),
<ide> pathKeysLength = pathKeys.length;
<ide>
<ide> // http://jsperf.com/angularjs-parse-getter/6
<ide> if (options.csp) {
<ide> if (pathKeysLength < 6) {
<del> fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp);
<add> fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
<ide> } else {
<ide> fn = function cspSafeGetter(scope, locals) {
<ide> var i = 0, val;
<ide> do {
<ide> val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
<del> pathKeys[i++], fullExp)(scope, locals);
<add> pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
<ide>
<ide> locals = undefined; // clear after first iteration
<ide> scope = val;
<ide> function getterFn(path, options, fullExp) {
<ide> }
<ide> } else {
<ide> var code = '';
<del> var needsEnsureSafeObject = false;
<add> if (expensiveChecks) {
<add> code += 's = eso(s, fe);\nl = eso(l, fe);\n';
<add> }
<add> var needsEnsureSafeObject = expensiveChecks;
<ide> forEach(pathKeys, function(key, index) {
<ide> ensureSafeMemberName(key, fullExp);
<ide> var lookupJs = (index
<ide> // we simply dereference 's' on any .dot notation
<ide> ? 's'
<ide> // but if we are first then we check locals first, and if so read it first
<ide> : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
<del> if (isPossiblyDangerousMemberName(key)) {
<add> if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
<ide> lookupJs = 'eso(' + lookupJs + ', fe)';
<ide> needsEnsureSafeObject = true;
<ide> }
<ide> function getValueOf(value) {
<ide> * service.
<ide> */
<ide> function $ParseProvider() {
<del> var cache = createMap();
<add> var cacheDefault = createMap();
<add> var cacheExpensive = createMap();
<ide>
<del> var $parseOptions = {
<del> csp: false
<del> };
<ide>
<ide>
<ide> this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
<del> $parseOptions.csp = $sniffer.csp;
<add> var $parseOptions = {
<add> csp: $sniffer.csp,
<add> expensiveChecks: false
<add> },
<add> $parseOptionsExpensive = {
<add> csp: $sniffer.csp,
<add> expensiveChecks: true
<add> };
<ide>
<ide> function wrapSharedExpression(exp) {
<ide> var wrapped = exp;
<ide> function $ParseProvider() {
<ide> return wrapped;
<ide> }
<ide>
<del> return function $parse(exp, interceptorFn) {
<add> return function $parse(exp, interceptorFn, expensiveChecks) {
<ide> var parsedExpression, oneTime, cacheKey;
<ide>
<ide> switch (typeof exp) {
<ide> case 'string':
<ide> cacheKey = exp = exp.trim();
<ide>
<add> var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
<ide> parsedExpression = cache[cacheKey];
<ide>
<ide> if (!parsedExpression) {
<ide> function $ParseProvider() {
<ide> exp = exp.substring(2);
<ide> }
<ide>
<del> var lexer = new Lexer($parseOptions);
<del> var parser = new Parser(lexer, $filter, $parseOptions);
<add> var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
<add> var lexer = new Lexer(parseOptions);
<add> var parser = new Parser(lexer, $filter, parseOptions);
<ide> parsedExpression = parser.parse(exp);
<ide>
<ide> if (parsedExpression.constant) {
<ide><path>test/ng/directive/ngEventDirsSpec.js
<ide> describe('event directives', function() {
<ide>
<ide> });
<ide>
<add> describe('security', function() {
<add> it('should allow access to the $event object', inject(function($rootScope, $compile) {
<add> var scope = $rootScope.$new();
<add> element = $compile('<button ng-click="e = $event">BTN</button>')(scope);
<add> element.triggerHandler('click');
<add> expect(scope.e.target).toBe(element[0]);
<add> }));
<add>
<add> it('should block access to DOM nodes (e.g. exposed via $event)', inject(function($rootScope, $compile) {
<add> var scope = $rootScope.$new();
<add> element = $compile('<button ng-click="e = $event.target">BTN</button>')(scope);
<add> expect(function() {
<add> element.triggerHandler('click');
<add> }).toThrowMinErr(
<add> '$parse', 'isecdom', 'Referencing DOM nodes in Angular expressions is disallowed! ' +
<add> 'Expression: e = $event.target');
<add> }));
<add> });
<add>
<ide> describe('blur', function() {
<ide>
<ide> describe('call the listener asynchronously during $apply', function() {
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide>
<ide> beforeEach(function() {
<del> /* global getterFnCache: true */
<del> // clear cache
<del> getterFnCache = createMap();
<add> /* global getterFnCacheDefault: true */
<add> /* global getterFnCacheExpensive: true */
<add> // clear caches
<add> getterFnCacheDefault = createMap();
<add> getterFnCacheExpensive = createMap();
<ide> });
<ide>
<ide>
<ide> describe('parser', function() {
<ide> 'Expression: foo["bar"]');
<ide>
<ide> });
<add>
<add> describe('expensiveChecks', function() {
<add> it('should block access to window object even when aliased', inject(function($parse, $window) {
<add> scope.foo = {w: $window};
<add> // This isn't blocked for performance.
<add> expect(scope.$eval($parse('foo.w'))).toBe($window);
<add> // Event handlers use the more expensive path for better protection since they expose
<add> // the $event object on the scope.
<add> expect(function() {
<add> scope.$eval($parse('foo.w', null, true));
<add> }).toThrowMinErr(
<add> '$parse', 'isecwindow', 'Referencing the Window in Angular expressions is disallowed! ' +
<add> 'Expression: foo.w');
<add>
<add> }));
<add> });
<ide> });
<ide>
<ide> describe('Function prototype functions', function() { | 4 |
PHP | PHP | remove default value from cache driver interface | 3eeb69d1bf642eb35883e60362ff373d0783601a | <ide><path>system/cache/driver.php
<ide> public function has($key);
<ide> * Get an item from the cache.
<ide> *
<ide> * @param string $key
<del> * @param mixed $default
<ide> * @return mixed
<ide> */
<del> public function get($key, $default = null);
<add> public function get($key);
<ide>
<ide> /**
<ide> * Write an item to the cache. | 1 |
Python | Python | fix bug in convlstm | 21bf90cbf561250b256d7b30c7545da3bf092552 | <ide><path>keras/layers/convolutional_recurrent.py
<ide> def build(self, input_shape):
<ide> self.reset_states()
<ide> else:
<ide> # initial states: 2 all-zero tensor of shape (filters)
<del> self.states = [None, None, None, None]
<add> self.states = [None, None]
<ide>
<ide> if self.data_format == 'channels_first':
<ide> channel_axis = 1 | 1 |
Ruby | Ruby | add a host method to hashconfig | b6f398bcfd4a427de18e83bea1cef5ac8eb8ce3c | <ide><path>activerecord/lib/active_record/database_configurations/database_config.rb
<ide> def adapter_method
<ide> "#{adapter}_connection"
<ide> end
<ide>
<add> def host
<add> raise NotImplementedError
<add> end
<add>
<ide> def database
<ide> raise NotImplementedError
<ide> end
<ide><path>activerecord/lib/active_record/database_configurations/hash_config.rb
<ide> def migrations_paths
<ide> configuration_hash[:migrations_paths]
<ide> end
<ide>
<add> def host
<add> configuration_hash[:host]
<add> end
<add>
<ide> def database
<ide> configuration_hash[:database]
<ide> end
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb
<ide> def each_local_configuration
<ide> end
<ide>
<ide> def local_database?(db_config)
<del> host = db_config.configuration_hash[:host]
<add> host = db_config.host
<ide> host.blank? || LOCAL_HOSTS.include?(host)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
<ide> def establish_master_connection
<ide> end
<ide>
<ide> def set_psql_env
<del> ENV["PGHOST"] = configuration_hash[:host] if configuration_hash[:host]
<add> ENV["PGHOST"] = db_config.host if db_config.host
<ide> ENV["PGPORT"] = configuration_hash[:port].to_s if configuration_hash[:port]
<ide> ENV["PGPASSWORD"] = configuration_hash[:password].to_s if configuration_hash[:password]
<ide> ENV["PGUSER"] = configuration_hash[:username].to_s if configuration_hash[:username] | 4 |
Javascript | Javascript | convert require to import in libraries/components | 0afd71a18d19edef3d6603cabd2672ffde5ba30e | <ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const Platform = require('../../Utilities/Platform');
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const View = require('../View/View');
<add>import * as React from 'react';
<add>import Platform from '../../Utilities/Platform';
<add>import StyleSheet, {type ColorValue} from '../../StyleSheet/StyleSheet';
<add>import View from '../View/View';
<ide> import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide>
<ide> const PlatformActivityIndicator =
<ide> Platform.OS === 'android'
<ide><path>Libraries/Components/Button.js
<ide>
<ide> 'use strict';
<ide>
<del>const Platform = require('../Utilities/Platform');
<del>const React = require('react');
<del>const StyleSheet = require('../StyleSheet/StyleSheet');
<del>const Text = require('../Text/Text');
<del>const TouchableNativeFeedback = require('./Touchable/TouchableNativeFeedback');
<del>const TouchableOpacity = require('./Touchable/TouchableOpacity');
<del>const View = require('./View/View');
<del>const invariant = require('invariant');
<add>import * as React from 'react';
<add>import Platform from '../Utilities/Platform';
<add>import StyleSheet, {type ColorValue} from '../StyleSheet/StyleSheet';
<add>import Text from '../Text/Text';
<add>import TouchableNativeFeedback from './Touchable/TouchableNativeFeedback';
<add>import TouchableOpacity from './Touchable/TouchableOpacity';
<add>import View from './View/View';
<add>import invariant from 'invariant';
<ide>
<ide> import type {AccessibilityState} from './View/ViewAccessibility';
<ide> import type {PressEvent} from '../Types/CoreEventTypes';
<del>import type {ColorValue} from '../StyleSheet/StyleSheet';
<ide>
<ide> type ButtonProps = $ReadOnly<{|
<ide> /**
<ide><path>Libraries/Components/DatePicker/DatePickerIOS.android.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const Text = require('../../Text/Text');
<del>const View = require('../View/View');
<add>import * as React from 'react';
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<add>import Text from '../../Text/Text';
<add>import View from '../View/View';
<ide>
<ide> class DummyDatePickerIOS extends React.Component {
<ide> render() {
<ide><path>Libraries/Components/DatePicker/DatePickerIOS.ios.js
<ide>
<ide> // This is a controlled component version of RCTDatePickerIOS.
<ide>
<add>import * as React from 'react';
<ide> import RCTDatePickerNativeComponent, {
<ide> Commands as DatePickerCommands,
<ide> } from './RCTDatePickerNativeComponent';
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const View = require('../View/View');
<del>
<del>const invariant = require('invariant');
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<add>import View from '../View/View';
<add>import invariant from 'invariant';
<ide>
<ide> import type {SyntheticEvent} from '../../Types/CoreEventTypes';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide><path>Libraries/Components/Keyboard/Keyboard.js
<ide> import LayoutAnimation from '../../LayoutAnimation/LayoutAnimation';
<ide> import dismissKeyboard from '../../Utilities/dismissKeyboard';
<ide> import Platform from '../../Utilities/Platform';
<ide> import NativeKeyboardObserver from './NativeKeyboardObserver';
<del>import {type EventSubscription} from '../../vendor/emitter/EventEmitter';
<add>import type {EventSubscription} from '../../vendor/emitter/EventEmitter';
<ide>
<ide> export type KeyboardEventName = $Keys<KeyboardEventDefinitions>;
<ide>
<ide><path>Libraries/Components/MaskedView/MaskedViewIOS.ios.js
<ide> * @flow
<ide> */
<ide>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const View = require('../View/View');
<add>import * as React from 'react';
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<add>import View from '../View/View';
<ide>
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide> import RCTMaskedViewNativeComponent from './RCTMaskedViewNativeComponent';
<ide><path>Libraries/Components/Picker/Picker.js
<ide>
<ide> 'use strict';
<ide>
<del>const PickerAndroid = require('./PickerAndroid');
<del>const PickerIOS = require('./PickerIOS');
<del>const Platform = require('../../Utilities/Platform');
<del>const React = require('react');
<del>const UnimplementedView = require('../UnimplementedViews/UnimplementedView');
<del>
<del>import type {TextStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<add>import * as React from 'react';
<add>import PickerAndroid from './PickerAndroid';
<add>import PickerIOS from './PickerIOS';
<add>import Platform from '../../Utilities/Platform';
<add>import UnimplementedView from '../UnimplementedViews/UnimplementedView';
<add>
<add>import type {TextStyleProp, ColorValue} from '../../StyleSheet/StyleSheet';
<ide>
<ide> const MODE_DIALOG = 'dialog';
<ide> const MODE_DROPDOWN = 'dropdown';
<ide><path>Libraries/Components/Picker/PickerIOS.ios.js
<ide>
<ide> // This is a controlled component version of RCTPickerIOS.
<ide>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const View = require('../View/View');
<del>
<del>const invariant = require('invariant');
<del>const processColor = require('../../StyleSheet/processColor');
<add>import * as React from 'react';
<add>import StyleSheet, {
<add> type TextStyleProp,
<add> type ColorValue,
<add>} from '../../StyleSheet/StyleSheet';
<add>import View from '../View/View';
<add>import invariant from 'invariant';
<add>import processColor, {
<add> type ProcessedColorValue,
<add>} from '../../StyleSheet/processColor';
<ide>
<ide> import RCTPickerNativeComponent, {
<ide> Commands as PickerCommands,
<ide> } from './RCTPickerNativeComponent';
<del>import type {TextStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<del>import type {ProcessedColorValue} from '../../StyleSheet/processColor';
<ide> import type {SyntheticEvent} from '../../Types/CoreEventTypes';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide>
<ide><path>Libraries/Components/ProgressViewIOS/ProgressViewIOS.android.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const Text = require('../../Text/Text');
<del>const View = require('../View/View');
<add>import * as React from 'react';
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<add>import Text from '../../Text/Text';
<add>import View from '../View/View';
<ide>
<ide> class DummyProgressViewIOS extends React.Component {
<ide> render() {
<ide><path>Libraries/Components/ProgressViewIOS/ProgressViewIOS.ios.js
<ide> * @flow strict-local
<ide> */
<ide>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<add>import * as React from 'react';
<add>import StyleSheet, {type ColorValue} from '../../StyleSheet/StyleSheet';
<ide>
<ide> import RCTProgressViewNativeComponent from './RCTProgressViewNativeComponent';
<ide> import type {ImageSource} from '../../Image/ImageSource';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide>
<ide> type Props = $ReadOnly<{|
<ide><path>Libraries/Components/RefreshControl/__mocks__/RefreshControlMock.js
<ide> */
<ide>
<ide> 'use strict';
<add>import * as React from 'react';
<ide>
<del>const React = require('react');
<del>
<del>const requireNativeComponent = require('../../../ReactNative/requireNativeComponent');
<add>import requireNativeComponent from '../../../ReactNative/requireNativeComponent';
<ide>
<ide> import type {HostComponent} from '../../../Renderer/shims/ReactNativeTypes';
<ide>
<ide><path>Libraries/Components/ScrollView/AndroidHorizontalScrollViewNativeComponent.js
<ide> * @format
<ide> */
<ide>
<del>import {type ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
<del>import {type HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<ide> import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry';
<ide>
<ide> const AndroidHorizontalScrollViewNativeComponent: HostComponent<Props> = NativeComponentRegistry.get<Props>(
<ide><path>Libraries/Components/ScrollView/ScrollContentViewNativeComponent.js
<ide> * @flow
<ide> */
<ide>
<del>import {type HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<ide> import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry';
<del>import {type ViewProps as Props} from '../View/ViewPropTypes';
<add>import type {ViewProps as Props} from '../View/ViewPropTypes';
<ide>
<ide> const ScrollContentViewNativeComponent: HostComponent<Props> = NativeComponentRegistry.get<Props>(
<ide> 'RCTScrollContentView',
<ide><path>Libraries/Components/ScrollView/ScrollViewNativeComponent.js
<ide> * @format
<ide> */
<ide>
<del>import {type ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
<del>import {type HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<ide> import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry';
<ide>
<ide> const ScrollViewNativeComponent: HostComponent<Props> = NativeComponentRegistry.get<Props>(
<ide><path>Libraries/Components/SegmentedControlIOS/SegmentedControlIOS.android.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const Text = require('../../Text/Text');
<del>const View = require('../View/View');
<add>import * as React from 'react';
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<add>import Text from '../../Text/Text';
<add>import View from '../View/View';
<ide>
<ide> class DummySegmentedControlIOS extends React.Component {
<ide> render() {
<ide><path>Libraries/Components/Slider/Slider.js
<ide> * @flow strict-local
<ide> */
<ide>
<del>const Platform = require('../../Utilities/Platform');
<add>import * as React from 'react';
<add>import Platform from '../../Utilities/Platform';
<ide> import SliderNativeComponent from './SliderNativeComponent';
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<add>import StyleSheet, {
<add> type ViewStyleProp,
<add> type ColorValue,
<add>} from '../../StyleSheet/StyleSheet';
<ide>
<ide> import type {ImageSource} from '../../Image/ImageSource';
<del>import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide> import type {SyntheticEvent} from '../../Types/CoreEventTypes';
<ide>
<ide><path>Libraries/Components/StatusBar/StatusBar.js
<ide> * @flow
<ide> */
<ide>
<del>const Platform = require('../../Utilities/Platform');
<del>const React = require('react');
<del>
<del>const invariant = require('invariant');
<del>const processColor = require('../../StyleSheet/processColor');
<add>import * as React from 'react';
<add>import Platform from '../../Utilities/Platform';
<add>import invariant from 'invariant';
<add>import processColor from '../../StyleSheet/processColor';
<ide> import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide>
<ide> import NativeStatusBarManagerAndroid from './NativeStatusBarManagerAndroid';
<ide><path>Libraries/Components/TextInput/AndroidTextInputNativeComponent.js
<ide> import type {
<ide> WithDefault,
<ide> } from '../../Types/CodegenTypes';
<ide> import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<del>import type {TextStyleProp, ViewStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<add>import type {
<add> TextStyleProp,
<add> ViewStyleProp,
<add> ColorValue,
<add>} from '../../StyleSheet/StyleSheet';
<ide> import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<ide> import type {TextInputNativeCommands} from './TextInputNativeCommands';
<ide><path>Libraries/Components/TextInput/AndroidTextInputViewConfig.js
<ide> */
<ide>
<ide> import ReactNativeViewViewConfig from '../../Components/View/ReactNativeViewViewConfig';
<del>import {type PartialViewConfig} from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
<add>import type {PartialViewConfig} from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
<ide>
<ide> const AndroidTextInputViewConfig = {
<ide> uiViewClassName: 'AndroidTextInput',
<ide><path>Libraries/Components/TextInput/InputAccessoryView.js
<ide> * @format
<ide> */
<ide>
<del>const Platform = require('../../Utilities/Platform');
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<add>import * as React from 'react';
<add>import Platform from '../../Utilities/Platform';
<add>import StyleSheet, {
<add> type ViewStyleProp,
<add> type ColorValue,
<add>} from '../../StyleSheet/StyleSheet';
<ide>
<ide> import RCTInputAccessoryViewNativeComponent from './RCTInputAccessoryViewNativeComponent';
<ide>
<del>import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<del>
<ide> /**
<ide> * Note: iOS only
<ide> *
<ide><path>Libraries/Components/TextInput/RCTMultilineTextInputNativeComponent.js
<ide> import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<ide> import type {TextInputNativeCommands} from './TextInputNativeCommands';
<ide> import RCTTextInputViewConfig from './RCTTextInputViewConfig';
<del>const ReactNativeViewConfigRegistry = require('../../Renderer/shims/ReactNativeViewConfigRegistry');
<add>import ReactNativeViewConfigRegistry from '../../Renderer/shims/ReactNativeViewConfigRegistry';
<ide>
<ide> type NativeType = HostComponent<mixed>;
<ide>
<ide><path>Libraries/Components/TextInput/RCTSingelineTextInputNativeComponent.js
<ide> import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<ide> import type {TextInputNativeCommands} from './TextInputNativeCommands';
<ide> import RCTTextInputViewConfig from './RCTTextInputViewConfig';
<del>const ReactNativeViewConfigRegistry = require('../../Renderer/shims/ReactNativeViewConfigRegistry');
<add>import ReactNativeViewConfigRegistry from '../../Renderer/shims/ReactNativeViewConfigRegistry';
<ide>
<ide> type NativeType = HostComponent<mixed>;
<ide>
<ide><path>Libraries/Components/TextInput/RCTTextInputViewConfig.js
<ide> */
<ide>
<ide> import ReactNativeViewViewConfig from '../../Components/View/ReactNativeViewViewConfig';
<del>import {type ViewConfig} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {ViewConfig} from '../../Renderer/shims/ReactNativeTypes';
<ide>
<ide> const RCTTextInputViewConfig = {
<ide> uiViewClassName: 'RCTSinglelineTextInputView',
<ide><path>Libraries/Components/TextInput/TextInput.js
<ide> * @format
<ide> */
<ide>
<del>const DeprecatedTextInputPropTypes = require('../../DeprecatedPropTypes/DeprecatedTextInputPropTypes');
<del>const Platform = require('../../Utilities/Platform');
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const Text = require('../../Text/Text');
<del>const TextAncestor = require('../../Text/TextAncestor');
<del>const TextInputState = require('./TextInputState');
<del>
<del>const invariant = require('invariant');
<del>const nullthrows = require('nullthrows');
<del>const setAndForwardRef = require('../../Utilities/setAndForwardRef');
<add>import * as React from 'react';
<add>
<add>import DeprecatedTextInputPropTypes from '../../DeprecatedPropTypes/DeprecatedTextInputPropTypes';
<add>
<add>import Platform from '../../Utilities/Platform';
<add>import StyleSheet, {
<add> type TextStyleProp,
<add> type ViewStyleProp,
<add> type ColorValue,
<add>} from '../../StyleSheet/StyleSheet';
<add>import Text from '../../Text/Text';
<add>import TextAncestor from '../../Text/TextAncestor';
<add>import TextInputState from './TextInputState';
<add>import invariant from 'invariant';
<add>import nullthrows from 'nullthrows';
<add>import setAndForwardRef from '../../Utilities/setAndForwardRef';
<ide>
<ide> import usePressability from '../../Pressability/usePressability';
<ide>
<del>import type {TextStyleProp, ViewStyleProp} from '../../StyleSheet/StyleSheet';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<del>import type {SyntheticEvent, ScrollEvent} from '../../Types/CoreEventTypes';
<del>import type {PressEvent} from '../../Types/CoreEventTypes';
<add>import type {
<add> SyntheticEvent,
<add> ScrollEvent,
<add> PressEvent,
<add>} from '../../Types/CoreEventTypes';
<ide> import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<ide> import type {TextInputNativeCommands} from './TextInputNativeCommands';
<ide>
<ide><path>Libraries/Components/Touchable/BoundingDimensions.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const PooledClass = require('./PooledClass');
<add>import PooledClass from './PooledClass';
<ide>
<ide> const twoArgumentPooler = PooledClass.twoArgumentPooler;
<ide>
<ide><path>Libraries/Components/Touchable/PooledClass.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const invariant = require('invariant');
<add>import invariant from 'invariant';
<ide>
<ide> /**
<ide> * Static poolers. Several custom versions for each potential number of
<ide><path>Libraries/Components/Touchable/Position.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const PooledClass = require('./PooledClass');
<add>import PooledClass from './PooledClass';
<ide>
<ide> const twoArgumentPooler = PooledClass.twoArgumentPooler;
<ide>
<ide><path>Libraries/Components/Touchable/Touchable.js
<ide> * @format
<ide> */
<ide>
<del>const BoundingDimensions = require('./BoundingDimensions');
<del>const Platform = require('../../Utilities/Platform');
<del>const Position = require('./Position');
<del>const React = require('react');
<del>const UIManager = require('../../ReactNative/UIManager');
<del>const SoundManager = require('../Sound/SoundManager');
<add>import * as React from 'react';
<add>import BoundingDimensions from './BoundingDimensions';
<add>import Platform from '../../Utilities/Platform';
<add>import Position from './Position';
<add>import UIManager from '../../ReactNative/UIManager';
<add>import SoundManager from '../Sound/SoundManager';
<ide>
<ide> import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
<ide>
<ide><path>Libraries/Components/Touchable/ensurePositiveDelayProps.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const invariant = require('invariant');
<add>import invariant from 'invariant';
<ide>
<ide> const ensurePositiveDelayProps = function(props: any) {
<ide> invariant(
<ide><path>Libraries/Components/UnimplementedViews/UnimplementedView.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<add>import * as React from 'react';
<add>import StyleSheet from '../../StyleSheet/StyleSheet';
<ide>
<ide> /**
<ide> * Common implementation for a simple stubbed view. Simply applies the view's styles to the inner
<ide><path>Libraries/Components/View/ReactNativeStyleAttributes.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const DeprecatedImageStylePropTypes = require('../../DeprecatedPropTypes/DeprecatedImageStylePropTypes');
<del>const DeprecatedTextStylePropTypes = require('../../DeprecatedPropTypes/DeprecatedTextStylePropTypes');
<del>const DeprecatedViewStylePropTypes = require('../../DeprecatedPropTypes/DeprecatedViewStylePropTypes');
<del>
<del>const processColor = require('../../StyleSheet/processColor');
<del>const processTransform = require('../../StyleSheet/processTransform');
<del>const sizesDiffer = require('../../Utilities/differ/sizesDiffer');
<add>import DeprecatedImageStylePropTypes from '../../DeprecatedPropTypes/DeprecatedImageStylePropTypes';
<add>import DeprecatedTextStylePropTypes from '../../DeprecatedPropTypes/DeprecatedTextStylePropTypes';
<add>import DeprecatedViewStylePropTypes from '../../DeprecatedPropTypes/DeprecatedViewStylePropTypes';
<add>import processColor from '../../StyleSheet/processColor';
<add>import processTransform from '../../StyleSheet/processTransform';
<add>import sizesDiffer from '../../Utilities/differ/sizesDiffer';
<ide>
<ide> type ReturnBoolType = <V>(V) => true;
<ide> type BoolifiedDeprecatedViewStylePropTypes = $ObjMap<
<ide><path>Libraries/Components/View/ReactNativeViewAttributes.js
<ide> */
<ide>
<ide> 'use strict';
<del>
<del>const ReactNativeStyleAttributes = require('./ReactNativeStyleAttributes');
<add>import ReactNativeStyleAttributes from './ReactNativeStyleAttributes';
<ide>
<ide> const UIView = {
<ide> pointerEvents: true,
<ide><path>Libraries/Components/View/ReactNativeViewViewConfig.js
<ide> * @format
<ide> */
<ide>
<del>import {type ViewConfig} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {ViewConfig} from '../../Renderer/shims/ReactNativeTypes';
<ide> import ReactNativeViewViewConfigAndroid from './ReactNativeViewViewConfigAndroid';
<ide> import {Platform} from 'react-native';
<ide> | 33 |
Ruby | Ruby | add references schema statements | cfb24586b811177666cf0d085e3ab111195fb3ff | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def index_name_exists?(table_name, index_name, default)
<ide> indexes(table_name).detect { |i| i.name == index_name }
<ide> end
<ide>
<add> # Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
<add> # <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
<add> #
<add> # ====== Create a user_id column
<add> # add_reference(:products, :user)
<add> #
<add> # ====== Create a supplier_id and supplier_type columns
<add> # add_belongs_to(:products, :supplier, polymorphic: true)
<add> #
<add> # ====== Create a supplier_id, supplier_type columns and appropriate index
<add> # add_reference(:products, :supplier, polymorphic: true, index: true)
<add> #
<add> def add_reference(table_name, ref_name, options = {})
<add> polymorphic = options.delete(:polymorphic)
<add> index_options = options.delete(:index)
<add> add_column(table_name, "#{ref_name}_id", :integer, options)
<add> add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
<add> add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : nil) if index_options
<add> end
<add> alias :add_belongs_to :add_reference
<add>
<add> # Removes the reference(s). Also removes a +type+ column if one exists.
<add> # <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
<add> #
<add> # ====== Remove the reference
<add> # remove_reference(:products, :user, index: true)
<add> #
<add> # ====== Remove polymorphic reference
<add> # remove_reference(:products, :supplier, polymorphic: true)
<add> #
<add> def remove_reference(table_name, ref_name, options = {})
<add> polymorphic = options.delete(:polymorphic)
<add> remove_column(table_name, "#{ref_name}_id")
<add> remove_column(table_name, "#{ref_name}_type") if polymorphic
<add> end
<add> alias :remove_belongs_to :remove_reference
<add>
<ide> # Returns a string of <tt>CREATE TABLE</tt> SQL statement(s) for recreating the
<ide> # entire structure of the database.
<ide> def structure_dump
<ide><path>activerecord/test/cases/migration/helper.rb
<ide> def puts(text="")
<ide> module TestHelper
<ide> attr_reader :connection, :table_name
<ide>
<del> CONNECTION_METHODS = %w[add_column remove_column rename_column add_index change_column rename_table]
<add> CONNECTION_METHODS = %w[add_column remove_column rename_column add_index change_column rename_table column_exists? index_exists? add_reference add_belongs_to remove_reference remove_references remove_belongs_to]
<ide>
<ide> class TestModel < ActiveRecord::Base
<ide> self.table_name = :test_models
<ide><path>activerecord/test/cases/migration/references_statements_test.rb
<add>require "cases/migration/helper"
<add>
<add>module ActiveRecord
<add> class Migration
<add> class ReferencesStatementsTest < ActiveRecord::TestCase
<add> include ActiveRecord::Migration::TestHelper
<add>
<add> self.use_transactional_fixtures = false
<add>
<add> def setup
<add> super
<add> @table_name = :test_models
<add>
<add> add_column table_name, :supplier_id, :integer
<add> add_index table_name, :supplier_id
<add> end
<add>
<add> def test_creates_reference_id_column
<add> add_reference table_name, :user
<add> assert column_exists?(table_name, :user_id, :integer)
<add> end
<add>
<add> def test_does_not_create_reference_type_column
<add> add_reference table_name, :taggable
<add> refute column_exists?(table_name, :taggable_type, :string)
<add> end
<add>
<add> def test_creates_reference_type_column
<add> add_reference table_name, :taggable, polymorphic: true
<add> assert column_exists?(table_name, :taggable_type, :string)
<add> end
<add>
<add> def test_creates_reference_id_index
<add> add_reference table_name, :user, index: true
<add> assert index_exists?(table_name, :user_id)
<add> end
<add>
<add> def test_does_not_create_reference_id_index
<add> add_reference table_name, :user
<add> refute index_exists?(table_name, :user_id)
<add> end
<add>
<add> def test_creates_polymorphic_index
<add> add_reference table_name, :taggable, polymorphic: true, index: true
<add> assert index_exists?(table_name, [:taggable_id, :taggable_type])
<add> end
<add>
<add> def test_creates_reference_type_column_with_default
<add> add_reference table_name, :taggable, polymorphic: { default: 'Photo' }, index: true
<add> assert column_exists?(table_name, :taggable_type, :string, default: 'Photo')
<add> end
<add>
<add> def test_creates_named_index
<add> add_reference table_name, :tag, index: { name: 'index_taggings_on_tag_id' }
<add> assert index_exists?(table_name, :tag_id, name: 'index_taggings_on_tag_id')
<add> end
<add>
<add> def test_deletes_reference_id_column
<add> remove_reference table_name, :supplier
<add> refute column_exists?(table_name, :supplier_id, :integer)
<add> end
<add>
<add> def test_deletes_reference_id_index
<add> remove_reference table_name, :supplier
<add> refute index_exists?(table_name, :supplier_id)
<add> end
<add>
<add> def test_does_not_delete_reference_type_column
<add> with_polymorphic_column do
<add> remove_reference table_name, :supplier
<add>
<add> refute column_exists?(table_name, :supplier_id, :integer)
<add> assert column_exists?(table_name, :supplier_type, :string)
<add> end
<add> end
<add>
<add> def test_deletes_reference_type_column
<add> with_polymorphic_column do
<add> remove_reference table_name, :supplier, polymorphic: true
<add> refute column_exists?(table_name, :supplier_type, :string)
<add> end
<add> end
<add>
<add> def test_deletes_polymorphic_index
<add> with_polymorphic_column do
<add> remove_reference table_name, :supplier, polymorphic: true
<add> refute index_exists?(table_name, [:supplier_id, :supplier_type])
<add> end
<add> end
<add>
<add> def test_add_belongs_to_alias
<add> add_belongs_to table_name, :user
<add> assert column_exists?(table_name, :user_id, :integer)
<add> end
<add>
<add> def test_remove_belongs_to_alias
<add> remove_belongs_to table_name, :supplier
<add> refute column_exists?(table_name, :supplier_id, :integer)
<add> end
<add>
<add> private
<add>
<add> def with_polymorphic_column
<add> add_column table_name, :supplier_type, :string
<add> add_index table_name, [:supplier_id, :supplier_type]
<add>
<add> yield
<add> end
<add> end
<add> end
<add>end | 3 |
Ruby | Ruby | improve performance of grouping_any/grouping_all | 3e3d4d197943d6fc30976021a0f125ba8eab1dd1 | <ide><path>lib/arel/predications.rb
<ide> def desc
<ide> private
<ide>
<ide> def grouping_any method_id, others
<del> others = others.dup
<del> first = send method_id, others.shift
<del>
<del> Nodes::Grouping.new others.inject(first) { |memo,expr|
<del> Nodes::Or.new(memo, send(method_id, expr))
<add> nodes = others.map {|expr| send(method_id, expr)}
<add> Nodes::Grouping.new nodes.inject { |memo,node|
<add> Nodes::Or.new(memo, node)
<ide> }
<ide> end
<ide>
<ide> def grouping_all method_id, others
<del> others = others.dup
<del> first = send method_id, others.shift
<del>
<del> Nodes::Grouping.new others.inject(first) { |memo,expr|
<del> Nodes::And.new([memo, send(method_id, expr)])
<del> }
<add> Nodes::Grouping.new Nodes::And.new(others.map {|expr| send(method_id, expr)})
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | convert constraints, initialization, activations | 5ed913da1108b63c69d48d30b395ae35e576dc9f | <ide><path>keras/activations.py
<ide> from __future__ import absolute_import
<del>import theano.tensor as T
<add>from . import backend as K
<ide>
<ide>
<ide> def softmax(x):
<del> return T.nnet.softmax(x.reshape((-1, x.shape[-1]))).reshape(x.shape)
<del>
<del>
<del>def time_distributed_softmax(x):
<del> return softmax(x)
<add> return K.softmax(x)
<ide>
<ide>
<ide> def softplus(x):
<del> return T.nnet.softplus(x)
<add> return K.softplus(x)
<ide>
<ide>
<del>def relu(x):
<del> return T.nnet.relu(x)
<add>def relu(x, alpha=0., max_value=None):
<add> return K.relu(x, alpha=alpha, max_value=max_value)
<ide>
<ide>
<ide> def tanh(x):
<del> return T.tanh(x)
<add> return K.tanh(x)
<ide>
<ide>
<ide> def sigmoid(x):
<del> return T.nnet.sigmoid(x)
<add> return K.sigmoid(x)
<ide>
<ide>
<ide> def hard_sigmoid(x):
<del> return T.nnet.hard_sigmoid(x)
<add> return K.hard_sigmoid(x)
<ide>
<ide>
<ide> def linear(x):
<ide><path>keras/callbacks.py
<ide> from __future__ import print_function
<ide>
<ide> import numpy as np
<del>import time, json, warnings
<add>import time
<add>import json
<add>import warnings
<ide>
<ide> from collections import deque
<ide> from .utils.generic_utils import Progbar
<ide><path>keras/constraints.py
<ide> from __future__ import absolute_import
<del>import theano
<del>import theano.tensor as T
<del>import numpy as np
<add>from . import backend as K
<ide>
<ide>
<ide> class Constraint(object):
<ide> def __init__(self, m=2):
<ide> self.m = m
<ide>
<ide> def __call__(self, p):
<del> norms = T.sqrt(T.sum(T.sqr(p), axis=0))
<del> desired = T.clip(norms, 0, self.m)
<add> norms = K.sqrt(K.sum(K.sqr(p), axis=0))
<add> desired = K.clip(norms, 0, self.m)
<ide> p = p * (desired / (1e-7 + norms))
<ide> return p
<ide>
<ide> def get_config(self):
<ide>
<ide> class NonNeg(Constraint):
<ide> def __call__(self, p):
<del> p = theano.shared(p)
<del> p *= T.ge(p, 0.)
<add> p = K.variable(p)
<add> p *= (p >= 0.)
<ide> return p
<ide>
<ide>
<ide> class UnitNorm(Constraint):
<ide> def __call__(self, p):
<del> return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True))
<add> return p / K.sqrt(K.sum(p**2, axis=-1, keepdims=True))
<ide>
<ide> identity = Constraint
<ide> maxnorm = MaxNorm
<ide><path>keras/initializations.py
<ide> from __future__ import absolute_import
<del>import theano
<del>import theano.tensor as T
<ide> import numpy as np
<del>
<del>from .utils.theano_utils import sharedX, shared_zeros, shared_ones
<add>from . import backend as K
<ide>
<ide>
<ide> def get_fans(shape):
<ide> def get_fans(shape):
<ide>
<ide>
<ide> def uniform(shape, scale=0.05):
<del> return sharedX(np.random.uniform(low=-scale, high=scale, size=shape))
<add> return K.variable(np.random.uniform(low=-scale, high=scale, size=shape))
<ide>
<ide>
<ide> def normal(shape, scale=0.05):
<del> return sharedX(np.random.randn(*shape) * scale)
<add> return K.variable(np.random.randn(*shape) * scale)
<ide>
<ide>
<ide> def lecun_uniform(shape):
<ide> def orthogonal(shape, scale=1.1):
<ide> # pick the one with the correct shape
<ide> q = u if u.shape == flat_shape else v
<ide> q = q.reshape(shape)
<del> return sharedX(scale * q[:shape[0], :shape[1]])
<add> return K.variable(scale * q[:shape[0], :shape[1]])
<ide>
<ide>
<ide> def identity(shape, scale=1):
<ide> if len(shape) != 2 or shape[0] != shape[1]:
<ide> raise Exception("Identity matrix initialization can only be used for 2D square matrices")
<ide> else:
<del> return sharedX(scale * np.identity(shape[0]))
<add> return K.variable(scale * np.identity(shape[0]))
<ide>
<ide>
<ide> def zero(shape):
<del> return shared_zeros(shape)
<add> return K.zeros(shape)
<ide>
<ide>
<ide> def one(shape):
<del> return shared_ones(shape)
<add> return K.ones(shape)
<ide>
<ide>
<ide> from .utils.generic_utils import get_from_module | 4 |
Javascript | Javascript | make sure jshint checks all js files | 68f32226db03654edf4af5a2a572458c61dc6821 | <ide><path>Gruntfile.js
<ide> module.exports = function(grunt) {
<ide> },
<ide> jshint: {
<ide> src: {
<del> src: ['src/js/*.js', 'Gruntfile.js', 'test/unit/*.js'],
<add> src: ['src/js/**/*.js', 'Gruntfile.js', 'test/unit/**/*.js'],
<ide> options: {
<ide> jshintrc: '.jshintrc'
<ide> }
<ide><path>src/js/control-bar/playback-rate-menu-button.js
<ide> vjs.PlaybackRateMenuButton.prototype.createMenu = function(){
<ide> menu.addChild(
<ide> new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'})
<ide> );
<del> };
<add> }
<ide> }
<ide>
<ide> return menu;
<ide> vjs.PlaybackRateMenuButton.prototype.onClick = function(){
<ide> newRate = rates[i];
<ide> break;
<ide> }
<del> };
<add> }
<ide> this.player().playbackRate(newRate);
<ide> };
<ide>
<ide><path>src/js/control-bar/progress-control.js
<ide> vjs.LoadProgressBar.prototype.update = function(){
<ide> part = children[i];
<ide>
<ide> if (!part) {
<del> part = this.el_.appendChild(vjs.createEl())
<del> };
<add> part = this.el_.appendChild(vjs.createEl());
<add> }
<ide>
<ide> // set the percent based on the width of the progress bar (bufferedEnd)
<ide> part.style.left = percentify(start, bufferedEnd);
<ide> part.style.width = percentify(end - start, bufferedEnd);
<del> };
<add> }
<ide>
<ide> // remove unused buffered range elements
<ide> for (i = children.length; i > buffered.length; i--) {
<ide><path>src/js/media/flash.js
<ide> vjs.Flash.prototype.enterFullScreen = function(){
<ide> function createSetter(attr){
<ide> var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
<ide> api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); };
<del> };
<add> }
<ide> function createGetter(attr) {
<ide> api[attr] = function(){ return this.el_.vjs_getProperty(attr); };
<del> };
<add> }
<ide>
<ide> // Create getter and setters for all read/write attributes
<ide> for (i = 0; i < readWrite.length; i++) {
<ide><path>src/js/media/media.js
<ide> vjs.MediaTechController.withSourceHandlers = function(Tech){
<ide> * @returns {null} Null if no source handler is found
<ide> */
<ide> Tech.selectSourceHandler = function(source){
<del> var handlers = Tech.sourceHandlers || [];
<add> var handlers = Tech.sourceHandlers || [],
<add> can;
<ide>
<ide> for (var i = 0; i < handlers.length; i++) {
<ide> can = handlers[i].canHandleSource(source); | 5 |
Go | Go | fix leak of handletableevents | 6d768ef73cac58c4d6dae59cbeb7ca9558722f64 | <ide><path>libnetwork/agent.go
<ide> func (n *network) cancelDriverWatches() {
<ide> }
<ide> }
<ide>
<del>func (c *controller) handleTableEvents(ch chan events.Event, fn func(events.Event)) {
<add>func (c *controller) handleTableEvents(ch *events.Channel, fn func(events.Event)) {
<ide> for {
<ide> select {
<del> case ev, ok := <-ch:
<del> if !ok {
<del> return
<del> }
<del>
<add> case ev := <-ch.C:
<ide> fn(ev)
<add> case <-ch.Done():
<add> return
<ide> }
<ide> }
<ide> }
<ide><path>libnetwork/networkdb/networkdb_test.go
<ide> func TestNetworkDBWatch(t *testing.T) {
<ide> err = dbs[0].CreateEntry("test_table", "network1", "test_key", []byte("test_value"))
<ide> assert.NoError(t, err)
<ide>
<del> testWatch(t, ch, CreateEvent{}, "test_table", "network1", "test_key", "test_value")
<add> testWatch(t, ch.C, CreateEvent{}, "test_table", "network1", "test_key", "test_value")
<ide>
<ide> err = dbs[0].UpdateEntry("test_table", "network1", "test_key", []byte("test_updated_value"))
<ide> assert.NoError(t, err)
<ide>
<del> testWatch(t, ch, UpdateEvent{}, "test_table", "network1", "test_key", "test_updated_value")
<add> testWatch(t, ch.C, UpdateEvent{}, "test_table", "network1", "test_key", "test_updated_value")
<ide>
<ide> err = dbs[0].DeleteEntry("test_table", "network1", "test_key")
<ide> assert.NoError(t, err)
<ide>
<del> testWatch(t, ch, DeleteEvent{}, "test_table", "network1", "test_key", "")
<add> testWatch(t, ch.C, DeleteEvent{}, "test_table", "network1", "test_key", "")
<ide>
<ide> cancel()
<ide> closeNetworkDBInstances(dbs)
<ide><path>libnetwork/networkdb/watch.go
<ide> type DeleteEvent event
<ide> // filter is an empty string it acts as a wildcard for that
<ide> // field. Watch returns a channel of events, where the events will be
<ide> // sent.
<del>func (nDB *NetworkDB) Watch(tname, nid, key string) (chan events.Event, func()) {
<add>func (nDB *NetworkDB) Watch(tname, nid, key string) (*events.Channel, func()) {
<ide> var matcher events.Matcher
<ide>
<ide> if tname != "" || nid != "" || key != "" {
<ide> func (nDB *NetworkDB) Watch(tname, nid, key string) (chan events.Event, func())
<ide> }
<ide>
<ide> nDB.broadcaster.Add(sink)
<del> return ch.C, func() {
<add> return ch, func() {
<ide> nDB.broadcaster.Remove(sink)
<ide> ch.Close()
<ide> sink.Close() | 3 |
Python | Python | fix a macos build failure when `npy_blas_order=""` | 5bec8df317ffbda8f97486195b758f2261495749 | <ide><path>numpy/distutils/system_info.py
<ide> def _parse_env_order(base_order, env):
<ide> allow_order = base_order.copy()
<ide>
<ide> for order in orders:
<add> if not order:
<add> continue
<add>
<ide> if order not in base_order:
<ide> unknown_order.append(order)
<ide> continue
<ide> def _parse_env_order(base_order, env):
<ide> allow_order = []
<ide>
<ide> for order in orders:
<add> if not order:
<add> continue
<add>
<ide> if order not in base_order:
<ide> unknown_order.append(order)
<ide> continue | 1 |
Python | Python | replace double quotes with single quotes | 7c882a457b734cd0a38d41c7e930e375a6ce6e4c | <ide><path>tests/test_helpers.py
<ide> def test_safe_join_exceptions(self):
<ide>
<ide> class TestHelpers(object):
<ide>
<del> @pytest.mark.parametrize("debug, expected_flag, expected_default_flag", [
<add> @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [
<ide> ('', None, True),
<ide> ('0', False, False),
<ide> ('False', False, False), | 1 |
Javascript | Javascript | fix incorrect parsing of define functions | 0c4e157196740d1c47f6b1affc4e55a9835b71f1 | <ide><path>lib/dependencies/AMDDefineDependency.js
<ide> const DEFINITIONS = {
<ide> lf: {
<ide> definition: "var XXX, XXXmodule;",
<ide> content:
<del> "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))",
<add> "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))",
<ide> requests: [RuntimeGlobals.require, RuntimeGlobals.module]
<ide> },
<ide> lo: {
<ide><path>lib/dependencies/AMDDefineDependencyParserPlugin.js
<ide> class AMDDefineDependencyParserPlugin {
<ide> }
<ide> parser.scope.inTry = inTry;
<ide> if (fn.body.type === "BlockStatement") {
<add> parser.detectMode(fn.body.body);
<add> const prev = parser.prevStatement;
<add> parser.preWalkStatement(fn.body);
<add> parser.prevStatement = prev;
<ide> parser.walkStatement(fn.body);
<ide> } else {
<ide> parser.walkExpression(fn.body);
<ide> class AMDDefineDependencyParserPlugin {
<ide> }
<ide> parser.scope.inTry = inTry;
<ide> if (fn.callee.object.body.type === "BlockStatement") {
<add> parser.detectMode(fn.callee.object.body.body);
<add> const prev = parser.prevStatement;
<add> parser.preWalkStatement(fn.callee.object.body);
<add> parser.prevStatement = prev;
<ide> parser.walkStatement(fn.callee.object.body);
<ide> } else {
<ide> parser.walkExpression(fn.callee.object.body);
<ide><path>test/cases/parsing/declared-api/index.js
<add>it("should not replace declared variables", () => {
<add> expect(require("./module")).toBe(42 + 42);
<add>});
<ide><path>test/cases/parsing/declared-api/module.js
<add>define("local", () => {
<add> var __webpack_modules__ = 42;
<add>
<add> return __webpack_modules__;
<add>});
<add>
<add>define(["local"], l => {
<add> var __webpack_modules__ = 42 + l;
<add>
<add> return __webpack_modules__;
<add>}); | 4 |
Java | Java | add originalmessage to errormessage | e677342628847104265420a2cb5d3e35b7891caa | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageHeaders;
<ide>
<ide> /**
<ide> * A {@link GenericMessage} with a {@link Throwable} payload.
<add> * The payload is typically a {@link org.springframework.messaging.MessagingException}
<add> * with the message at the point of failure in its {@code failedMessage} property.
<add> * An optional {@code originalMessage} may be provided, which represents the message
<add> * that existed at the point in the stack where the error message is created.
<add> * <p>Consider some code that starts with a message, invokes some process that performs
<add> * transformation on that message and then fails for some reason, throwing the exception.
<add> * The exception is caught and an error message produced that contains both the original
<add> * message, and the transformed message that failed.
<ide> *
<ide> * @author Mark Fisher
<ide> * @author Oleg Zhurakousky
<add> * @author Gary Russell
<ide> * @since 4.0
<ide> * @see MessageBuilder
<ide> */
<ide> public class ErrorMessage extends GenericMessage<Throwable> {
<ide>
<ide> private static final long serialVersionUID = -5470210965279837728L;
<ide>
<add> private final Message<?> originalMessage;
<ide>
<ide> /**
<ide> * Create a new message with the given payload.
<ide> * @param payload the message payload (never {@code null})
<ide> */
<ide> public ErrorMessage(Throwable payload) {
<ide> super(payload);
<add> this.originalMessage = null;
<ide> }
<ide>
<ide> /**
<ide> public ErrorMessage(Throwable payload) {
<ide> */
<ide> public ErrorMessage(Throwable payload, Map<String, Object> headers) {
<ide> super(payload, headers);
<add> this.originalMessage = null;
<ide> }
<ide>
<ide> /**
<ide> public ErrorMessage(Throwable payload, Map<String, Object> headers) {
<ide> */
<ide> public ErrorMessage(Throwable payload, MessageHeaders headers) {
<ide> super(payload, headers);
<add> this.originalMessage = null;
<add> }
<add>
<add> /**
<add> * Create a new message with the given payload and original message.
<add> * @param payload the message payload (never {@code null})
<add> * @param originalMessage the original message (if present) at the point in the stack
<add> * where the ErrorMessage was created
<add> * @since 5.0
<add> */
<add> public ErrorMessage(Throwable payload, Message<?> originalMessage) {
<add> super(payload);
<add> this.originalMessage = originalMessage;
<add> }
<add>
<add> /**
<add> * Create a new message with the given payload, headers and original message.
<add> * The content of the given header map is copied.
<add> * @param payload the message payload (never {@code null})
<add> * @param headers message headers to use for initialization
<add> * @param originalMessage the original message (if present) at the point in the stack
<add> * where the ErrorMessage was created
<add> * @since 5.0
<add> */
<add> public ErrorMessage(Throwable payload, Map<String, Object> headers, Message<?> originalMessage) {
<add> super(payload, headers);
<add> this.originalMessage = originalMessage;
<add> }
<add>
<add> /**
<add> * Create a new message with the payload, {@link MessageHeaders} and original message.
<add> * <p><strong>Note:</strong> the given {@code MessageHeaders} instance
<add> * is used directly in the new message, i.e. it is not copied.
<add> * @param payload the message payload (never {@code null})
<add> * @param headers message headers
<add> * @param originalMessage the original message (if present) at the point in the stack
<add> * where the ErrorMessage was created
<add> * @since 5.0
<add> */
<add> public ErrorMessage(Throwable payload, MessageHeaders headers, Message<?> originalMessage) {
<add> super(payload, headers);
<add> this.originalMessage = originalMessage;
<add> }
<add>
<add> /**
<add> * The original message (if present) at the point in the stack where the
<add> * ErrorMessage was created.
<add> * @return the originalMessage
<add> */
<add> public Message<?> getOriginalMessage() {
<add> return originalMessage;
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> if (this.originalMessage == null) {
<add> return super.toString();
<add> }
<add> else {
<add> StringBuilder sb = new StringBuilder(super.toString());
<add> if (sb.length() > 0) {
<add> sb.setLength(sb.length() - 1);
<add> }
<add> sb.append(", originalMessage=").append(this.originalMessage.toString()).append("]");
<add> return sb.toString();
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java
<add>/*
<add> * Copyright 2017 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support;
<add>
<add>import org.junit.Test;
<add>
<add>import static org.hamcrest.CoreMatchers.*;
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> *
<add> * @author Gary Russell
<add> * @since 5.0
<add> */
<add>public class ErrorMessageTests {
<add>
<add> @Test
<add> public void testToString() {
<add> ErrorMessage em = new ErrorMessage(new RuntimeException("foo"));
<add> String emString = em.toString();
<add> assertThat(emString, not(containsString("originalMessage")));
<add> em = new ErrorMessage(new RuntimeException("foo"), new GenericMessage<>("bar"));
<add> emString = em.toString();
<add> assertThat(emString, containsString("}, originalMessage="));
<add> }
<add>
<add>} | 2 |
Javascript | Javascript | fix typo in timers insert function comment | 2fa86b818bb85d0aade89d4dcd4765e439ce7a01 | <ide><path>lib/internal/timers.js
<ide> function insertGuarded(item, refed, start) {
<ide> }
<ide>
<ide> function insert(item, msecs, start = getLibuvNow()) {
<del> // Truncate so that accuracy of sub-milisecond timers is not assumed.
<add> // Truncate so that accuracy of sub-millisecond timers is not assumed.
<ide> msecs = MathTrunc(msecs);
<ide> item._idleStart = start;
<ide> | 1 |
Ruby | Ruby | add default exceptions affected by suppress | 28492204ee59a5aca2f3bc7b161d45724552686d | <ide><path>activesupport/lib/active_support/core_ext/kernel/reporting.rb
<ide> def with_warnings(flag)
<ide> #
<ide> # puts 'This code gets executed and nothing related to ZeroDivisionError was seen'
<ide> def suppress(*exception_classes)
<add> exception_classes = StandardError if exception_classes.empty?
<ide> yield
<ide> rescue *exception_classes
<ide> end
<ide><path>activesupport/test/core_ext/kernel_test.rb
<ide> def test_reraise
<ide> end
<ide> end
<ide>
<add> def test_suppress_with_defaults
<add> suppress { raise RuntimeError }
<add> suppress { raise ArgumentError }
<add>
<add> assert_raise(LoadError) do
<add> suppress { raise LoadError }
<add> end
<add> end
<add>
<ide> def test_suppression
<ide> suppress(ArgumentError) { raise ArgumentError }
<ide> suppress(LoadError) { raise LoadError } | 2 |
Ruby | Ruby | fix references to requesthelpers methods in docs | 1d5f9c3e1791f54cc96baafdbcb086e970f7d601 | <ide><path>actionpack/lib/action_dispatch/http/response.rb
<ide> module ActionDispatch # :nodoc:
<ide> # Nevertheless, integration tests may want to inspect controller responses in
<ide> # more detail, and that's when \Response can be useful for application
<ide> # developers. Integration test methods such as
<del> # ActionDispatch::Integration::Session#get and
<del> # ActionDispatch::Integration::Session#post return objects of type
<del> # TestResponse (which are of course also of type \Response).
<add> # Integration::RequestHelpers#get and Integration::RequestHelpers#post return
<add> # objects of type TestResponse (which are of course also of type \Response).
<ide> #
<ide> # For example, the following demo integration test prints the body of the
<ide> # controller response to the console:
<ide><path>actionpack/lib/action_dispatch/testing/test_response.rb
<ide> require "action_dispatch/testing/request_encoder"
<ide>
<ide> module ActionDispatch
<del> # Integration test methods such as ActionDispatch::Integration::Session#get
<del> # and ActionDispatch::Integration::Session#post return objects of class
<add> # Integration test methods such as Integration::RequestHelpers#get
<add> # and Integration::RequestHelpers#post return objects of class
<ide> # TestResponse, which represent the HTTP response results of the requested
<ide> # controller actions.
<ide> # | 2 |
Python | Python | use defaults for adding not null on sqlite | e802c97581594e3a37e6497443b105ecb9920a55 | <ide><path>django/db/backends/sqlite3/base.py
<ide> def quote_parameter(self, value):
<ide> if isinstance(value, six.integer_types):
<ide> return str(value)
<ide> elif isinstance(value, six.string_types):
<del> return six.text_type(value)
<add> return '"%s"' % six.text_type(value)
<ide> elif isinstance(value, type(True)):
<ide> return str(int(value))
<ide> elif value is None:
<ide><path>django/db/backends/sqlite3/schema.py
<ide> def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=
<ide> # Add in any created fields
<ide> for field in create_fields:
<ide> body[field.name] = field
<add> # If there's a default, insert it into the copy map
<add> if field.get_default():
<add> mapping[field.column] = self.connection.ops.quote_parameter(
<add> field.get_default()
<add> )
<ide> # Add in any altered fields
<ide> for (old_field, new_field) in alter_fields:
<ide> del body[old_field.name]
<ide><path>tests/schema/tests.py
<ide> def test_add_field(self):
<ide> # Ensure there's no age field
<ide> columns = self.column_classes(Author)
<ide> self.assertNotIn("age", columns)
<del> # Alter the name field to a TextField
<add> # Add the new field
<ide> new_field = IntegerField(null=True)
<ide> new_field.set_attributes_from_name("age")
<ide> with connection.schema_editor() as editor:
<ide> def test_add_field(self):
<ide> self.assertEqual(columns['age'][0], "IntegerField")
<ide> self.assertEqual(columns['age'][1][6], True)
<ide>
<add> def test_add_field_temp_default(self):
<add> """
<add> Tests adding fields to models with a temporary default
<add> """
<add> # Create the table
<add> with connection.schema_editor() as editor:
<add> editor.create_model(Author)
<add> # Ensure there's no age field
<add> columns = self.column_classes(Author)
<add> self.assertNotIn("age", columns)
<add> # Add some rows of data
<add> Author.objects.create(name="Andrew", height=30)
<add> Author.objects.create(name="Andrea")
<add> # Add a not-null field
<add> new_field = CharField(max_length=30, default="Godwin")
<add> new_field.set_attributes_from_name("surname")
<add> with connection.schema_editor() as editor:
<add> editor.add_field(
<add> Author,
<add> new_field,
<add> )
<add> # Ensure the field is right afterwards
<add> columns = self.column_classes(Author)
<add> self.assertEqual(columns['surname'][0], "CharField")
<add> self.assertEqual(columns['surname'][1][6], False)
<add>
<ide> def test_alter(self):
<ide> """
<ide> Tests simple altering of fields | 3 |
Text | Text | add v4.3.0-beta.1 to changelog | 1e56cc828415bd0bfcccb35f431daa12467129aa | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.3.0-beta.1 (February 7, 2022)
<add>
<add>No public API changes or bugfixes.
<add>
<ide> ### v4.2.0 (February 7, 2022)
<ide>
<ide> - [#19878](https://github.com/emberjs/ember.js/pull/19878) [BUGFIX] Allow class-based helpers to work in strict-mode. | 1 |
Javascript | Javascript | improve code (review) | d2461dab06194f660b106e01dd5c8350d6366f82 | <ide><path>lib/optimize/UglifyJsPlugin.js
<ide> class UglifyJsPlugin {
<ide> case "boolean":
<ide> var b = condition[key];
<ide> condition[key] = () => b;
<del> case "function": // eslint-disable-line no-fallthrough
<add> break;
<add> case "function":
<ide> break;
<ide> case "string":
<ide> if(condition[key] === "all") {
<ide> condition[key] = () => true;
<ide> break;
<ide> }
<del> condition[key] = new RegExp(condition[key]);
<del> default: // eslint-disable-line no-fallthrough
<del> var regex = condition[key];
<add> var regex = new RegExp(condition[key]);
<add> condition[key] = (astNode, comment) => regex.test(comment.value);
<add> break;
<add> default:
<add> regex = condition[key];
<ide> condition[key] = (astNode, comment) => regex.test(comment.value);
<ide> }
<ide> });
<ide> class UglifyJsPlugin {
<ide> ast.print(stream);
<ide> if(map) map = map + "";
<ide> const stringifiedStream = stream + "";
<del> asset.__UglifyJsPlugin = compilation.assets[file] = (map ?
<add> let outputSource = (map ?
<ide> new SourceMapSource(stringifiedStream, file, JSON.parse(map), input, inputSourceMap) :
<ide> new RawSource(stringifiedStream));
<ide> if(extractedComments.length > 0) {
<del> let commentsFile = options.extractComments.file || file + ".LICENSE";
<add> let commentsFile = options.extractComments.filename || file + ".LICENSE";
<ide> if(typeof commentsFile === "function") {
<ide> commentsFile = commentsFile(file);
<ide> }
<ide> class UglifyJsPlugin {
<ide> banner = banner(commentsFile);
<ide> }
<ide> if(banner) {
<del> asset.__UglifyJsPlugin = compilation.assets[file] = new ConcatSource(
<del> "/*! " + banner + " */\n", compilation.assets[file]
<add> outputSource = new ConcatSource(
<add> "/*! " + banner + " */\n", outputSource
<ide> );
<ide> }
<ide> }
<ide> }
<add> asset.__UglifyJsPlugin = compilation.assets[file] = outputSource;
<ide> if(warnings.length > 0) {
<ide> compilation.warnings.push(new Error(file + " from UglifyJs\n" + warnings.join("\n")));
<ide> }
<ide><path>test/UglifyJsPlugin.test.js
<ide> describe("UglifyJsPlugin", function() {
<ide> comments: false,
<ide> extractComments: {
<ide> condition: 'should be extracted',
<del> file: function(file) {
<add> filename: function(file) {
<ide> return file.replace(/(\.\w+)$/, '.license$1');
<ide> },
<ide> banner: function(licenseFile) {
<ide> describe("UglifyJsPlugin", function() {
<ide> comments: "all",
<ide> extractComments: {
<ide> condition: /.*/,
<del> file: "extracted-comments.js"
<add> filename: "extracted-comments.js"
<ide> }
<ide> });
<ide> plugin.apply(compilerEnv); | 2 |
Text | Text | remove reference to react-router-native | c535c263c6173d5eda19071b8e4c3093f59b7a07 | <ide><path>docs/Navigation.md
<ide> Check out the [`NavigatorIOS` reference docs](docs/navigatorios.html) to learn m
<ide>
<ide> Since early 2016, React Native has shipped with an experimental re-implementation of the original `Navigator` component called `CardStack`. The major benefit it had over `Navigator` is the smooth native-thread animations provided by the Animated library.
<ide>
<del>Because `NavigationExperimental` only included view components, it required a lot of boilerplate to use by itself. Several libraries sprung up around it, making it easier to use. Libraries such as `react-native-router-flux`, `ex-navigation`, and `react-router-native` all wrapped NavigationExperimental views in an easier-to-use API. Authors of many of these libraries now support React Navigation.
<add>Because `NavigationExperimental` only included view components, it required a lot of boilerplate to use by itself. Several libraries sprung up around it, making it easier to use. Libraries such as `react-native-router-flux` and `ex-navigation` wrapped NavigationExperimental views in an easier-to-use API. Authors of many of these libraries now support React Navigation.
<ide>
<ide> The `CardStack` and other NavigationExperimental views live on as a part of the React Navigation project. The new library aims to be easy to use, while continuing to enable the smooth and customizable animations that NavigationExperimental pioneered.
<ide> | 1 |
Text | Text | update changelog entry for session#fetch | 96a6703ed9c0e64a01ce729dc8c2c6c19bea7903 | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> * Add `session#fetch` method
<ide>
<del> fetch behaves similarly to [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch),
<del> with the exception that the returned value is always saved into the session.
<del>
<add> fetch behaves like [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch).
<ide> It returns a value from the hash for the given key.
<ide> If the key can’t be found, there are several options:
<ide> | 1 |
Javascript | Javascript | use english slugs for all challenges | 412938890a198ef1e4d944514fa11a30a3e58d2a | <ide><path>api-server/server/utils/get-curriculum.js
<ide> import { getChallengesForLang } from '../../../curriculum/getChallenges';
<ide>
<ide> let curriculum;
<ide> export async function getCurriculum() {
<del> curriculum = curriculum
<del> ? curriculum
<del> : getChallengesForLang(process.env.CURRICULUM_LOCALE);
<add> // NOTE: this is always 'english' because we are only interested in the slugs
<add> // and those should not change between the languages.
<add> curriculum = curriculum ? curriculum : getChallengesForLang('english');
<ide> return curriculum;
<ide> }
<ide> | 1 |
Javascript | Javascript | add an example of another locale | f152a9e67170274f58a0e65192eeedc1b8b36274 | <ide><path>src/locale/ru-RU.js
<add>import "locale";
<add>
<add>var d3_locale_ruRU = d3.locale({
<add> decimal: ",",
<add> thousands: " ",
<add> grouping: [3, 3],
<add> currency: "руб. ",
<add> dateTime: "%A, %e %B %Y г. %X",
<add> date: "%d.%m.%Y",
<add> time: "%H:%M:%S",
<add> periods: ["AM", "PM"],
<add> days: ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"],
<add> shortDays: ["вс", "пн", "вт", "ср", "чт", "пт", "сб"],
<add> months: ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"],
<add> shortMonths: ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"]
<add>}); | 1 |
Text | Text | add link and fix typos. | a0aa7ddbe501ec15a77c53816f53183443a5a493 | <ide><path>guide/english/python/for-loop-statements/index.md
<ide> title: For Loop Statements
<ide>
<ide> Python utilizes a for loop to iterate over a list of elements. Unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
<ide>
<del>For loops iterate over collection based data structures like lists, tuples, and dictionaries.
<add>For loops iterate over collection based data structures like [lists](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/english/python/lists), tuples, and dictionaries.
<ide>
<ide> The basic syntax is:
<ide>
<ide> for i in range(10):
<ide> print(i)
<ide> ```
<ide> Rather than being a function, range is actually an immutable sequence type.
<del>The output will contain results from lower bound i.e 0 to the upper bound i.e 10 but excluding 10.By default the lower bound or the starting index is set to zero.
<add>The output will contain results from lower bound i.e 0 to the upper bound i.e 10 but excluding 10. By default the lower bound or the starting index is set to zero.
<ide>
<ide> Output:
<ide>
<ide> for index, item in enumerate(shopping_basket):
<ide> print("Item", index, "is a", item)
<ide> ```
<ide> **for/else statements**
<del>Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of `break` statement so that we can break out of the loop on a satsfied condition.If we do not break out then the else part will be executed.
<add>Python permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of `break` statement so that we can break out of the loop on a satsfied condition. If we do not break out then the else part will be executed.
<ide>
<ide> ```python
<ide> week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday'] | 1 |
Text | Text | fix links in releasing guide | e5b6f36831ae003b13fcc042509915e7b071acc7 | <ide><path>dev/README_RELEASE_AIRFLOW.md
<ide> previously released RC candidates in "${AIRFLOW_SOURCES}/dist":
<ide> (both airflow and latest provider packages).
<ide>
<ide> ```shell script
<add> git checkout ${VERSION}
<ide> git push origin ${VERSION}
<ide> ```
<ide>
<ide> Dear Airflow community,
<ide>
<ide> I'm happy to announce that Airflow ${VERSION} was just released.
<ide>
<del>The released sources and packages can be downloaded via https://airflow.apache.org/installation/installing-from-sources.html
<add>The released sources and packages can be downloaded via https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-sources.html
<ide>
<del>Other installation methods are described in https://airflow.apache.org/installation/
<add>Other installation methods are described in https://airflow.apache.org/docs/apache-airflow/stable/installation/
<ide>
<ide> The documentation is available on:
<ide> https://airflow.apache.org/
<ide> https://airflow.apache.org/docs/apache-airflow/${VERSION}/
<ide>
<ide> Find the CHANGELOG here for more details:
<ide>
<del>https://airflow.apache.org/changelog.html#airflow-1-10-2-2019-01-19
<add>https://airflow.apache.org/docs/apache-airflow/${VERSION}/changelog.html
<ide>
<ide> Cheers,
<ide> <your name> | 1 |
Ruby | Ruby | avoid directories with @ | b6447120aed42a58a70aad54e7c997ae7f22e685 | <ide><path>Library/Homebrew/mktemp.rb
<ide> def to_s
<ide> end
<ide>
<ide> def run
<del> @tmpdir = Pathname.new(Dir.mktmpdir("#{@prefix}-", HOMEBREW_TEMP))
<add> @tmpdir = Pathname.new(Dir.mktmpdir("#{@prefix.tr "@", "-"}-", HOMEBREW_TEMP))
<ide>
<ide> # Make sure files inside the temporary directory have the same group as the
<ide> # brew instance. | 1 |
PHP | PHP | remove a test class & use a mock | 1e461b7403a3d79841c169eb8e91534c2c8dd0b4 | <ide><path>lib/Cake/Test/TestCase/View/Helper/HtmlHelperTest.php
<ide> define('FULL_BASE_URL', 'http://cakephp.org');
<ide> }
<ide>
<del>/**
<del> * TheHtmlTestController class
<del> *
<del> * @package Cake.Test.Case.View.Helper
<del> */
<del>class TheHtmlTestController extends Controller {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TheTest'
<del> */
<del> public $name = 'TheTest';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var mixed null
<del> */
<del> public $uses = null;
<del>}
<del>
<ide> class TestHtmlHelper extends HtmlHelper {
<ide>
<ide> /**
<ide> class HtmlHelperTest extends TestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<del> $this->View = $this->getMock('Cake\View\View', array('append'), array(new TheHtmlTestController()));
<add> $controller = $this->getMock('Cake\Controller\Controller');
<add> $this->View = $this->getMock('Cake\View\View', array('append'), array($controller));
<ide> $this->Html = new TestHtmlHelper($this->View);
<ide> $this->Html->request = new Request(null, false);
<ide> $this->Html->request->webroot = ''; | 1 |
Text | Text | fix markdown link in blog post | 948b381a1465653a72c466f4fdfad7014fbcb539 | <ide><path>blog/2016-07-06-toward-better-documentation.md
<ide> We have a new [guide to Navigation](/react-native/docs/navigator-comparison.html
<ide>
<ide> We also have a new [guide to handling touches](/react-native/docs/handling-touches.html) that explains some of the basics of making button-like interfaces, and a brief summary of the different ways to handle touch events.
<ide>
<del>Another area we worked on is Flexbox. This includes tutorials on how to [handle layout with Flexbox](/react-native/docs/flexbox.html) and how to control [the size of components](/react-native/docs/height-and-width.html). It also includes an unsexy but hopefully-useful (list of all the props that control layout in React Native)[/react-native/docs/layout-props.html].
<add>Another area we worked on is Flexbox. This includes tutorials on how to [handle layout with Flexbox](/react-native/docs/flexbox.html) and how to control [the size of components](/react-native/docs/height-and-width.html). It also includes an unsexy but hopefully-useful [list of all the props that control layout in React Native](/react-native/docs/layout-props.html).
<ide>
<ide> ## Getting Started
<ide> | 1 |
Mixed | Ruby | add a hidden field on the collection_radio_buttons | 491013e06d0ad4a296cc23be6c4a48bb0a98106f | <ide><path>actionview/CHANGELOG.md
<add>* Add a `hidden_field` on the `collection_radio_buttons` to avoid raising a error
<add> when the only input on the form is the `collection_radio_buttons`.
<add>
<add> *Mauro George*
<add>
<ide> * `url_for` does not modify its arguments when generating polymorphic URLs.
<ide>
<ide> *Bernerd Schaefer*
<ide><path>actionview/lib/action_view/helpers/form_options_helper.rb
<ide> def time_zone_options_for_select(selected = nil, priority_zones = nil, model = :
<ide> # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
<ide> # b.label(:"data-value" => b.value) { b.radio_button + b.text }
<ide> # end
<add> #
<add> # ==== Gotcha
<add> #
<add> # The HTML specification says when nothing is select on a collection of radio buttons
<add> # web browsers do not send any value to server.
<add> # Unfortunately this introduces a gotcha:
<add> # if a +User+ model has a +category_id+ field, and in the form none category is selected no +category_id+ parameter is sent. So,
<add> # any strong parameters idiom like
<add> #
<add> # params.require(:user).permit(...)
<add> #
<add> # will raise a error since no +{user: ...}+ will be present.
<add> #
<add> # To prevent this the helper generates an auxiliary hidden field before
<add> # every collection of radio buttons. The hidden field has the same name as collection radio button and blank value.
<add> #
<add> # In case if you don't want the helper to generate this hidden field you can specify
<add> # <tt>include_hidden: false</tt> option.
<ide> def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
<ide> Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
<ide> end
<ide><path>actionview/lib/action_view/helpers/tags/collection_check_boxes.rb
<ide> class CollectionCheckBoxes < Base # :nodoc:
<ide> class CheckBoxBuilder < Builder # :nodoc:
<ide> def check_box(extra_html_options={})
<ide> html_options = extra_html_options.merge(@input_html_options)
<add> html_options[:multiple] = true
<ide> @template_object.check_box(@object_name, @method_name, html_options, @value, nil)
<ide> end
<ide> end
<ide>
<ide> def render(&block)
<del> rendered_collection = render_collection do |item, value, text, default_html_options|
<del> default_html_options[:multiple] = true
<del> builder = instantiate_builder(CheckBoxBuilder, item, value, text, default_html_options)
<del>
<del> if block_given?
<del> @template_object.capture(builder, &block)
<del> else
<del> render_component(builder)
<del> end
<del> end
<del>
<del> # Append a hidden field to make sure something will be sent back to the
<del> # server if all check boxes are unchecked.
<del> if @options.fetch(:include_hidden, true)
<del> rendered_collection + hidden_field
<del> else
<del> rendered_collection
<del> end
<add> render_collection_for(CheckBoxBuilder, &block)
<ide> end
<ide>
<ide> private
<ide>
<ide> def render_component(builder)
<ide> builder.check_box + builder.label
<ide> end
<del>
<del> def hidden_field
<del> hidden_name = @html_options[:name] || "#{tag_name(false, @options[:index])}[]"
<del> @template_object.hidden_field_tag(hidden_name, "", id: nil)
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/helpers/tags/collection_helpers.rb
<ide> def render_collection #:nodoc:
<ide> yield item, value, text, default_html_options.merge(additional_html_options)
<ide> end.join.html_safe
<ide> end
<add>
<add> def render_collection_for(builder_class, &block) #:nodoc:
<add> options = @options.stringify_keys
<add> rendered_collection = render_collection do |item, value, text, default_html_options|
<add> builder = instantiate_builder(builder_class, item, value, text, default_html_options)
<add>
<add> if block_given?
<add> @template_object.capture(builder, &block)
<add> else
<add> render_component(builder)
<add> end
<add> end
<add>
<add> # Append a hidden field to make sure something will be sent back to the
<add> # server if all radio buttons are unchecked.
<add> if options.fetch('include_hidden', true)
<add> rendered_collection + hidden_field
<add> else
<add> rendered_collection
<add> end
<add> end
<add>
<add> def hidden_field #:nodoc:
<add> hidden_name = @html_options[:name] || "#{tag_name(false, @options[:index])}[]"
<add> @template_object.hidden_field_tag(hidden_name, "", id: nil)
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/helpers/tags/collection_radio_buttons.rb
<ide> def radio_button(extra_html_options={})
<ide> end
<ide>
<ide> def render(&block)
<del> render_collection do |item, value, text, default_html_options|
<del> builder = instantiate_builder(RadioButtonBuilder, item, value, text, default_html_options)
<del>
<del> if block_given?
<del> @template_object.capture(builder, &block)
<del> else
<del> render_component(builder)
<del> end
<del> end
<add> render_collection_for(RadioButtonBuilder, &block)
<ide> end
<ide>
<ide> private
<ide><path>actionview/test/template/form_collections_helper_test.rb
<ide> def with_collection_check_boxes(*args, &block)
<ide> assert_select 'input[type=radio][value=false][checked=checked]'
<ide> end
<ide>
<add> test 'collection radio buttons generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection' do
<add> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name
<add>
<add> assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 1
<add> end
<add>
<add> test 'collection radio buttons generates a hidden field using the given :name in :html_options' do
<add> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, {}, { name: "user[other_category_ids][]" }
<add>
<add> assert_select "input[type=hidden][name='user[other_category_ids][]'][value='']", count: 1
<add> end
<add>
<add> test 'collection radio buttons generates a hidden field with index if it was provided' do
<add> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, { index: 322 }
<add>
<add> assert_select "input[type=hidden][name='user[322][category_ids][]'][value='']", count: 1
<add> end
<add>
<add> test 'collection radio buttons does not generate a hidden field if include_hidden option is false' do
<add> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, include_hidden: false
<add>
<add> assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0
<add> end
<add>
<add> test 'collection radio buttons does not generate a hidden field if include_hidden option is false with key as string' do
<add> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<add> with_collection_radio_buttons :user, :category_ids, collection, :id, :name, 'include_hidden' => false
<add>
<add> assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0
<add> end
<add>
<ide> # COLLECTION CHECK BOXES
<ide> test 'collection check boxes accepts a collection and generate a series of checkboxes for value method' do
<ide> collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
<ide><path>actionview/test/template/form_helper_test.rb
<ide> def post.active; false; end
<ide> "<input id='post_active_true' name='post[active]' type='radio' value='true' />" +
<ide> "<label for='post_active_true'>true</label>" +
<ide> "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
<del> "<label for='post_active_false'>false</label>"
<add> "<label for='post_active_false'>false</label>" +
<add> "<input type='hidden' name='post[active][]' value='' />"
<ide> end
<ide>
<ide> assert_dom_equal expected, output_buffer
<ide> def post.active; false; end
<ide> "true</label>" +
<ide> "<label for='post_active_false'>"+
<ide> "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
<del> "false</label>"
<add> "false</label>" +
<add> "<input type='hidden' name='post[active][]' value='' />"
<ide> end
<ide>
<ide> assert_dom_equal expected, output_buffer
<ide> def post.id; 1; end
<ide> "<label for='post_active_false'>"+
<ide> "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
<ide> "false</label>"+
<add> "<input type='hidden' name='post[active][]' value='' />" +
<ide> "<input id='post_id' name='post[id]' type='hidden' value='1' />"
<ide> end
<ide>
<ide> def post.active; false; end
<ide> "<input id='foo_post_active_true' name='post[active]' type='radio' value='true' />" +
<ide> "<label for='foo_post_active_true'>true</label>" +
<ide> "<input checked='checked' id='foo_post_active_false' name='post[active]' type='radio' value='false' />" +
<del> "<label for='foo_post_active_false'>false</label>"
<add> "<label for='foo_post_active_false'>false</label>" +
<add> "<input type='hidden' name='post[active][]' value='' />"
<ide> end
<ide>
<ide> assert_dom_equal expected, output_buffer
<ide> def post.active; false; end
<ide> "<input id='post_1_active_true' name='post[1][active]' type='radio' value='true' />" +
<ide> "<label for='post_1_active_true'>true</label>" +
<ide> "<input checked='checked' id='post_1_active_false' name='post[1][active]' type='radio' value='false' />" +
<del> "<label for='post_1_active_false'>false</label>"
<add> "<label for='post_1_active_false'>false</label>" +
<add> "<input type='hidden' name='post[1][active][]' value='' />"
<ide> end
<ide>
<ide> assert_dom_equal expected, output_buffer | 7 |
Javascript | Javascript | update remote method definitions | 187dbdfc92aa59986452f9a5fa353decc56d01ae | <ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> User.remoteMethod(
<ide> 'updateTheme',
<ide> {
<del> isStatic: false,
<ide> description: 'updates the users chosen theme',
<ide> accepts: [
<ide> { | 1 |
Go | Go | fix race between two containerrm | 4d1007d75c24f4e9f1d8df18cb3faae53b183661 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) create(params *ContainerCreateConfig) (retC *Container, re
<ide> }
<ide> defer func() {
<ide> if retErr != nil {
<del> if err := daemon.rm(container, true); err != nil {
<add> if err := daemon.ContainerRm(container.ID, &ContainerRmConfig{ForceRemove: true}); err != nil {
<ide> logrus.Errorf("Clean up Error! Cannot destroy container %s: %v", container.ID, err)
<ide> }
<ide> }
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) ContainerRm(name string, config *ContainerRmConfig) error
<ide> return err
<ide> }
<ide>
<add> // Container state RemovalInProgress should be used to avoid races.
<add> if err = container.setRemovalInProgress(); err != nil {
<add> if err == derr.ErrorCodeAlreadyRemoving {
<add> // do not fail when the removal is in progress started by other request.
<add> return nil
<add> }
<add> return derr.ErrorCodeRmState.WithArgs(err)
<add> }
<add> defer container.resetRemovalInProgress()
<add>
<add> // check if container wasn't deregistered by previous rm since Get
<add> if c := daemon.containers.Get(container.ID); c == nil {
<add> return nil
<add> }
<add>
<ide> if config.RemoveLink {
<ide> name, err := GetFullContainerName(name)
<ide> if err != nil {
<ide> func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) {
<ide> }
<ide> }
<ide>
<del> // Container state RemovalInProgress should be used to avoid races.
<del> if err = container.setRemovalInProgress(); err != nil {
<del> if err == derr.ErrorCodeAlreadyRemoving {
<del> // do not fail when the removal is in progress started by other request.
<del> return nil
<del> }
<del> return derr.ErrorCodeRmState.WithArgs(err)
<del> }
<del> defer container.resetRemovalInProgress()
<del>
<ide> // stop collection of stats for the container regardless
<ide> // if stats are currently getting collected.
<ide> daemon.statsCollector.stopCollection(container)
<ide><path>daemon/delete_test.go
<ide> func TestContainerDoubleDelete(t *testing.T) {
<ide> repository: tmp,
<ide> root: tmp,
<ide> }
<add> daemon.containers = &contStore{s: make(map[string]*Container)}
<ide>
<ide> container := &Container{
<ide> CommonContainer: CommonContainer{
<add> ID: "test",
<ide> State: NewState(),
<ide> Config: &runconfig.Config{},
<ide> },
<ide> }
<add> daemon.containers.Add(container.ID, container)
<ide>
<ide> // Mark the container as having a delete in progress
<ide> if err := container.setRemovalInProgress(); err != nil {
<ide> func TestContainerDoubleDelete(t *testing.T) {
<ide>
<ide> // Try to remove the container when it's start is removalInProgress.
<ide> // It should ignore the container and not return an error.
<del> if err := daemon.rm(container, true); err != nil {
<add> if err := daemon.ContainerRm(container.ID, &ContainerRmConfig{ForceRemove: true}); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> } | 3 |
Ruby | Ruby | add support for custom version schemes | 2ff6c40735be2aca0e37ed94095526abcd115310 | <ide><path>Library/Homebrew/formula_support.rb
<ide> def url val=nil, specs=nil
<ide> end
<ide>
<ide> def version val=nil
<del> if val.nil?
<del> @version ||= Version.parse(@url)
<del> else
<del> @version = Version.new(val)
<del> end
<add> @version ||= case val
<add> when nil then Version.parse(@url)
<add> when Hash
<add> key, value = val.shift
<add> scheme = VersionSchemeDetector.new(value).detect
<add> scheme.new(key)
<add> else Version.new(val)
<add> end
<ide> end
<ide>
<ide> def mirror val
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_revised_bottle_specs
<ide> when :mountainlion then '8badf00d8badf00d8badf00d8badf00d8badf00d'
<ide> end, f.bottle.checksum.hexdigest
<ide> end
<add>
<add> def test_custom_version_scheme
<add> f = CustomVersionSchemeTestBall.new
<add>
<add> assert_version_equal '1.0', f.version
<add> assert_instance_of CustomVersionScheme, f.version
<add> end
<ide> end
<ide><path>Library/Homebrew/test/testball.rb
<ide> def initialize name=nil
<ide> super "revisedbottlespectestball"
<ide> end
<ide> end
<add>
<add>class CustomVersionScheme < Version
<add>end
<add>
<add>class CustomVersionSchemeTestBall < Formula
<add> homepage 'http://example.com'
<add> url 'file:///foo.com/testball-0.1.tbz'
<add> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<add> version '1.0' => CustomVersionScheme
<add>
<add> def initialize name=nil
<add> super "customversionschemetestball"
<add> end
<add>end
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse spec
<ide> return m.captures.first unless m.nil?
<ide> end
<ide> end
<add>
<add>class VersionSchemeDetector
<add> def initialize scheme
<add> @scheme = scheme
<add> end
<add>
<add> def detect
<add> if @scheme.is_a? Class and @scheme.ancestors.include? Version
<add> @scheme
<add> elsif @scheme.is_a? Symbol then detect_from_symbol
<add> else
<add> raise "Unknown version scheme #{@scheme} was requested."
<add> end
<add> end
<add>
<add> private
<add>
<add> def detect_from_symbol
<add> raise "Unknown version scheme #{@scheme} was requested."
<add> end
<add>end | 4 |
Text | Text | decharter the http working group | 132e44b4028b2f6038843d839b631c2b4ef0eef7 | <ide><path>WORKING_GROUPS.md
<ide> Top Level Working Group](https://github.com/nodejs/TSC/blob/master/WORKING_GROUP
<ide> * [Benchmarking](#benchmarking)
<ide> * [Post-mortem](#post-mortem)
<ide> * [Intl](#intl)
<del>* [HTTP](#http)
<ide> * [Documentation](#documentation)
<ide> * [Testing](#testing)
<ide>
<ide> Responsibilities include:
<ide> * Publishing regular update summaries and other promotional
<ide> content.
<ide>
<del>### [HTTP](https://github.com/nodejs/http)
<del>
<del>The HTTP Working Group is chartered for the support and improvement of the
<del>HTTP implementation in Node.js.
<del>
<del>Responsibilities include:
<del>* Addressing HTTP issues on the Node.js issue tracker.
<del>* Authoring and editing HTTP documentation within the Node.js project.
<del>* Reviewing changes to HTTP functionality within the Node.js project.
<del>* Working with the ecosystem of HTTP related module developers to evolve the
<del> HTTP implementation and APIs in core.
<del>* Advising the CTC on all HTTP related issues and discussions.
<del>* Messaging about the future of HTTP to give the community advance notice of
<del> changes.
<del>
<ide> ### [Docker](https://github.com/nodejs/docker-iojs)
<ide>
<ide> The Docker Working Group's purpose is to build, maintain, and improve official | 1 |
Javascript | Javascript | remove external prop on 'donate' link | 0a7278774eee83a8b8056f2a89a0d353104a574b | <ide><path>client/src/components/Header/components/NavLinks.js
<ide> export class NavLinks extends Component {
<ide> <FontAwesomeIcon icon={faHeart} />
<ide> </div>
<ide> ) : (
<del> <Link
<del> className='nav-link'
<del> external={true}
<del> key='donate'
<del> sameTab={false}
<del> to='/donate'
<del> >
<add> <Link className='nav-link' key='donate' sameTab={false} to='/donate'>
<ide> {t('buttons.donate')}
<ide> </Link>
<ide> )} | 1 |
Javascript | Javascript | adjust donation confirmation text | 05a97d19fbafa2c3fd1dad72b03b528a2caa33b7 | <ide><path>client/src/components/Donation/DonateForm.js
<ide> class DonateForm extends Component {
<ide> {t('donate.confirm-1')} {donationAmount / 100}:
<ide> </b>
<ide> ) : (
<del> <b>
<del> {t('donate.confirm-2')} {donationAmount / 100} / {donationDuration}:
<del> </b>
<add> <b>{t('donate.confirm-3', { usd: donationAmount / 100 })}:</b>
<ide> )}
<ide> <Spacer />
<ide> <div className='donate-btn-group'>
<ide><path>cypress/integration/learn/donate/donate-page-default.js
<ide> describe('Donate page', () => {
<ide> cy.title().should('eq', 'Support our nonprofit | freeCodeCamp.org');
<ide> });
<ide>
<add> it('Should display default amount and duration', () => {
<add> cy.contains('Confirm your donation of $5 / month:').should('be.visible');
<add> });
<add>
<ide> it('Should have support section', () => {
<ide> cy.contains(
<ide> 'Want to make a bigger one-time donation, mail us a check, or give in other ways?' | 2 |
PHP | PHP | improve arugement name and docblock | c731d7ba1888c4658f2aacff41aa728e1def852b | <ide><path>src/Utility/Inflector.php
<ide> public static function underscore($camelCasedWord) {
<ide> }
<ide>
<ide> /**
<del> * Returns the given underscored_word or CamelCasedWord as an hyphenated-word.
<add> * Returns the given CamelCasedWordGroup as an hyphenated-word-group.
<ide> *
<del> * @param string $word The word to hyphenate.
<del> * @return string Hyphenated version of the word.
<add> * @param string $wordGroup The string to hyphenate.
<add> * @return string Hyphenated version of the word group
<ide> */
<del> public static function hyphenate($word) {
<del> $result = static::_cache(__FUNCTION__, $word);
<add> public static function hyphenate($wordGroup) {
<add> $result = static::_cache(__FUNCTION__, $wordGroup);
<ide> if ($result !== null) {
<ide> return $result;
<ide> }
<ide>
<del> $result = str_replace('_', '-', static::underscore($word));
<del> static::_cache(__FUNCTION__, $word, $result);
<add> $result = str_replace('_', '-', static::underscore($wordGroup));
<add> static::_cache(__FUNCTION__, $wordGroup, $result);
<ide> return $result;
<ide> }
<ide> | 1 |
Ruby | Ruby | add gzip rsync to the white list | ffb405019d1e76d36fd1bf3b20094044aa94b818 | <ide><path>Library/Homebrew/rubocops/uses_from_macos.rb
<ide> class UsesFromMacos < FormulaCop
<ide> bash
<ide> expect
<ide> groff
<add> gzip
<ide> openssl
<ide> openssl@1.1
<ide> perl
<ide> php
<ide> python
<ide> python@3
<add> rsync
<ide> vim
<ide> xz
<ide> zsh | 1 |
Ruby | Ruby | restore test deliveries properly in actionmailer | c4f4123ef45463a09b36186047dbdc82f933fe46 | <ide><path>actionmailer/lib/action_mailer/test_case.rb
<ide> module Behavior
<ide> class_attribute :_mailer_class
<ide> setup :initialize_test_deliveries
<ide> setup :set_expected_mail
<add> teardown :restore_test_deliveries
<ide> end
<ide>
<ide> module ClassMethods
<ide> def determine_default_mailer(name)
<ide> protected
<ide>
<ide> def initialize_test_deliveries
<add> @old_delivery_method = ActionMailer::Base.delivery_method
<add> @old_perform_deliveries = ActionMailer::Base.perform_deliveries
<ide> ActionMailer::Base.delivery_method = :test
<ide> ActionMailer::Base.perform_deliveries = true
<add> end
<add>
<add> def restore_test_deliveries
<add> ActionMailer::Base.delivery_method = @old_delivery_method
<add> ActionMailer::Base.perform_deliveries = @old_perform_deliveries
<ide> ActionMailer::Base.deliveries.clear
<ide> end
<ide> | 1 |
Ruby | Ruby | follow alias changes | 2a683f2569614850f79534a8547fd96cc52c7850 | <ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def print_outdated(formulae)
<ide>
<ide> outdated_formulae.each do |f|
<ide> if verbose
<del> outdated_versions = f.outdated_versions(fetch_head: fetch_head)
<del> current_version = if f.head? && outdated_versions.any? { |v| v.to_s == f.pkg_version.to_s }
<add> outdated_kegs = f.outdated_kegs(fetch_head: fetch_head)
<add>
<add> current_version = if f.alias_changed?
<add> latest = f.latest_formula
<add> "#{latest.name} (#{latest.pkg_version})"
<add> elsif f.head? && outdated_kegs.any? { |k| k.version.to_s == f.pkg_version.to_s }
<add> # There is a newer HEAD but the version number has not changed.
<ide> "latest HEAD"
<ide> else
<ide> f.pkg_version.to_s
<ide> end
<del> puts "#{f.full_name} (#{outdated_versions.join(", ")}) < #{current_version}"
<add>
<add> outdated_versions = outdated_kegs.
<add> group_by(&:name).
<add> sort_by(&:first).
<add> map { |name, kegs| "#{name} (#{kegs.map(&:version) * ", "})" } * ", "
<add>
<add> puts "#{outdated_versions} < #{current_version}"
<ide> else
<del> puts f.full_name
<add> puts f.full_installed_specified_name
<ide> end
<ide> end
<ide> end
<ide> def print_outdated_json(formulae)
<ide> outdated_formulae = formulae.select { |f| f.outdated?(fetch_head: fetch_head) }
<ide>
<ide> outdated = outdated_formulae.each do |f|
<del> outdated_versions = f.outdated_versions(fetch_head: fetch_head)
<add> outdated_versions = f.outdated_kegs(fetch_head: fetch_head).map(&:version)
<ide> current_version = if f.head? && outdated_versions.any? { |v| v.to_s == f.pkg_version.to_s }
<ide> "HEAD"
<ide> else
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide> (ARGV.resolved_formulae - outdated).each do |f|
<ide> versions = f.installed_kegs.map(&:version)
<ide> if versions.empty?
<del> onoe "#{f.full_name} not installed"
<add> onoe "#{f.full_specified_name} not installed"
<ide> else
<ide> version = versions.max
<del> onoe "#{f.full_name} #{version} already installed"
<add> onoe "#{f.full_specified_name} #{version} already installed"
<ide> end
<ide> end
<ide> exit 1 if outdated.empty?
<ide> def upgrade
<ide> outdated -= pinned
<ide> end
<ide>
<del> if outdated.empty?
<add> formulae_to_install = outdated.map(&:latest_formula)
<add>
<add> if formulae_to_install.empty?
<ide> oh1 "No packages to upgrade"
<ide> else
<del> oh1 "Upgrading #{outdated.length} outdated package#{plural(outdated.length)}, with result:"
<del> puts outdated.map { |f| "#{f.full_name} #{f.pkg_version}" } * ", "
<add> oh1 "Upgrading #{formulae_to_install.length} outdated package#{plural(formulae_to_install.length)}, with result:"
<add> puts formulae_to_install.map { |f| "#{f.full_specified_name} #{f.pkg_version}" } * ", "
<ide> end
<ide>
<ide> unless upgrade_pinned? || pinned.empty?
<ide> oh1 "Not upgrading #{pinned.length} pinned package#{plural(pinned.length)}:"
<del> puts pinned.map { |f| "#{f.full_name} #{f.pkg_version}" } * ", "
<add> puts pinned.map { |f| "#{f.full_specified_name} #{f.pkg_version}" } * ", "
<ide> end
<ide>
<del> outdated.each do |f|
<add> formulae_to_install.each do |f|
<ide> upgrade_formula(f)
<ide> next unless ARGV.include?("--cleanup")
<ide> next unless f.installed?
<ide> def upgrade_pinned?
<ide> end
<ide>
<ide> def upgrade_formula(f)
<del> outdated_keg = Keg.new(f.linked_keg.resolved_path) if f.linked_keg.directory?
<add> formulae_maybe_with_kegs = [f] + f.old_installed_formulae
<add> outdated_kegs = formulae_maybe_with_kegs.
<add> map(&:linked_keg).
<add> select(&:directory?).
<add> map { |k| Keg.new(k.resolved_path) }
<ide>
<ide> fi = FormulaInstaller.new(f)
<ide> fi.options = f.build.used_options
<ide> def upgrade_formula(f)
<ide> fi.debug = ARGV.debug?
<ide> fi.prelude
<ide>
<del> oh1 "Upgrading #{f.full_name}"
<add> oh1 "Upgrading #{f.full_specified_name}"
<ide>
<ide> # first we unlink the currently active keg for this formula otherwise it is
<ide> # possible for the existing build to interfere with the build we are about to
<ide> # do! Seriously, it happens!
<del> outdated_keg.unlink if outdated_keg
<add> outdated_kegs.each(&:unlink)
<ide>
<ide> fi.install
<ide> fi.finish
<ide> def upgrade_formula(f)
<ide> ensure
<ide> # restore previous installation state if build failed
<ide> begin
<del> outdated_keg.link if outdated_keg && !f.installed?
<add> outdated_kegs.each(&:link) if !f.installed?
<ide> rescue
<ide> nil
<ide> end
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def resolved_formulae
<ide> f.version.update_commit(k.version.version.commit) if k.version.head?
<ide> end
<ide> end
<del> f
<ide> else
<ide> rack = Formulary.to_rack(name)
<del> Formulary.from_rack(rack, spec(nil))
<add> alias_path = Formulary.factory(name).alias_path
<add> f = Formulary.from_rack(rack, spec(nil), alias_path: alias_path)
<ide> end
<add>
<add> # If this formula was installed with an alias that has since changed,
<add> # then it was specified explicitly in ARGV. (Using the alias would
<add> # instead have found the new formula.)
<add> #
<add> # Because of this, the user is referring to this specific formula,
<add> # not any formula targetted by the same alias, so in this context
<add> # the formula shouldn't be considered outdated if the alias used to
<add> # install it has changed.
<add> f.follow_installed_alias = false
<add>
<add> f
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide> # e.g. `this-formula`
<ide> attr_reader :name
<ide>
<del> # The name that was used to identify this {Formula}.
<del> # Could be the name of the {Formula}, or an alias.
<del> # e.g. `another-name-for-this-formula`
<add> # The path to the alias that was used to identify this {Formula}.
<add> # e.g. `/usr/local/Library/Taps/homebrew/homebrew-core/Aliases/another-name-for-this-formula`
<ide> attr_reader :alias_path
<ide>
<add> # The name of the alias that was used to identify this {Formula}.
<add> # e.g. `another-name-for-this-formula`
<add> attr_reader :alias_name
<add>
<ide> # The fully-qualified name of this {Formula}.
<ide> # For core formula it's the same as {#name}.
<ide> # e.g. `homebrew/tap-name/this-formula`
<ide> attr_reader :full_name
<ide>
<add> # The fully-qualified alias referring to this {Formula}.
<add> # For core formula it's the same as {#alias_name}.
<add> # e.g. `homebrew/tap-name/another-name-for-this-formula`
<add> attr_reader :full_alias_name
<add>
<ide> # The full path to this {Formula}.
<ide> # e.g. `/usr/local/Library/Taps/homebrew/homebrew-core/Formula/this-formula.rb`
<ide> attr_reader :path
<ide> class Formula
<ide> # @return [BuildOptions]
<ide> attr_accessor :build
<ide>
<add> # A {Boolean} indicating whether this formula should be considered outdated
<add> # if the target of the alias it was installed with has since changed.
<add> # Defaults to true.
<add> # @return [Boolean]
<add> attr_accessor :follow_installed_alias
<add> alias follow_installed_alias? follow_installed_alias
<add>
<ide> # @private
<ide> def initialize(name, path, spec, alias_path: nil)
<ide> @name = name
<ide> @path = path
<ide> @alias_path = alias_path
<add> @alias_name = File.basename(alias_path) if alias_path
<ide> @revision = self.class.revision || 0
<ide> @version_scheme = self.class.version_scheme || 0
<ide>
<del> if path == Formulary.core_path(name)
<del> @tap = CoreTap.instance
<del> @full_name = name
<add> @tap = if path == Formulary.core_path(name)
<add> CoreTap.instance
<ide> elsif path.to_s =~ HOMEBREW_TAP_PATH_REGEX
<del> @tap = Tap.fetch($1, $2)
<del> @full_name = "#{@tap}/#{name}"
<del> else
<del> @tap = nil
<del> @full_name = name
<add> Tap.fetch($1, $2)
<ide> end
<ide>
<add> @full_name = get_full_name(name)
<add> @full_alias_name = get_full_name(@alias_name)
<add>
<ide> set_spec :stable
<ide> set_spec :devel
<ide> set_spec :head
<ide> def initialize(name, path, spec, alias_path: nil)
<ide> validate_attributes!
<ide> @build = active_spec.build
<ide> @pin = FormulaPin.new(self)
<add> @follow_installed_alias = true
<ide> end
<ide>
<ide> # @private
<ide> def set_active_spec(spec_sym)
<ide>
<ide> private
<ide>
<add> # Allow full name logic to be re-used between names, aliases,
<add> # and installed aliases.
<add> def get_full_name(name)
<add> if name.nil? || @tap.nil? || @tap.core_tap?
<add> name
<add> else
<add> "#{@tap}/#{name}"
<add> end
<add> end
<add>
<ide> def set_spec(name)
<ide> spec = self.class.send(name)
<ide> if spec.url
<ide> def installed_alias_path
<ide> path if path =~ %r{#{HOMEBREW_TAP_DIR_REGEX}/Aliases}
<ide> end
<ide>
<add> def installed_alias_name
<add> File.basename(installed_alias_path) if installed_alias_path
<add> end
<add>
<add> def full_installed_alias_name
<add> get_full_name(installed_alias_name)
<add> end
<add>
<ide> # The path that was specified to find this formula.
<ide> def specified_path
<ide> alias_path || path
<ide> end
<ide>
<add> # The name specified to find this formula.
<add> def specified_name
<add> alias_name || name
<add> end
<add>
<add> # The name (including tap) specified to find this formula.
<add> def full_specified_name
<add> full_alias_name || full_name
<add> end
<add>
<add> # The name specified to install this formula.
<add> def installed_specified_name
<add> installed_alias_name || name
<add> end
<add>
<add> # The name (including tap) specified to install this formula.
<add> def full_installed_specified_name
<add> full_installed_alias_name || full_name
<add> end
<add>
<ide> # Is the currently active {SoftwareSpec} a {#stable} build?
<ide> # @private
<ide> def stable?
<ide> def migration_needed?
<ide> end
<ide>
<ide> # @private
<del> def outdated_versions(options = {})
<del> @outdated_versions ||= Hash.new do |cache, key|
<add> def outdated_kegs(options = {})
<add> @outdated_kegs ||= Hash.new do |cache, key|
<ide> raise Migrator::MigrationNeededError, self if migration_needed?
<del> cache[key] = _outdated_versions(key)
<add> cache[key] = _outdated_kegs(key)
<ide> end
<del> @outdated_versions[options]
<add> @outdated_kegs[options]
<ide> end
<ide>
<del> def _outdated_versions(options = {})
<del> all_versions = []
<add> def _outdated_kegs(options = {})
<add> all_kegs = []
<ide>
<ide> installed_kegs.each do |keg|
<add> all_kegs << keg
<ide> version = keg.version
<del> all_versions << version
<ide> next if version.head?
<ide>
<ide> tab = Tab.for_keg(keg)
<ide> next if version_scheme > tab.version_scheme
<ide> next if version_scheme == tab.version_scheme && pkg_version > version
<del> return []
<add> next if follow_installed_alias? && installed_alias_target_changed?
<add>
<add> return [] # this keg is the current version of the formula, so it's not outdated
<ide> end
<ide>
<add> # Even if this formula hasn't been installed, there may be installations
<add> # of other formulae which used to be targets of the alias currently
<add> # targetting this formula. These should be counted as outdated versions.
<add> all_kegs.concat old_installed_formulae.flat_map(&:installed_kegs)
<add>
<ide> head_version = latest_head_version
<ide> if head_version && !head_version_outdated?(head_version, options)
<ide> []
<ide> else
<del> all_versions.sort
<add> all_kegs.sort_by(&:version)
<ide> end
<ide> end
<ide>
<add> def current_installed_alias_target
<add> Formulary.factory(installed_alias_path) if installed_alias_path
<add> end
<add>
<add> # Has the target of the alias used to install this formula changed?
<add> # Returns false if the formula wasn't installed with an alias.
<add> def installed_alias_target_changed?
<add> ![self, nil].include?(current_installed_alias_target)
<add> end
<add>
<add> # Is this formula the target of an alias used to install an old formula?
<add> def supersedes_an_installed_formula?
<add> old_installed_formulae.any?
<add> end
<add>
<add> # Has the alias used to install the formula changed, or are different
<add> # formulae already installed with this alias?
<add> def alias_changed?
<add> installed_alias_target_changed? || supersedes_an_installed_formula?
<add> end
<add>
<add> # If the alias has changed value, return the new formula.
<add> # Otherwise, return self.
<add> def latest_formula
<add> installed_alias_target_changed? ? current_installed_alias_target : self
<add> end
<add>
<add> def old_installed_formulae
<add> alias_path ? self.class.installed_with_alias_path(alias_path) : []
<add> end
<add>
<ide> # @private
<ide> def outdated?(options = {})
<del> !outdated_versions(options).empty?
<add> !outdated_kegs(options).empty?
<ide> rescue Migrator::MigrationNeededError
<ide> true
<ide> end
<ide> def self.installed
<ide> end.compact
<ide> end
<ide>
<add> def self.installed_with_alias_path(alias_path)
<add> return [] if alias_path.nil?
<add> installed.select { |f| f.installed_alias_path == alias_path }
<add> end
<add>
<ide> # an array of all alias files of core {Formula}
<ide> # @private
<ide> def self.core_alias_files
<ide><path>Library/Homebrew/formulary.rb
<ide> def initialize(name, path)
<ide> end
<ide>
<ide> # Gets the formula instance.
<del> def get_formula(spec)
<del> klass.new(name, path, spec, alias_path: alias_path)
<add> #
<add> # `alias_path` can be overridden here in case an alias was used to refer to
<add> # a formula that was loaded in another way.
<add> def get_formula(spec, alias_path: nil)
<add> klass.new(name, path, spec, alias_path: alias_path || self.alias_path)
<ide> end
<ide>
<ide> def klass
<ide> def initialize(bottle_name)
<ide> super name, Formulary.path(full_name)
<ide> end
<ide>
<del> def get_formula(spec)
<add> def get_formula(spec, alias_path: nil)
<ide> formula = super
<ide> formula.local_bottle_path = @bottle_filename
<ide> formula_version = formula.pkg_version
<ide> def initialize(alias_path)
<ide> path = alias_path.resolved_path
<ide> name = path.basename(".rb").to_s
<ide> super name, path
<del> @alias_path = alias_path
<add> @alias_path = alias_path.to_s
<ide> end
<ide> end
<ide>
<ide> def initialize(tapped_name)
<ide> super name, path
<ide> end
<ide>
<del> def get_formula(spec)
<add> def get_formula(spec, alias_path: nil)
<ide> super
<ide> rescue FormulaUnavailableError => e
<ide> raise TapFormulaUnavailableError.new(tap, name), "", e.backtrace
<ide> def initialize(name)
<ide> super name, Formulary.core_path(name)
<ide> end
<ide>
<del> def get_formula(_spec)
<add> def get_formula(_spec, alias_path: nil)
<ide> raise FormulaUnavailableError, name
<ide> end
<ide> end
<ide> def klass
<ide> # * a formula pathname
<ide> # * a formula URL
<ide> # * a local bottle reference
<del> def self.factory(ref, spec = :stable)
<del> loader_for(ref).get_formula(spec)
<add> def self.factory(ref, spec = :stable, alias_path: nil)
<add> loader_for(ref).get_formula(spec, alias_path: alias_path)
<ide> end
<ide>
<ide> # Return a Formula instance for the given rack.
<ide> # It will auto resolve formula's spec when requested spec is nil
<del> def self.from_rack(rack, spec = nil)
<add> #
<add> # The :alias_path option will be used if the formula is found not to be
<add> # installed, and discarded if it is installed because the alias_path used
<add> # to install the formula will be set instead.
<add> def self.from_rack(rack, spec = nil, alias_path: nil)
<ide> kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : []
<ide> keg = kegs.detect(&:linked?) || kegs.detect(&:optlinked?) || kegs.max_by(&:version)
<ide>
<ide> if keg
<del> from_keg(keg, spec)
<add> from_keg(keg, spec, :alias_path => alias_path)
<ide> else
<del> factory(rack.basename.to_s, spec || :stable)
<add> factory(rack.basename.to_s, spec || :stable, :alias_path => alias_path)
<ide> end
<ide> end
<ide>
<ide> # Return a Formula instance for the given keg.
<ide> # It will auto resolve formula's spec when requested spec is nil
<del> def self.from_keg(keg, spec = nil)
<add> def self.from_keg(keg, spec = nil, alias_path: nil)
<ide> tab = Tab.for_keg(keg)
<ide> tap = tab.tap
<ide> spec ||= tab.spec
<ide>
<ide> f = if tap.nil?
<del> factory(keg.rack.basename.to_s, spec)
<add> factory(keg.rack.basename.to_s, spec, :alias_path => alias_path)
<ide> else
<ide> begin
<del> factory("#{tap}/#{keg.rack.basename}", spec)
<add> factory("#{tap}/#{keg.rack.basename}", spec, :alias_path => alias_path)
<ide> rescue FormulaUnavailableError
<ide> # formula may be migrated to different tap. Try to search in core and all taps.
<del> factory(keg.rack.basename.to_s, spec)
<add> factory(keg.rack.basename.to_s, spec, :alias_path => alias_path)
<ide> end
<ide> end
<ide> f.build = tab
<ide> def self.loader_for(ref)
<ide> end
<ide>
<ide> def self.core_path(name)
<del> CoreTap.instance.formula_dir/"#{name.downcase}.rb"
<add> CoreTap.instance.formula_dir/"#{name.to_s.downcase}.rb"
<ide> end
<ide>
<ide> def self.tap_paths(name, taps = Dir["#{HOMEBREW_LIBRARY}/Taps/*/*/"])
<ide><path>Library/Homebrew/test/test_formulary.rb
<ide> def test_factory_from_alias
<ide> FileUtils.ln_s @path, alias_path
<ide> result = Formulary.factory("foo")
<ide> assert_kind_of Formula, result
<del> assert_equal alias_path, result.alias_path
<add> assert_equal alias_path.to_s, result.alias_path
<ide> ensure
<ide> alias_dir.rmtree
<ide> end | 6 |
Ruby | Ruby | add methods to get git related information | 9f96e41b40f52313fbc7832df631827f5e3bcacb | <ide><path>Library/Homebrew/tap.rb
<ide> def clear_cache
<ide> # e.g. `https://github.com/user/homebrew-repo`
<ide> def remote
<ide> @remote ||= if installed?
<del> if git?
<add> if git? && Utils.git_available?
<ide> path.cd do
<ide> Utils.popen_read("git", "config", "--get", "remote.origin.url").chomp
<ide> end
<ide> def git?
<ide> (path/".git").exist?
<ide> end
<ide>
<add> # git HEAD for this {Tap}.
<add> def git_head
<add> raise TapUnavailableError, name unless installed?
<add> return unless git? && Utils.git_available?
<add> path.cd { Utils.popen_read("git", "rev-parse", "--verify", "-q", "HEAD").chuzzle }
<add> end
<add>
<add> # git HEAD in short format for this {Tap}.
<add> def git_short_head
<add> raise TapUnavailableError, name unless installed?
<add> return unless git? && Utils.git_available?
<add> path.cd { Utils.popen_read("git", "rev-parse", "--short=4", "--verify", "-q", "HEAD").chuzzle }
<add> end
<add>
<add> # time since git last commit for this {Tap}.
<add> def git_last_commit
<add> raise TapUnavailableError, name unless installed?
<add> return unless git? && Utils.git_available?
<add> path.cd { Utils.popen_read("git", "show", "-s", "--format=%cr", "HEAD").chuzzle }
<add> end
<add>
<add> # git last commit date for this {Tap}.
<add> def git_last_commit_date
<add> raise TapUnavailableError, name unless installed?
<add> return unless git? && Utils.git_available?
<add> path.cd { Utils.popen_read("git", "show", "-s", "--format=%cd", "--date=short", "HEAD").chuzzle }
<add> end
<add>
<ide> # The issues URL of this {Tap}.
<ide> # e.g. `https://github.com/user/homebrew-repo/issues`
<ide> def issues_url
<ide><path>Library/Homebrew/test/test_tap.rb
<ide> require "testing_env"
<ide>
<ide> class TapTest < Homebrew::TestCase
<add> include FileUtils
<add>
<ide> def setup
<ide> @path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo"
<ide> @path.mkpath
<ide> class Foo < Formula
<ide> EOS
<ide> @alias_file = @path/"Aliases/bar"
<ide> @alias_file.parent.mkpath
<del> FileUtils.ln_s @formula_file, @alias_file
<add> ln_s @formula_file, @alias_file
<ide> (@path/"formula_renames.json").write <<-EOS.undent
<ide> { "oldname": "foo" }
<ide> EOS
<ide> class Foo < Formula
<ide> EOS
<ide> @cmd_file = @path/"cmd/brew-tap-cmd.rb"
<ide> @cmd_file.parent.mkpath
<del> FileUtils.touch @cmd_file
<del> FileUtils.chmod 0755, @cmd_file
<add> touch @cmd_file
<add> chmod 0755, @cmd_file
<ide> @manpage_file = @path/"man/man1/brew-tap-cmd.1"
<ide> @manpage_file.parent.mkpath
<del> FileUtils.touch @manpage_file
<add> touch @manpage_file
<ide> end
<ide>
<ide> def setup_git_repo
<add> env = ENV.to_hash
<add> %w[AUTHOR COMMITTER].each do |role|
<add> ENV["GIT_#{role}_NAME"] = "brew tests"
<add> ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost"
<add> ENV["GIT_#{role}_DATE"] = "Thu May 21 00:04:11 2009 +0100"
<add> end
<add>
<ide> @path.cd do
<ide> shutup do
<ide> system "git", "init"
<ide> def setup_git_repo
<ide> system "git", "commit", "-m", "init"
<ide> end
<ide> end
<add> ensure
<add> ENV.replace(env)
<ide> end
<ide>
<ide> def teardown
<ide> def test_issues_url
<ide> t = Tap.new("someone", "foo")
<ide> path = Tap::TAP_DIRECTORY/"someone/homebrew-foo"
<ide> path.mkpath
<del> FileUtils.cd path do
<add> cd path do
<ide> shutup { system "git", "init" }
<ide> system "git", "remote", "add", "origin",
<ide> "https://github.com/someone/homebrew-foo"
<ide> def test_remote
<ide> refute_predicate version_tap, :private?
<ide> end
<ide>
<add> def test_remote_not_git_repo
<add> assert_nil @tap.remote
<add> end
<add>
<add> def test_remote_git_not_available
<add> setup_git_repo
<add> Utils.stubs(:git_available?).returns(false)
<add> assert_nil @tap.remote
<add> end
<add>
<add> def test_git_variant
<add> touch @path/"README"
<add> setup_git_repo
<add>
<add> assert_equal "e1893a6bd191ba895c71b652ff8376a6114c7fa7", @tap.git_head
<add> assert_equal "e189", @tap.git_short_head
<add> assert_match %r{years ago}, @tap.git_last_commit
<add> assert_equal "2009-05-21", @tap.git_last_commit_date
<add> end
<add>
<ide> def test_private_remote
<ide> skip "HOMEBREW_GITHUB_API_TOKEN is required" unless ENV["HOMEBREW_GITHUB_API_TOKEN"]
<ide> assert_predicate @tap, :private?
<ide> def test_pin_and_unpin
<ide> end
<ide>
<ide> class CoreFormulaRepositoryTest < Homebrew::TestCase
<add> include FileUtils
<add>
<ide> def setup
<ide> @repo = CoreFormulaRepository.new
<ide> end
<ide> class Foo < Formula
<ide> EOS
<ide> @alias_file = @repo.alias_dir/"bar"
<ide> @alias_file.parent.mkpath
<del> FileUtils.ln_s @formula_file, @alias_file
<add> ln_s @formula_file, @alias_file
<ide>
<ide> assert_equal [@formula_file], @repo.formula_files
<ide> assert_equal ["foo"], @repo.formula_names | 2 |
Javascript | Javascript | replace string magic + path.join by path.resolve | 1ac133ea6f34bb8ef493f8f908d0cdda9a3e626a | <ide><path>lib/repl.js
<ide> REPLServer.prototype.complete = function(line) {
<ide> var dir, files, f, name, base, ext, abs, subfiles, s;
<ide> group = [];
<ide> for (i = 0; i < require.paths.length; i++) {
<del> dir = require.paths[i];
<del> if (subdir && subdir[0] === '/') {
<del> dir = subdir;
<del> } else if (subdir) {
<del> dir = path.join(dir, subdir);
<del> }
<add> dir = path.resolve(require.paths[i], subdir);
<ide> try {
<ide> files = fs.readdirSync(dir);
<ide> } catch (e) {
<ide> REPLServer.prototype.complete = function(line) {
<ide> group.push(subdir + base);
<ide> }
<ide> } else {
<del> abs = path.join(dir, name);
<add> abs = path.resolve(dir, name);
<ide> try {
<ide> if (fs.statSync(abs).isDirectory()) {
<ide> group.push(subdir + name + '/');
<ide><path>src/node.js
<ide>
<ide> var path = requireNative('path');
<ide>
<del> var modulePaths = [path.join(process.execPath, '..', '..', 'lib', 'node')];
<add> var modulePaths = [path.resolve(process.execPath, '..', '..', 'lib', 'node')];
<ide>
<ide> if (process.env['HOME']) {
<del> modulePaths.unshift(path.join(process.env['HOME'], '.node_libraries'));
<del> modulePaths.unshift(path.join(process.env['HOME'], '.node_modules'));
<add> modulePaths.unshift(path.resolve(process.env['HOME'], '.node_libraries'));
<add> modulePaths.unshift(path.resolve(process.env['HOME'], '.node_modules'));
<ide> }
<ide>
<ide> if (process.env['NODE_PATH']) {
<ide> for (var i = 0, PL = paths.length; i < PL; i++) {
<ide> var p = paths[i],
<ide> // try to join the request to the path
<del> f = tryFile(path.join(p, request)) ||
<add> f = tryFile(path.resolve(p, request)) ||
<ide> // try it with each of the extensions
<del> tryExtensions(path.join(p, request)) ||
<add> tryExtensions(path.resolve(p, request)) ||
<ide> // try it with each of the extensions at "index"
<del> tryExtensions(path.join(p, request, 'index'));
<add> tryExtensions(path.resolve(p, request, 'index'));
<ide> if (f) { return f; }
<ide> }
<ide> return false;
<ide> // as it already has been accepted as a module.
<ide> var isIndex = /^index\.\w+?$/.test(path.basename(parent.filename)),
<ide> parentIdPath = isIndex ? parent.id : path.dirname(parent.id),
<del> id = path.join(parentIdPath, request);
<add> id = path.resolve(parentIdPath, request);
<ide>
<ide> // make sure require('./path') and require('path') get distinct ids, even
<ide> // when called from the toplevel js file
<ide>
<ide> } else {
<ide> // Load module
<del> if ('/\\'.indexOf(process.argv[1].charAt(0)) < 0
<del> && process.argv[1].charAt(1) != ':'
<del> && !(/^http:\/\//).exec(process.argv[1])) {
<del> process.argv[1] = path.join(cwd, process.argv[1]);
<add> // make process.argv[1] into a full path
<add> if (!(/^http:\/\//).exec(process.argv[1])) {
<add> process.argv[1] = path.resolve(process.argv[1]);
<ide> }
<ide> // REMOVEME: nextTick should not be necessary. This hack to get
<ide> // test/simple/test-exception-handler2.js working. | 2 |
Ruby | Ruby | move tool path methods to abstractdownloadstrategy | 3e1cc70fb4301a94dbf4c12b4b5a7660efac5f41 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch; end
<ide> def stage; end
<ide> def cached_location; end
<ide> def clear_cache; end
<add>
<add> private
<add>
<add> def xzpath
<add> "#{HOMEBREW_PREFIX}/opt/xz/bin/xz"
<add> end
<add>
<add> def lzippath
<add> "#{HOMEBREW_PREFIX}/opt/lzip/bin/lzip"
<add> end
<add>
<add> def cvspath
<add> @cvspath ||= %W[
<add> /usr/bin/cvs
<add> #{HOMEBREW_PREFIX}/bin/cvs
<add> #{HOMEBREW_PREFIX}/opt/cvs/bin/cvs
<add> #{which("cvs")}
<add> ].find { |p| File.executable? p }
<add> end
<add>
<add> def hgpath
<add> @hgpath ||= %W[
<add> #{which("hg")}
<add> #{HOMEBREW_PREFIX}/bin/hg
<add> #{HOMEBREW_PREFIX}/opt/mercurial/bin/hg
<add> ].find { |p| File.executable? p }
<add> end
<add>
<add> def bzrpath
<add> @bzrpath ||= %W[
<add> #{which("bzr")}
<add> #{HOMEBREW_PREFIX}/bin/bzr
<add> #{HOMEBREW_PREFIX}/opt/bazaar/bin/bzr
<add> ].find { |p| File.executable? p }
<add> end
<add>
<add> def fossilpath
<add> @fossilpath ||= %W[
<add> #{which("fossil")}
<add> #{HOMEBREW_PREFIX}/bin/fossil
<add> #{HOMEBREW_PREFIX}/opt/fossil/bin/fossil
<add> ].find { |p| File.executable? p }
<add> end
<ide> end
<ide>
<ide> class VCSDownloadStrategy < AbstractDownloadStrategy
<ide> def curl(*args)
<ide> super
<ide> end
<ide>
<del> def xzpath
<del> "#{HOMEBREW_PREFIX}/opt/xz/bin/xz"
<del> end
<del>
<del> def lzippath
<del> "#{HOMEBREW_PREFIX}/opt/lzip/bin/lzip"
<del> end
<del>
<ide> def chdir
<ide> entries = Dir['*']
<ide> case entries.length
<ide> def split_url(in_url)
<ide> url=parts.join(':')
<ide> [ mod, url ]
<ide> end
<del>
<del> def cvspath
<del> @path ||= %W[
<del> /usr/bin/cvs
<del> #{HOMEBREW_PREFIX}/bin/cvs
<del> #{HOMEBREW_PREFIX}/opt/cvs/bin/cvs
<del> #{which("cvs")}
<del> ].find { |p| File.executable? p }
<del> end
<ide> end
<ide>
<ide> class MercurialDownloadStrategy < VCSDownloadStrategy
<ide> def clone_repo
<ide> def update
<ide> cached_location.cd { quiet_safe_system hgpath, "pull", "--update" }
<ide> end
<del>
<del> def hgpath
<del> @path ||= %W[
<del> #{which("hg")}
<del> #{HOMEBREW_PREFIX}/bin/hg
<del> #{HOMEBREW_PREFIX}/opt/mercurial/bin/hg
<del> ].find { |p| File.executable? p }
<del> end
<ide> end
<ide>
<ide> class BazaarDownloadStrategy < VCSDownloadStrategy
<ide> def clone_repo
<ide> def update
<ide> cached_location.cd { quiet_safe_system bzrpath, "update" }
<ide> end
<del>
<del> def bzrpath
<del> @path ||= %W[
<del> #{which("bzr")}
<del> #{HOMEBREW_PREFIX}/bin/bzr
<del> ].find { |p| File.executable? p }
<del> end
<ide> end
<ide>
<ide> class FossilDownloadStrategy < VCSDownloadStrategy
<ide> def update
<ide> safe_system fossilpath, "pull", "-R", cached_location
<ide> end
<ide>
<del> def fossilpath
<del> @path ||= %W[
<del> #{which("fossil")}
<del> #{HOMEBREW_PREFIX}/bin/fossil
<del> ].find { |p| File.executable? p }
<del> end
<ide> end
<ide>
<ide> class DownloadStrategyDetector | 1 |
PHP | PHP | fix more strict errors | 87f5b6cf26b1a6efaf6be228bb9f70032f9f0212 | <ide><path>lib/Cake/Network/Email/CakeEmail.php
<ide> protected function _addEmail($varName, $email, $name) {
<ide> }
<ide>
<ide> /**
<del> * Set Subject
<add> * Get/Set Subject.
<ide> *
<del> * @param string $subject
<add> * @param null|string $subject
<ide> * @return mixed
<ide> */
<ide> public function subject($subject = null) {
<ide><path>lib/Cake/Network/Email/SmtpTransport.php
<ide> protected function _smtpSend($data, $checkCode = '250') {
<ide> if (substr($response, -2) !== "\r\n") {
<ide> throw new SocketException(__d('cake_dev', 'SMTP timeout.'));
<ide> }
<del> $response = end(explode("\r\n", rtrim($response, "\r\n")));
<add> $responseLines = explode("\r\n", rtrim($response, "\r\n"));
<add> $response = end($responseLines);
<ide>
<ide> if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
<ide> if ($code[2] === '-') {
<ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php
<ide> public function testReadOnlyCallingQueryAssociationWhenDefined() {
<ide> */
<ide> public function testFieldsUsingMethodCache() {
<ide> $this->testDb->cacheMethods = false;
<del> $this->assertTrue(empty($this->testDb->methodCache['fields']), 'Cache not empty');
<add> DboTestSource::$methodCache = array();
<ide>
<ide> $Article = ClassRegistry::init('Article');
<ide> $this->testDb->fields($Article, null, array('title', 'body', 'published'));
<del> $this->assertTrue(empty($this->testDb->methodCache['fields']), 'Cache not empty');
<add> $this->assertTrue(empty(DboTestSource::$methodCache['fields']), 'Cache not empty');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php
<ide> public function testSubject() {
<ide> $this->CakeEmail->subject(1);
<ide> $this->assertIdentical($this->CakeEmail->subject(), '1');
<ide>
<del> $result = $this->CakeEmail->subject(array('something'));
<del> $this->assertIdentical($this->CakeEmail->subject(), 'Array');
<del> $this->assertIdentical($this->CakeEmail, $result);
<del>
<ide> $this->CakeEmail->subject('هذه رسالة بعنوان طويل مرسل للمستلم');
<ide> $expected = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
<ide> $this->assertIdentical($this->CakeEmail->subject(), $expected);
<ide><path>lib/Cake/Test/test_app/Model/Datasource/Test2OtherSource.php
<ide> public function describe($model) {
<ide> return compact('model');
<ide> }
<ide>
<del> public function listSources() {
<add> public function listSources($data = null) {
<ide> return array('test_source');
<ide> }
<ide>
<del> public function create($model, $fields = array(), $values = array()) {
<add> public function create(Model $model, $fields = null, $values = null) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function read($model, $queryData = array()) {
<add> public function read(Model $model, $queryData = array()) {
<ide> return compact('model', 'queryData');
<ide> }
<ide>
<del> public function update($model, $fields = array(), $values = array()) {
<add> public function update(Model $model, $fields = array(), $values = array()) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function delete($model, $id) {
<add> public function delete(Model $model, $id = null) {
<ide> return compact('model', 'id');
<ide> }
<ide> }
<ide><path>lib/Cake/Test/test_app/Model/Datasource/Test2Source.php
<ide> public function describe($model) {
<ide> return compact('model');
<ide> }
<ide>
<del> public function listSources() {
<add> public function listSources($data = null) {
<ide> return array('test_source');
<ide> }
<ide>
<del> public function create($model, $fields = array(), $values = array()) {
<add> public function create(Model $model, $fields = null, $values = null) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function read($model, $queryData = array()) {
<add> public function read(Model $model, $queryData = array()) {
<ide> return compact('model', 'queryData');
<ide> }
<ide>
<del> public function update($model, $fields = array(), $values = array()) {
<add> public function update(Model $model, $fields = array(), $values = array()) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function delete($model, $id) {
<add> public function delete(Model $model, $id = null) {
<ide> return compact('model', 'id');
<ide> }
<ide> }
<ide><path>lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/test_other_source.php
<ide> public function describe($model) {
<ide> return compact('model');
<ide> }
<ide>
<del> public function listSources() {
<add> public function listSources($data = null) {
<ide> return array('test_source');
<ide> }
<ide>
<del> public function create($model, $fields = array(), $values = array()) {
<add> public function create(Model $model, $fields = null, $values = array()) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function read($model, $queryData = array()) {
<add> public function read(Model $model, $queryData = array()) {
<ide> return compact('model', 'queryData');
<ide> }
<ide>
<del> public function update($model, $fields = array(), $values = array()) {
<add> public function update(Model $model, $fields = array(), $values = array()) {
<ide> return compact('model', 'fields', 'values');
<ide> }
<ide>
<del> public function delete($model, $id) {
<add> public function delete(Model $model, $id = null) {
<ide> return compact('model', 'id');
<ide> }
<ide> } | 7 |
Javascript | Javascript | define printerr() in script string | 22b68042590de93109dbc2a4ddaf78caa24c2306 | <ide><path>lib/internal/v8_prof_processor.js
<ide> scriptFiles.forEach(function(s) {
<ide> script += process.binding('natives')[s] + '\n';
<ide> });
<ide>
<del>// eslint-disable-next-line no-unused-vars
<del>function printErr(err) {
<del> console.error(err);
<del>}
<del>
<ide> const tickArguments = [];
<ide> if (process.platform === 'darwin') {
<ide> tickArguments.push('--mac');
<ide> tickArguments.push.apply(tickArguments, process.argv.slice(1));
<ide> script = `(function(module, require) {
<ide> arguments = ${JSON.stringify(tickArguments)};
<ide> function write (s) { process.stdout.write(s) }
<add> function printErr(err) { console.error(err); }
<ide> ${script}
<ide> })`;
<ide> vm.runInThisContext(script)(module, require); | 1 |
Javascript | Javascript | move guid key init before initmixins | 3f7a1181510c21c3afd87731970e3b79eb2e37b1 | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> // Ember.Object. We only define this separately so that Ember.Set can depend on it
<ide>
<ide>
<del>
<del>var classToString = Ember.Mixin.prototype.toString;
<del>var set = Ember.set, get = Ember.get;
<del>var o_create = Ember.create,
<add>var set = Ember.set, get = Ember.get,
<add> o_create = Ember.create,
<ide> o_defineProperty = Ember.platform.defineProperty,
<ide> a_slice = Array.prototype.slice,
<add> GUID_KEY = Ember.GUID_KEY,
<add> guidFor = Ember.guidFor,
<add> generateGuid = Ember.generateGuid,
<ide> meta = Ember.meta,
<ide> rewatch = Ember.rewatch,
<ide> finishChains = Ember.finishChains,
<del> finishPartial = Ember.Mixin.finishPartial,
<del> reopen = Ember.Mixin.prototype.reopen;
<add> destroy = Ember.destroy,
<add> schedule = Ember.run.schedule,
<add> Mixin = Ember.Mixin,
<add> applyMixin = Mixin._apply,
<add> finishPartial = Mixin.finishPartial,
<add> reopen = Mixin.prototype.reopen,
<add> classToString = Mixin.prototype.toString;
<ide>
<ide> var undefinedDescriptor = {
<ide> configurable: true,
<ide> function makeCtor() {
<ide> if (!wasApplied) {
<ide> Class.proto(); // prepare prototype...
<ide> }
<del> var m = Ember.meta(this);
<add> o_defineProperty(this, GUID_KEY, undefinedDescriptor);
<add> o_defineProperty(this, '_super', undefinedDescriptor);
<add> var m = meta(this);
<ide> m.proto = this;
<ide> if (initMixins) {
<ide> this.reopen.apply(this, initMixins);
<ide> initMixins = null;
<ide> }
<del> o_defineProperty(this, Ember.GUID_KEY, undefinedDescriptor);
<del> o_defineProperty(this, '_super', undefinedDescriptor);
<ide> finishPartial(this, m);
<ide> delete m.proto;
<ide> finishChains(this);
<ide> function makeCtor() {
<ide> Class.toString = classToString;
<ide> Class.willReopen = function() {
<ide> if (wasApplied) {
<del> Class.PrototypeMixin = Ember.Mixin.create(Class.PrototypeMixin);
<add> Class.PrototypeMixin = Mixin.create(Class.PrototypeMixin);
<ide> }
<ide>
<ide> wasApplied = false;
<ide> function makeCtor() {
<ide>
<ide> var CoreObject = makeCtor();
<ide>
<del>CoreObject.PrototypeMixin = Ember.Mixin.create(
<add>CoreObject.PrototypeMixin = Mixin.create(
<ide> /** @scope Ember.CoreObject.prototype */ {
<ide>
<ide> reopen: function() {
<del> Ember.Mixin._apply(this, arguments, true);
<add> applyMixin(this, arguments, true);
<ide> return this;
<ide> },
<ide>
<ide> CoreObject.PrototypeMixin = Ember.Mixin.create(
<ide> if (this.willDestroy) { this.willDestroy(); }
<ide>
<ide> set(this, 'isDestroyed', true);
<del> Ember.run.schedule('destroy', this, this._scheduledDestroy);
<add> schedule('destroy', this, this._scheduledDestroy);
<ide> return this;
<ide> },
<ide>
<ide> CoreObject.PrototypeMixin = Ember.Mixin.create(
<ide> @private
<ide> */
<ide> _scheduledDestroy: function() {
<del> Ember.destroy(this);
<add> destroy(this);
<ide> if (this.didDestroy) { this.didDestroy(); }
<ide> },
<ide>
<ide> CoreObject.PrototypeMixin = Ember.Mixin.create(
<ide> },
<ide>
<ide> toString: function() {
<del> return '<'+this.constructor.toString()+':'+Ember.guidFor(this)+'>';
<add> return '<'+this.constructor.toString()+':'+guidFor(this)+'>';
<ide> }
<ide> });
<ide>
<ide> if (Ember.config.overridePrototypeMixin) {
<ide>
<ide> CoreObject.__super__ = null;
<ide>
<del>var ClassMixin = Ember.Mixin.create(
<add>var ClassMixin = Mixin.create(
<ide> /** @scope Ember.ClassMixin.prototype */ {
<ide>
<ide> ClassMixin: Ember.required(),
<ide> var ClassMixin = Ember.Mixin.create(
<ide>
<ide> extend: function() {
<ide> var Class = makeCtor(), proto;
<del> Class.ClassMixin = Ember.Mixin.create(this.ClassMixin);
<del> Class.PrototypeMixin = Ember.Mixin.create(this.PrototypeMixin);
<add> Class.ClassMixin = Mixin.create(this.ClassMixin);
<add> Class.PrototypeMixin = Mixin.create(this.PrototypeMixin);
<ide>
<ide> Class.ClassMixin.ownerConstructor = Class;
<ide> Class.PrototypeMixin.ownerConstructor = Class;
<ide> var ClassMixin = Ember.Mixin.create(
<ide>
<ide> proto = Class.prototype = o_create(this.prototype);
<ide> proto.constructor = Class;
<del> Ember.generateGuid(proto, 'ember');
<add> generateGuid(proto, 'ember');
<ide> meta(proto).proto = proto; // this will disable observers on prototype
<ide>
<ide> Class.ClassMixin.apply(Class);
<ide> var ClassMixin = Ember.Mixin.create(
<ide>
<ide> reopenClass: function() {
<ide> reopen.apply(this.ClassMixin, arguments);
<del> Ember.Mixin._apply(this, arguments, false);
<add> applyMixin(this, arguments, false);
<ide> return this;
<ide> },
<ide> | 1 |
Python | Python | remove redundant file | ac82ad67980f3fbfe93ace2ee967541410b9ff5a | <ide><path>research/object_detection/dataset_tools/create_ava_tf_record_for_context.py
<del># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del>
<del>r"""Code to download and parse the AVA Actions dataset for TensorFlow models.
<del>
<del>The [AVA Actions data set](
<del>https://research.google.com/ava/index.html)
<del>is a dataset for human action recognition.
<del>
<del>This script downloads the annotations and prepares data from similar annotations
<del>if local video files are available. The video files can be downloaded
<del>from the following website:
<del>https://github.com/cvdfoundation/ava-dataset
<del>
<del>Prior to running this script, please run download_and_preprocess_ava.sh to
<del>download input videos.
<del>
<del>Running this code as a module generates the data set on disk. First, the
<del>required files are downloaded (_download_data) which enables constructing the
<del>label map. Then (in generate_examples), for each split in the data set, the
<del>metadata and image frames are generated from the annotations for each sequence
<del>example (_generate_examples). The data set is written to disk as a set of
<del>numbered TFRecord files.
<del>
<del>Generating the data on disk can take considerable time and disk space.
<del>(Image compression quality is the primary determiner of disk usage.
<del>
<del>If using the Tensorflow Object Detection API, set the input_type field
<del>in the input_reader to TF_SEQUENCE_EXAMPLE.
<del>
<del>This data is structured for per-clip action classification where images is
<del>the sequence of images and labels are a one-hot encoded value. See
<del>as_dataset() for more details.
<del>
<del>Note that the number of videos changes in the data set over time, so it will
<del>likely be necessary to change the expected number of examples.
<del>
<del>The argument video_path_format_string expects a value as such:
<del> "/path/to/videos/{0}"
<del>
<del>"""
<del>
<del>import contextlib
<del>import csv
<del>import os
<del>import random
<del>import sys
<del>import zipfile
<del>import collections
<del>import glob
<del>
<del>from absl import app
<del>from absl import flags
<del>from absl import logging
<del>from six.moves import range
<del>from six.moves import urllib
<del>import tensorflow.compat.v1 as tf
<del>import cv2
<del>import hashlib
<del>
<del>from object_detection.utils import dataset_util
<del>
<del>POSSIBLE_TIMESTAMPS = range(902, 1798)
<del>ANNOTATION_URL = "https://research.google.com/ava/download/ava_v2.2.zip"
<del>SECONDS_TO_MILLI = 1000
<del>FILEPATTERN = "ava_actions_%s_1fps_rgb"
<del>SPLITS = {
<del> "train": {
<del> "shards": 1000,
<del> "examples": 862663,
<del> "csv": '',
<del> "excluded-csv": ''
<del> },
<del> "val": {
<del> "shards": 100,
<del> "examples": 243029,
<del> "csv": '',
<del> "excluded-csv": ''
<del> },
<del> #Test doesn't have ground truth, so TF Records can't be created
<del> "test": {
<del> "shards": 100,
<del> "examples": 0,
<del> "csv": '',
<del> "excluded-csv": ''
<del> }
<del>}
<del>
<del>NUM_CLASSES = 80
<del>
<del>def feature_list_feature(value):
<del> return tf.train.FeatureList(feature=value)
<del>
<del>class Ava(object):
<del> """Generates and loads the AVA Actions 2.2 data set."""
<del>
<del> def __init__(self, path_to_output_dir, path_to_data_download):
<del> if not path_to_output_dir:
<del> raise ValueError("You must supply the path to the data directory.")
<del> self.path_to_data_download = path_to_data_download
<del> self.path_to_output_dir = path_to_output_dir
<del>
<del> def generate_and_write_records(self,
<del> splits_to_process="train,val,test",
<del> video_path_format_string=None,
<del> seconds_per_sequence=10,
<del> hop_between_sequences=10):
<del> """Downloads data and generates sharded TFRecords.
<del>
<del> Downloads the data files, generates metadata, and processes the metadata
<del> with MediaPipe to produce tf.SequenceExamples for training. The resulting
<del> files can be read with as_dataset(). After running this function the
<del> original data files can be deleted.
<del>
<del> Args:
<del> splits_to_process: csv string of which splits to process. Allows providing
<del> a custom CSV with the CSV flag. The original data is still downloaded
<del> to generate the label_map.
<del> video_path_format_string: The format string for the path to local files.
<del> seconds_per_sequence: The length of each sequence, in seconds.
<del> hop_between_sequences: The gap between the centers of
<del> successive sequences.
<del> """
<del> logging.info("Downloading data.")
<del> download_output = self._download_data()
<del> for key in splits_to_process.split(","):
<del> logging.info("Generating examples for split: %s", key)
<del> all_metadata = list(self._generate_examples(
<del> download_output[0][key][0], download_output[0][key][1],
<del> download_output[1], seconds_per_sequence, hop_between_sequences,
<del> video_path_format_string))
<del> logging.info("An example of the metadata: ")
<del> logging.info(all_metadata[0])
<del> random.seed(47)
<del> random.shuffle(all_metadata)
<del> shards = SPLITS[key]["shards"]
<del> shard_names = [os.path.join(
<del> self.path_to_output_dir, FILEPATTERN % key + "-%05d-of-%05d" % (
<del> i, shards)) for i in range(shards)]
<del> writers = [tf.io.TFRecordWriter(shard_name) for shard_name in shard_names]
<del> with _close_on_exit(writers) as writers:
<del> for i, seq_ex in enumerate(all_metadata):
<del> writers[i % len(writers)].write(seq_ex.SerializeToString())
<del> logging.info("Data extraction complete.")
<del>
<del> def _generate_examples(self, annotation_file, excluded_file, label_map,
<del> seconds_per_sequence, hop_between_sequences,
<del> video_path_format_string):
<del> """For each row in the annotation CSV, generates the corresponding
<del> examples. When iterating through frames for a single example, skips
<del> over excluded frames. Generates equal-length sequence examples, each with
<del> length seconds_per_sequence (1 fps) and gaps of hop_between_sequences
<del> frames (and seconds) between them, possible greater due to excluded frames.
<del>
<del> Args:
<del> annotation_file: path to the file of AVA CSV annotations.
<del> excluded_path: path to a CSV file of excluded timestamps for each video.
<del> label_map: an {int: string} label map.
<del> seconds_per_sequence: The number of seconds per example in each example.
<del> hop_between_sequences: The hop between sequences. If less than
<del> seconds_per_sequence, will overlap.
<del> Yields:
<del> Each prepared tf.Example of metadata also containing video frames
<del> """
<del> fieldnames = ["id", "timestamp_seconds", "xmin", "ymin", "xmax", "ymax",
<del> "action_label"]
<del> frame_excluded = {}
<del> # create a sparse, nested map of videos and frame indices.
<del> with open(excluded_file, "r") as excluded:
<del> reader = csv.reader(excluded)
<del> for row in reader:
<del> frame_excluded[(row[0], int(float(row[1])))] = True
<del> with open(annotation_file, "r") as annotations:
<del> reader = csv.DictReader(annotations, fieldnames)
<del> frame_annotations = collections.defaultdict(list)
<del> ids = set()
<del> # aggreggate by video and timestamp:
<del> for row in reader:
<del> ids.add(row["id"])
<del> key = (row["id"], int(float(row["timestamp_seconds"])))
<del> frame_annotations[key].append(row)
<del> # for each video, find aggreggates near each sampled frame.:
<del> logging.info("Generating metadata...")
<del> media_num = 1
<del> for media_id in ids:
<del> logging.info("%d/%d, ignore warnings.\n" % (media_num, len(ids)))
<del> media_num += 1
<del>
<del> filepath = glob.glob(
<del> video_path_format_string.format(media_id) + "*")[0]
<del> filename = filepath.split("/")[-1]
<del> cur_vid = cv2.VideoCapture(filepath)
<del> width = cur_vid.get(cv2.CAP_PROP_FRAME_WIDTH)
<del> height = cur_vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
<del> middle_frame_time = POSSIBLE_TIMESTAMPS[0]
<del> total_non_excluded = 0;
<del> while middle_frame_time < POSSIBLE_TIMESTAMPS[-1]:
<del> if (media_id, middle_frame_time) not in frame_excluded:
<del> total_non_excluded += 1
<del> middle_frame_time += 1
<del>
<del> middle_frame_time = POSSIBLE_TIMESTAMPS[0]
<del> cur_frame_num = 0
<del> while middle_frame_time < POSSIBLE_TIMESTAMPS[-1]:
<del> cur_vid.set(cv2.CAP_PROP_POS_MSEC,
<del> (middle_frame_time) * SECONDS_TO_MILLI)
<del> success, image = cur_vid.read()
<del> success, buffer = cv2.imencode('.jpg', image)
<del>
<del> bufstring = buffer.tostring()
<del>
<del> if (media_id, middle_frame_time) in frame_excluded:
<del> middle_frame_time += 1
<del> logging.info("Ignoring and skipping excluded frame.")
<del> continue
<del>
<del> cur_frame_num += 1
<del> source_id = str(middle_frame_time) + "_" + media_id
<del>
<del> xmins = []
<del> xmaxs = []
<del> ymins = []
<del> ymaxs = []
<del> areas = []
<del> labels = []
<del> label_strings = []
<del> confidences = []
<del> for row in frame_annotations[(media_id, middle_frame_time)]:
<del> if len(row) > 2 and int(row["action_label"]) in label_map:
<del> xmins.append(float(row["xmin"]))
<del> xmaxs.append(float(row["xmax"]))
<del> ymins.append(float(row["ymin"]))
<del> ymaxs.append(float(row["ymax"]))
<del> areas.append(float((xmaxs[-1] - xmins[-1]) *
<del> (ymaxs[-1] - ymins[-1])) / 2)
<del> labels.append(int(row["action_label"]))
<del> label_strings.append(label_map[int(row["action_label"])])
<del> confidences.append(1)
<del> else:
<del> logging.warning("Unknown label: %s", row["action_label"])
<del>
<del> middle_frame_time += 1/3
<del> if abs(middle_frame_time - round(middle_frame_time) < 0.0001):
<del> middle_frame_time = round(middle_frame_time)
<del>
<del> key = hashlib.sha256(bufstring).hexdigest()
<del> date_captured_feature = ("2020-06-17 00:%02d:%02d" % ((middle_frame_time - 900)*3 // 60, (middle_frame_time - 900)*3 % 60))
<del> context_feature_dict = {
<del> 'image/height':
<del> dataset_util.int64_feature(int(height)),
<del> 'image/width':
<del> dataset_util.int64_feature(int(width)),
<del> 'image/format':
<del> dataset_util.bytes_feature('jpeg'.encode('utf8')),
<del> 'image/source_id':
<del> dataset_util.bytes_feature(source_id.encode("utf8")),
<del> 'image/filename':
<del> dataset_util.bytes_feature(source_id.encode("utf8")),
<del> 'image/encoded':
<del> dataset_util.bytes_feature(bufstring),
<del> 'image/key/sha256':
<del> dataset_util.bytes_feature(key.encode('utf8')),
<del> 'image/object/bbox/xmin':
<del> dataset_util.float_list_feature(xmins),
<del> 'image/object/bbox/xmax':
<del> dataset_util.float_list_feature(xmaxs),
<del> 'image/object/bbox/ymin':
<del> dataset_util.float_list_feature(ymins),
<del> 'image/object/bbox/ymax':
<del> dataset_util.float_list_feature(ymaxs),
<del> 'image/object/area':
<del> dataset_util.float_list_feature(areas),
<del> 'image/object/class/label':
<del> dataset_util.int64_list_feature(labels),
<del> 'image/object/class/text':
<del> dataset_util.bytes_list_feature(label_strings),
<del> 'image/location':
<del> dataset_util.bytes_feature(media_id.encode('utf8')),
<del> 'image/date_captured':
<del> dataset_util.bytes_feature(date_captured_feature.encode('utf8')),
<del> 'image/seq_num_frames':
<del> dataset_util.int64_feature(total_non_excluded),
<del> 'image/seq_frame_num':
<del> dataset_util.int64_feature(cur_frame_num),
<del> 'image/seq_id':
<del> dataset_util.bytes_feature(media_id.encode('utf8')),
<del> }
<del>
<del> yield tf.train.Example(
<del> features=tf.train.Features(feature=context_feature_dict))
<del>
<del> cur_vid.release()
<del>
<del> def _download_data(self):
<del> """Downloads and extracts data if not already available."""
<del> if sys.version_info >= (3, 0):
<del> urlretrieve = urllib.request.urlretrieve
<del> else:
<del> urlretrieve = urllib.request.urlretrieve
<del> logging.info("Creating data directory.")
<del> tf.io.gfile.makedirs(self.path_to_data_download)
<del> logging.info("Downloading annotations.")
<del> paths = {}
<del> zip_path = os.path.join(self.path_to_data_download,
<del> ANNOTATION_URL.split("/")[-1])
<del> urlretrieve(ANNOTATION_URL, zip_path)
<del> with zipfile.ZipFile(zip_path, 'r') as zip_ref:
<del> zip_ref.extractall(self.path_to_data_download)
<del> for split in ["train", "test", "val"]:
<del> csv_path = os.path.join(self.path_to_data_download, "ava_%s_v2.2.csv" % split)
<del> excl_name = "ava_%s_excluded_timestamps_v2.2.csv" % split
<del> excluded_csv_path = os.path.join(self.path_to_data_download, excl_name)
<del> SPLITS[split]["csv"] = csv_path
<del> SPLITS[split]["excluded-csv"] = excluded_csv_path
<del> paths[split] = (csv_path, excluded_csv_path)
<del>
<del> label_map = self.get_label_map(os.path.join(self.path_to_data_download, "ava_action_list_v2.2.pbtxt"))
<del>
<del> return paths, label_map
<del>
<del> def get_label_map(self, path):
<del> """Parsess a label map into {integer:string} format."""
<del> label_map = {}
<del> with open(path, "r") as f:
<del> current_id = -1
<del> current_label = ""
<del> for line in f:
<del> if "item {" in line:
<del> current_id = -1
<del> current_label = ""
<del> if "name:" in line:
<del> first_quote = line.find('"') + 1
<del> second_quote = line.find('"', first_quote)
<del> assert second_quote > -1
<del> current_label = line[first_quote:second_quote]
<del> if "id:" in line:
<del> current_id = int(line.split()[1])
<del> if "}" in line:
<del> label_map[current_id] = bytes23(current_label)
<del> logging.info(label_map)
<del> assert len(label_map) == NUM_CLASSES
<del> return label_map
<del>
<del>def bytes23(string):
<del> """Creates a bytes string in either Python 2 or 3."""
<del> if sys.version_info >= (3, 0):
<del> return bytes(string, "utf8")
<del> return bytes(string)
<del>
<del>@contextlib.contextmanager
<del>def _close_on_exit(writers):
<del> """Call close on all writers on exit."""
<del> try:
<del> yield writers
<del> finally:
<del> for writer in writers:
<del> writer.close()
<del>
<del>def main(argv):
<del> if len(argv) > 1:
<del> raise app.UsageError("Too many command-line arguments.")
<del> Ava(flags.FLAGS.path_to_output_dir,
<del> flags.FLAGS.path_to_download_data).generate_and_write_records(
<del> flags.FLAGS.splits_to_process,
<del> flags.FLAGS.video_path_format_string,
<del> flags.FLAGS.seconds_per_sequence,
<del> flags.FLAGS.hop_between_sequences)
<del>
<del>if __name__ == "__main__":
<del> flags.DEFINE_string("path_to_download_data",
<del> "",
<del> "Path to directory to download data to.")
<del> flags.DEFINE_string("path_to_output_dir",
<del> "",
<del> "Path to directory to write data to.")
<del> flags.DEFINE_string("splits_to_process",
<del> "train,val",
<del> "Process these splits. Useful for custom data splits.")
<del> flags.DEFINE_string("video_path_format_string",
<del> None,
<del> "The format string for the path to local video files. "
<del> "Uses the Python string.format() syntax with possible "
<del> "arguments of {video}, {start}, {end}, {label_name}, and "
<del> "{split}, corresponding to columns of the data csvs.")
<del> flags.DEFINE_integer("seconds_per_sequence",
<del> 10,
<del> "The number of seconds per example in each example.")
<del> flags.DEFINE_integer("hop_between_sequences",
<del> 10,
<del> "The hop between sequences. If less than "
<del> "seconds_per_sequence, will overlap.")
<del> app.run(main) | 1 |
Go | Go | add status message for v2 pull | 456f493659d92ef271bc3573c537d10ae5d0847b | <ide><path>graph/pull.go
<ide> type downloadInfo struct {
<ide> }
<ide>
<ide> func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out io.Writer, localName, remoteName, tag string, sf *utils.StreamFormatter, parallel bool) error {
<add> var layersDownloaded bool
<ide> if tag == "" {
<ide> log.Debugf("Pulling tag list from V2 registry for %s", remoteName)
<ide> tags, err := r.GetV2RemoteTags(remoteName, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> for _, t := range tags {
<del> if err := s.pullV2Tag(eng, r, out, localName, remoteName, t, sf, parallel); err != nil {
<add> if downloaded, err := s.pullV2Tag(eng, r, out, localName, remoteName, t, sf, parallel); err != nil {
<ide> return err
<add> } else if downloaded {
<add> layersDownloaded = true
<ide> }
<ide> }
<ide> } else {
<del> if err := s.pullV2Tag(eng, r, out, localName, remoteName, tag, sf, parallel); err != nil {
<add> if downloaded, err := s.pullV2Tag(eng, r, out, localName, remoteName, tag, sf, parallel); err != nil {
<ide> return err
<add> } else if downloaded {
<add> layersDownloaded = true
<ide> }
<ide> }
<ide>
<add> requestedTag := localName
<add> if len(tag) > 0 {
<add> requestedTag = localName + ":" + tag
<add> }
<add> WriteStatus(requestedTag, out, sf, layersDownloaded)
<ide> return nil
<ide> }
<ide>
<del>func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, localName, remoteName, tag string, sf *utils.StreamFormatter, parallel bool) error {
<add>func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, localName, remoteName, tag string, sf *utils.StreamFormatter, parallel bool) (bool, error) {
<ide> log.Debugf("Pulling tag from V2 registry: %q", tag)
<ide> manifestBytes, err := r.GetV2ImageManifest(remoteName, tag, nil)
<ide> if err != nil {
<del> return err
<add> return false, err
<ide> }
<ide>
<ide> manifest, verified, err := s.verifyManifest(eng, manifestBytes)
<ide> if err != nil {
<del> return fmt.Errorf("error verifying manifest: %s", err)
<add> return false, fmt.Errorf("error verifying manifest: %s", err)
<ide> }
<ide>
<ide> if len(manifest.BlobSums) != len(manifest.History) {
<del> return fmt.Errorf("length of history not equal to number of layers")
<add> return false, fmt.Errorf("length of history not equal to number of layers")
<ide> }
<ide>
<ide> if verified {
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide> }
<ide>
<ide> if len(manifest.BlobSums) == 0 {
<del> return fmt.Errorf("no blobSums in manifest")
<add> return false, fmt.Errorf("no blobSums in manifest")
<ide> }
<ide>
<ide> downloads := make([]downloadInfo, len(manifest.BlobSums))
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide>
<ide> img, err := image.NewImgJSON(imgJSON)
<ide> if err != nil {
<del> return fmt.Errorf("failed to parse json: %s", err)
<add> return false, fmt.Errorf("failed to parse json: %s", err)
<ide> }
<ide> downloads[i].img = img
<ide>
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide>
<ide> chunks := strings.SplitN(sumStr, ":", 2)
<ide> if len(chunks) < 2 {
<del> return fmt.Errorf("expected 2 parts in the sumStr, got %#v", chunks)
<add> return false, fmt.Errorf("expected 2 parts in the sumStr, got %#v", chunks)
<ide> }
<ide> sumType, checksum := chunks[0], chunks[1]
<ide> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Pulling fs layer", nil))
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide> } else {
<ide> err := downloadFunc(&downloads[i])
<ide> if err != nil {
<del> return err
<add> return false, err
<ide> }
<ide> }
<ide> }
<ide>
<add> var layersDownloaded bool
<ide> for i := len(downloads) - 1; i >= 0; i-- {
<ide> d := &downloads[i]
<ide> if d.err != nil {
<ide> err := <-d.err
<ide> if err != nil {
<del> return err
<add> return false, err
<ide> }
<ide> }
<ide> if d.downloaded {
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide> err = s.graph.Register(d.img, d.imgJSON,
<ide> utils.ProgressReader(d.tmpFile, int(d.length), out, sf, false, utils.TruncateID(d.img.ID), "Extracting"))
<ide> if err != nil {
<del> return err
<add> return false, err
<ide> }
<ide>
<ide> // FIXME: Pool release here for parallel tag pull (ensures any downloads block until fully extracted)
<ide> }
<ide> out.Write(sf.FormatProgress(utils.TruncateID(d.img.ID), "Pull complete", nil))
<del>
<add> layersDownloaded = true
<ide> } else {
<ide> out.Write(sf.FormatProgress(utils.TruncateID(d.img.ID), "Already exists", nil))
<ide> }
<ide>
<ide> }
<ide>
<ide> if err = s.Set(localName, tag, downloads[0].img.ID, true); err != nil {
<del> return err
<add> return false, err
<ide> }
<ide>
<del> return nil
<add> return layersDownloaded, nil
<ide> } | 1 |
PHP | PHP | fix bug in ironmq connector | 8f80dd1aaa91834c02a963d6b352fc50efd31089 | <ide><path>src/Illuminate/Queue/Connectors/IronConnector.php
<ide> class IronConnector implements ConnectorInterface {
<ide> */
<ide> public function connect(array $config)
<ide> {
<del> $config = array('token' => $config['token'], 'project_id' => $config['project']);
<add> $ironConfig = array('token' => $config['token'], 'project_id' => $config['project']);
<ide>
<del> return new IronQueue(new IronMQ($config), $config['queue']);
<add> return new IronQueue(new IronMQ($ironConfig), $config['queue']);
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Mixed | Python | remove outdated comment | 6e0f2666072fb09a67afa71510cce02b9f3c1aef | <ide><path>README.md
<ide> All the release binaries can be found on [Pypi](https://pypi.org/project/keras/#
<ide> | [2.4](https://github.com/keras-team/keras/releases/tag/2.4.0) | Last stable release of multi-backend Keras | < 2.5
<ide> | 2.5-pre| Pre-release (not formal) for standalone Keras repo | >= 2.5 < 2.6
<ide> | [2.6](https://github.com/keras-team/keras/releases/tag/v2.6.0) | First formal release of standalone Keras. | >= 2.6 < 2.7
<del>| [2.7](https://github.com/keras-team/keras/releases/tag/v2.7.0) | Latest Release | >= 2.7 < 2.8
<add>| [2.7](https://github.com/keras-team/keras/releases/tag/v2.7.0-rc0) | (Upcoming release) | >= 2.7 < 2.8
<ide> | nightly| | tf-nightly
<ide>
<ide> ---
<ide><path>keras/layers/core/dropout.py
<ide> class Dropout(base_layer.BaseRandomLayer):
<ide> """
<ide>
<ide> def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
<del> # Note that the constructor is annotated with
<del> # @no_automatic_dependency_tracking. This is to skip the auto
<del> # tracking of self._random_generator instance, which is an AutoTrackable.
<del> # The backend.RandomGenerator could contain a tf.random.Generator instance
<del> # which will have tf.Variable as the internal state. We want to avoid saving
<del> # that state into model.weights and checkpoints for backward compatibility
<del> # reason. In the meantime, we still need to make them visible to SavedModel
<del> # when it is tracing the tf.function for the `call()`.
<del> # See _list_extra_dependencies_for_serialization below for more details.
<ide> super(Dropout, self).__init__(seed=seed, **kwargs)
<ide> if isinstance(rate, (int, float)) and not 0 <= rate <= 1:
<ide> raise ValueError(f'Invalid value {rate} received for ' | 2 |
Ruby | Ruby | improve string#first and #last performance | 0e2de0e3fdc9a1fc763531b74e9fc49666022ff9 | <ide><path>activesupport/lib/active_support/core_ext/string/access.rb
<ide> def to(position)
<ide> # str.first(0) # => ""
<ide> # str.first(6) # => "hello"
<ide> def first(limit = 1)
<del> ActiveSupport::Deprecation.warn(
<del> "Calling String#first with a negative integer limit " \
<del> "will raise an ArgumentError in Rails 6.1."
<del> ) if limit < 0
<del> if limit == 0
<del> ""
<del> elsif limit >= size
<del> dup
<del> else
<del> to(limit - 1)
<del> end
<add> self[0, limit] || (raise ArgumentError, "negative limit")
<ide> end
<ide>
<ide> # Returns the last character of the string. If a limit is supplied, returns a substring
<ide> def first(limit = 1)
<ide> # str.last(0) # => ""
<ide> # str.last(6) # => "hello"
<ide> def last(limit = 1)
<del> ActiveSupport::Deprecation.warn(
<del> "Calling String#last with a negative integer limit " \
<del> "will raise an ArgumentError in Rails 6.1."
<del> ) if limit < 0
<del> if limit == 0
<del> ""
<del> elsif limit >= size
<del> dup
<del> else
<del> from(-limit)
<del> end
<add> self[[length - limit, 0].max, limit] || (raise ArgumentError, "negative limit")
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> class StringAccessTest < ActiveSupport::TestCase
<ide> assert_not_same different_string, string
<ide> end
<ide>
<del> test "#first with negative Integer is deprecated" do
<del> string = "hello"
<del> message = "Calling String#first with a negative integer limit " \
<del> "will raise an ArgumentError in Rails 6.1."
<del> assert_deprecated(message) do
<del> string.first(-1)
<add> test "#first with Integer returns a non-frozen string" do
<add> string = "he"
<add> (0..string.length + 1).each do |limit|
<add> assert_not string.first(limit).frozen?
<add> end
<add> end
<add>
<add> test "#first with negative Integer raises ArgumentError" do
<add> assert_raise ArgumentError do
<add> "hello".first(-1)
<ide> end
<ide> end
<ide>
<ide> class StringAccessTest < ActiveSupport::TestCase
<ide> assert_not_same different_string, string
<ide> end
<ide>
<del> test "#last with negative Integer is deprecated" do
<del> string = "hello"
<del> message = "Calling String#last with a negative integer limit " \
<del> "will raise an ArgumentError in Rails 6.1."
<del> assert_deprecated(message) do
<del> string.last(-1)
<add> test "#last with Integer returns a non-frozen string" do
<add> string = "he"
<add> (0..string.length + 1).each do |limit|
<add> assert_not string.last(limit).frozen?
<add> end
<add> end
<add>
<add> test "#last with negative Integer raises ArgumentError" do
<add> assert_raise ArgumentError do
<add> "hello".last(-1)
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | use native json.stringify | 35125d25137ac2da13ed1ca3e652ec8f2c945053 | <ide><path>src/JSON.js
<ide> 'use strict';
<ide>
<add>var jsonReplacer = function(key, value) {
<add> var val = value;
<add> if (/^\$+/.test(key)) {
<add> val = undefined;
<add> } else if (isWindow(value)) {
<add> val = '$WINDOW';
<add> } else if (value && document === value) {
<add> val = '$DOCUMENT';
<add> } else if (isScope(value)) {
<add> val = '$SCOPE';
<add> }
<add>
<add> return val;
<add>};
<add>
<ide> /**
<ide> * @ngdoc function
<ide> * @name angular.toJson
<ide> * @returns {string} Jsonified string representing `obj`.
<ide> */
<ide> function toJson(obj, pretty) {
<del> var buf = [];
<del> toJsonArray(buf, obj, pretty ? "\n " : null, []);
<del> return buf.join('');
<add> return JSON.stringify(obj, jsonReplacer, pretty ? ' ' : null);
<ide> }
<ide>
<ide> /**
<ide> function fromJson(json) {
<ide> ? JSON.parse(json)
<ide> : json;
<ide> }
<del>
<del>
<del>function jsonDateToString(date){
<del> if (!date) return date;
<del> var isoString = date.toISOString ? date.toISOString() : '';
<del> return (isoString.length==24)
<del> ? isoString
<del> : padNumber(date.getUTCFullYear(), 4) + '-' +
<del> padNumber(date.getUTCMonth() + 1, 2) + '-' +
<del> padNumber(date.getUTCDate(), 2) + 'T' +
<del> padNumber(date.getUTCHours(), 2) + ':' +
<del> padNumber(date.getUTCMinutes(), 2) + ':' +
<del> padNumber(date.getUTCSeconds(), 2) + '.' +
<del> padNumber(date.getUTCMilliseconds(), 3) + 'Z';
<del>}
<del>
<del>function quoteUnicode(string) {
<del> var chars = ['"'];
<del> for ( var i = 0; i < string.length; i++) {
<del> var code = string.charCodeAt(i);
<del> var ch = string.charAt(i);
<del> switch(ch) {
<del> case '"': chars.push('\\"'); break;
<del> case '\\': chars.push('\\\\'); break;
<del> case '\n': chars.push('\\n'); break;
<del> case '\f': chars.push('\\f'); break;
<del> case '\r': chars.push(ch = '\\r'); break;
<del> case '\t': chars.push(ch = '\\t'); break;
<del> default:
<del> if (32 <= code && code <= 126) {
<del> chars.push(ch);
<del> } else {
<del> var encode = "000" + code.toString(16);
<del> chars.push("\\u" + encode.substring(encode.length - 4));
<del> }
<del> }
<del> }
<del> chars.push('"');
<del> return chars.join('');
<del> }
<del>
<del>
<del>function toJsonArray(buf, obj, pretty, stack) {
<del> if (isObject(obj)) {
<del> if (obj === window) {
<del> buf.push('WINDOW');
<del> return;
<del> }
<del>
<del> if (obj === document) {
<del> buf.push('DOCUMENT');
<del> return;
<del> }
<del>
<del> if (includes(stack, obj)) {
<del> buf.push('RECURSION');
<del> return;
<del> }
<del> stack.push(obj);
<del> }
<del> if (obj === null) {
<del> buf.push('null');
<del> } else if (obj instanceof RegExp) {
<del> buf.push(quoteUnicode(obj.toString()));
<del> } else if (isFunction(obj)) {
<del> return;
<del> } else if (isBoolean(obj)) {
<del> buf.push('' + obj);
<del> } else if (isNumber(obj)) {
<del> if (isNaN(obj)) {
<del> buf.push('null');
<del> } else {
<del> buf.push('' + obj);
<del> }
<del> } else if (isString(obj)) {
<del> return buf.push(quoteUnicode(obj));
<del> } else if (isObject(obj)) {
<del> if (isArray(obj)) {
<del> buf.push("[");
<del> var len = obj.length;
<del> var sep = false;
<del> for(var i=0; i<len; i++) {
<del> var item = obj[i];
<del> if (sep) buf.push(",");
<del> if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) {
<del> buf.push('null');
<del> } else {
<del> toJsonArray(buf, item, pretty, stack);
<del> }
<del> sep = true;
<del> }
<del> buf.push("]");
<del> } else if (isElement(obj)) {
<del> // TODO(misko): maybe in dev mode have a better error reporting?
<del> buf.push('DOM_ELEMENT');
<del> } else if (isDate(obj)) {
<del> buf.push(quoteUnicode(jsonDateToString(obj)));
<del> } else {
<del> buf.push("{");
<del> if (pretty) buf.push(pretty);
<del> var comma = false;
<del> var childPretty = pretty ? pretty + " " : false;
<del> var keys = [];
<del> for(var k in obj) {
<del> if (k!='this' && k!='$parent' && k.substring(0,2) != '$$' && obj.hasOwnProperty(k) && obj[k] !== undefined) {
<del> keys.push(k);
<del> }
<del> }
<del> keys.sort();
<del> for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
<del> var key = keys[keyIndex];
<del> var value = obj[key];
<del> if (!isFunction(value)) {
<del> if (comma) {
<del> buf.push(",");
<del> if (pretty) buf.push(pretty);
<del> }
<del> buf.push(quoteUnicode(key));
<del> buf.push(":");
<del> toJsonArray(buf, value, childPretty, stack);
<del> comma = true;
<del> }
<del> }
<del> buf.push("}");
<del> }
<del> }
<del> if (isObject(obj)) {
<del> stack.pop();
<del> }
<del>}
<ide><path>src/ng/directive/input.js
<ide> function checkboxInputType(scope, element, attr, ctrl) {
<ide> </doc:source>
<ide> <doc:scenario>
<ide> it('should initialize to model', function() {
<del> expect(binding('user')).toEqual('{"last":"visitor","name":"guest"}');
<add> expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
<ide> expect(binding('myForm.userName.$valid')).toEqual('true');
<ide> expect(binding('myForm.$valid')).toEqual('true');
<ide> });
<ide> function checkboxInputType(scope, element, attr, ctrl) {
<ide>
<ide> it('should be valid if empty when min length is set', function() {
<ide> input('user.last').enter('');
<del> expect(binding('user')).toEqual('{"last":"","name":"guest"}');
<add> expect(binding('user')).toEqual('{"name":"guest","last":""}');
<ide> expect(binding('myForm.lastName.$valid')).toEqual('true');
<ide> expect(binding('myForm.$valid')).toEqual('true');
<ide> });
<ide><path>src/ng/filter/filters.js
<ide> function dateFilter($locale) {
<ide> </doc:source>
<ide> <doc:scenario>
<ide> it('should jsonify filtered objects', function() {
<del> expect(binding("{'name':'value'}")).toBe('{\n "name":"value"}');
<add> expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
<ide> });
<ide> </doc:scenario>
<ide> </doc:example>
<ide><path>src/ng/filter/limitTo.js
<ide> }
<ide> </script>
<ide> <div ng-controller="Ctrl">
<del> Limit {{numbers}} to: <input type="integer" ng-model="limit"/>
<del> <p>Output: {{ numbers | limitTo:limit | json }}</p>
<add> Limit {{numbers}} to: <input type="integer" ng-model="limit" ng-model-instant>
<add> <p>Output: {{ numbers | limitTo:limit }}</p>
<ide> </div>
<ide> </doc:source>
<ide> <doc:scenario>
<ide> it('should limit the numer array to first three items', function() {
<ide> expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
<del> expect(binding('numbers | limitTo:limit | json')).toEqual('[1,2,3]');
<add> expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
<ide> });
<ide>
<ide> it('should update the output when -3 is entered', function() {
<ide> input('limit').enter(-3);
<del> expect(binding('numbers | limitTo:limit | json')).toEqual('[7,8,9]');
<add> expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
<ide> });
<ide>
<ide> it('should not exceed the maximum size of input array', function() {
<ide> input('limit').enter(100);
<del> expect(binding('numbers | limitTo:limit | json')).toEqual('[1,2,3,4,5,6,7,8,9]');
<add> expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
<ide> });
<ide> </doc:scenario>
<ide> </doc:example>
<ide><path>test/JsonSpec.js
<ide> describe('json', function() {
<ide>
<ide> describe('fromJson', function() {
<ide>
<del> it('should delegate to native parser', function() {
<add> it('should delegate to JSON.parse', function() {
<ide> var spy = spyOn(JSON, 'parse').andCallThrough();
<ide>
<ide> expect(fromJson('{}')).toEqual({});
<ide> describe('json', function() {
<ide> });
<ide>
<ide>
<del> it('should serialize primitives', function() {
<del> expect(toJson(0/0)).toEqual('null');
<del> expect(toJson(null)).toEqual('null');
<del> expect(toJson(true)).toEqual('true');
<del> expect(toJson(false)).toEqual('false');
<del> expect(toJson(123.45)).toEqual('123.45');
<del> expect(toJson('abc')).toEqual('"abc"');
<del> expect(toJson('a \t \n \r b \\')).toEqual('"a \\t \\n \\r b \\\\"');
<del> });
<del>
<del> it('should not serialize $$properties', function() {
<del> expect(toJson({$$some:'value', 'this':1, '$parent':1}, false)).toEqual('{}');
<del> });
<del>
<del> it('should not serialize this or $parent', function() {
<del> expect(toJson({'this':'value', $parent:'abc'}, false)).toEqual('{}');
<del> });
<add> describe('toJson', function() {
<ide>
<del> it('should serialize strings with escaped characters', function() {
<del> expect(toJson("7\\\"7")).toEqual("\"7\\\\\\\"7\"");
<del> });
<del>
<del> it('should serialize objects', function() {
<del> expect(toJson({a: 1, b: 2})).toEqual('{"a":1,"b":2}');
<del> expect(toJson({a: {b: 2}})).toEqual('{"a":{"b":2}}');
<del> expect(toJson({a: {b: {c: 0}}})).toEqual('{"a":{"b":{"c":0}}}');
<del> expect(toJson({a: {b: 0/0}})).toEqual('{"a":{"b":null}}');
<del> });
<del>
<del> it('should format objects pretty', function() {
<del> expect(toJson({a: 1, b: 2}, true)).toEqual('{\n "a":1,\n "b":2}');
<del> expect(toJson({a: {b: 2}}, true)).toEqual('{\n "a":{\n "b":2}}');
<del> });
<add> it('should delegate to JSON.stringify', function() {
<add> var spy = spyOn(JSON, 'stringify').andCallThrough();
<ide>
<del> it('should serialize array', function() {
<del> expect(toJson([])).toEqual('[]');
<del> expect(toJson([1, 'b'])).toEqual('[1,"b"]');
<del> });
<del>
<del> it('should serialize RegExp', function() {
<del> expect(toJson(/foo/)).toEqual('"/foo/"');
<del> expect(toJson([1, new RegExp('foo')])).toEqual('[1,"/foo/"]');
<del> });
<del>
<del> it('should ignore functions', function() {
<del> expect(toJson([function() {},1])).toEqual('[null,1]');
<del> expect(toJson({a:function() {}})).toEqual('{}');
<del> });
<del>
<del> it('should serialize array with empty items', function() {
<del> var a = [];
<del> a[1] = 'X';
<del> expect(toJson(a)).toEqual('[null,"X"]');
<del> });
<del>
<del> it('should escape unicode', function() {
<del> expect('\u00a0'.length).toEqual(1);
<del> expect(toJson('\u00a0').length).toEqual(8);
<del> expect(fromJson(toJson('\u00a0')).length).toEqual(1);
<del> });
<del>
<del> it('should serialize UTC dates', function() {
<del> var date = new angular.mock.TzDate(-1, '2009-10-09T01:02:03.027Z');
<del> expect(toJson(date)).toEqual('"2009-10-09T01:02:03.027Z"');
<del> });
<del>
<del> it('should prevent recursion', function() {
<del> var obj = {a: 'b'};
<del> obj.recursion = obj;
<del> expect(angular.toJson(obj)).toEqual('{"a":"b","recursion":RECURSION}');
<del> });
<add> expect(toJson({})).toEqual('{}');
<add> expect(spy).toHaveBeenCalled();
<add> });
<ide>
<del> it('should serialize $ properties', function() {
<del> var obj = {$a: 'a'};
<del> expect(angular.toJson(obj)).toEqual('{"$a":"a"}');
<del> });
<ide>
<del> it('should NOT serialize inherited properties', function() {
<del> // This is what native Browser does
<del> var obj = inherit({p:'p'});
<del> obj.a = 'a';
<del> expect(angular.toJson(obj)).toEqual('{"a":"a"}');
<del> });
<add> it('should format objects pretty', function() {
<add> expect(toJson({a: 1, b: 2}, true)).
<add> toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}');
<add> expect(toJson({a: {b: 2}}, true)).
<add> toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}');
<add> });
<ide>
<del> it('should serialize same objects multiple times', function() {
<del> var obj = {a:'b'};
<del> expect(angular.toJson({A:obj, B:obj})).toEqual('{"A":{"a":"b"},"B":{"a":"b"}}');
<del> });
<ide>
<del> it('should not serialize undefined values', function() {
<del> expect(angular.toJson({A:undefined})).toEqual('{}');
<del> });
<add> it('should not serialize properties starting with $', function() {
<add> expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}');
<add> });
<ide>
<del> it('should not serialize $window object', function() {
<del> expect(toJson(window)).toEqual('WINDOW');
<del> });
<ide>
<del> it('should not serialize $document object', function() {
<del> expect(toJson(document)).toEqual('DOCUMENT');
<del> });
<add> it('should not serialize undefined values', function() {
<add> expect(angular.toJson({A:undefined})).toEqual('{}');
<add> });
<ide>
<ide>
<del> describe('string', function() {
<del> it('should quote', function() {
<del> expect(quoteUnicode('a')).toBe('"a"');
<del> expect(quoteUnicode('\\')).toBe('"\\\\"');
<del> expect(quoteUnicode("'a'")).toBe('"\'a\'"');
<del> expect(quoteUnicode('"a"')).toBe('"\\"a\\""');
<del> expect(quoteUnicode('\n\f\r\t')).toBe('"\\n\\f\\r\\t"');
<add> it('should not serialize $window object', function() {
<add> expect(toJson(window)).toEqual('"$WINDOW"');
<ide> });
<ide>
<del> it('should quote slashes', function() {
<del> expect(quoteUnicode("7\\\"7")).toBe('"7\\\\\\\"7"');
<del> });
<ide>
<del> it('should quote unicode', function() {
<del> expect(quoteUnicode('abc\u00A0def')).toBe('"abc\\u00a0def"');
<add> it('should not serialize $document object', function() {
<add> expect(toJson(document)).toEqual('"$DOCUMENT"');
<ide> });
<ide>
<del> });
<ide>
<add> it('should not serialize scope instances', inject(function($rootScope) {
<add> expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
<add> }));
<add> });
<ide> }); | 5 |
Javascript | Javascript | update legacy safari test for github actions | a8b39889f33524ad1f1a0334d3092e3532a8c313 | <ide><path>test/integration/production-nav/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import {
<del> nextBuild,
<del> findPort,
<del> nextStart,
<del> killApp,
<del> waitFor,
<del>} from 'next-test-utils'
<add>import { nextBuild, nextStart, killApp, waitFor } from 'next-test-utils'
<add>import getPort from 'get-port'
<ide> import webdriver from 'next-webdriver'
<ide> import { join } from 'path'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
<ide> describe('Production Usage', () => {
<ide> beforeAll(async () => {
<ide> await nextBuild(appDir)
<del> appPort = await findPort()
<add> // use compatible port: https://www.browserstack.com/question/664
<add> appPort = await getPort({
<add> port: [8080, 8081, 8888, 8899],
<add> })
<ide> app = await nextStart(appDir, appPort)
<ide> })
<ide> afterAll(() => killApp(app))
<ide><path>test/jest-environment.js
<ide> class CustomEnvironment extends NodeEnvironment {
<ide> this.server.close()
<ide> }
<ide> if (this.global.wd) {
<del> await this.global.wd.quit()
<add> try {
<add> await this.global.wd.quit()
<add> } catch (err) {
<add> console.log(`Failed to quit webdriver instance`, err)
<add> }
<ide> }
<ide> // must come after wd.quit()
<ide> if (this.seleniumServer) {
<ide><path>test/lib/next-webdriver.js
<ide> let browser = new Builder()
<ide>
<ide> global.wd = browser
<ide>
<del>/*
<del> # Methods to match
<del>
<del> - elementByCss
<del> - elementsByCss
<del> - waitForElementByCss
<del> - elementByCss.text
<del> - elementByCss.click
<del>*/
<del>
<ide> let initialWindow
<ide> let deviceIP = 'localhost'
<ide>
<ide> export default async (appPort, path, waitHydration = true) => {
<ide> if (!initialWindow) {
<ide> initialWindow = await browser.getWindowHandle()
<ide> }
<del> if (isBrowserStack && deviceIP === 'localhost') {
<add> if (isBrowserStack && deviceIP === 'localhost' && !LEGACY_SAFARI) {
<ide> await getDeviceIP()
<ide> }
<ide> // browser.switchTo().window() fails with `missing field `handle`` | 3 |
Ruby | Ruby | remove unused require | 4b4f5f2a11e5c948cb5636d5b50d22d9d223f1a7 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
<del>require 'ipaddr'
<del>
<ide> module ActiveRecord
<ide> module ConnectionAdapters # :nodoc:
<ide> # The goal of this module is to move Adapter specific column | 1 |
Javascript | Javascript | use $browser.addjs for jsonp | 8a8a2cf4623708b69dba3816e22b01407e338b73 | <ide><path>src/Browser.js
<ide> function Browser(window, document, body, XHR, $log) {
<ide> outstandingRequestCount ++;
<ide> if (lowercase(method) == 'json') {
<ide> var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, '');
<del> var script = jqLite(rawDocument.createElement('script'))
<del> .attr({type: 'text/javascript', src: url.replace('JSON_CALLBACK', callbackId)});
<add> var script = self.addJs(url.replace('JSON_CALLBACK', callbackId));
<ide> window[callbackId] = function(data){
<ide> delete window[callbackId];
<del> script.remove();
<add> body[0].removeChild(script)
<ide> completeOutstandingRequest(callback, 200, data);
<ide> };
<del> body.append(script);
<ide> } else {
<ide> var xhr = new XHR();
<ide> xhr.open(method, url, true);
<ide><path>test/BrowserSpecs.js
<ide> describe('browser', function(){
<ide>
<del> var browser, fakeWindow, xhr, logs, scripts, setTimeoutQueue;
<add> var browser, fakeWindow, xhr, logs, scripts, removedScripts, setTimeoutQueue;
<ide>
<ide> function fakeSetTimeout(fn) {
<ide> setTimeoutQueue.push(fn);
<ide> describe('browser', function(){
<ide> beforeEach(function(){
<ide> setTimeoutQueue = [];
<ide> scripts = [];
<add> removedScripts = [];
<ide> xhr = null;
<ide> fakeWindow = {
<ide> location: {href:"http://server"},
<ide> setTimeout: fakeSetTimeout
<ide> };
<ide>
<del> var fakeBody = {append: function(node){scripts.push(node);}};
<add> var fakeBody = [{appendChild: function(node){scripts.push(node);},
<add> removeChild: function(node){removedScripts.push(node);}}];
<ide>
<ide> var FakeXhr = function(){
<ide> xhr = this;
<ide> describe('browser', function(){
<ide> expect(callback).not.toHaveBeenCalled();
<ide> expect(scripts.length).toEqual(1);
<ide> var script = scripts[0];
<del> script.remove = function(){
<del> log += 'remove();';
<del> };
<del> var url = script.attr('src').split('?cb=');
<add> var url = script.src.split('?cb=');
<ide> expect(url[0]).toEqual('http://example.org/path');
<ide> expect(typeof fakeWindow[url[1]]).toEqual($function);
<ide> fakeWindow[url[1]]('data');
<ide> expect(callback).toHaveBeenCalled();
<del> expect(log).toEqual('remove();200:data;');
<add> expect(log).toEqual('200:data;');
<add> expect(scripts).toEqual(removedScripts);
<ide> expect(fakeWindow[url[1]]).toBeUndefined();
<ide> });
<ide> }); | 2 |
Python | Python | set version to 2.1.0a7 | e0c91a4c8d3b182683df8176356055edda4d883c | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a7.dev8"
<add>__version__ = "2.1.0a7"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI"
<ide> __email__ = "contact@explosion.ai"
<ide> __license__ = "MIT"
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Python | Python | fix mypy errors for qubole provider. | 7d84196519fcdbf96204d754d95c4dbca1ba9121 | <ide><path>airflow/providers/qubole/hooks/qubole.py
<ide> import os
<ide> import pathlib
<ide> import time
<del>from typing import Dict, List, Tuple
<add>from typing import Dict, List, Optional, Tuple
<ide>
<ide> from qds_sdk.commands import (
<ide> Command,
<ide> def __init__(self, *args, **kwargs) -> None:
<ide> self.dag_id = kwargs['dag'].dag_id
<ide> self.kwargs = kwargs
<ide> self.cls = COMMAND_CLASSES[self.kwargs['command_type']]
<del> self.cmd = None
<add> self.cmd: Optional[Command] = None
<ide> self.task_instance = None
<ide>
<ide> @staticmethod
<ide><path>airflow/providers/qubole/hooks/qubole_check.py
<ide> from qds_sdk.commands import Command
<ide>
<ide> from airflow.exceptions import AirflowException
<add>from airflow.hooks.dbapi import DbApiHook
<ide> from airflow.providers.qubole.hooks.qubole import QuboleHook
<ide>
<ide> log = logging.getLogger(__name__)
<ide> def parse_first_row(row_list) -> List[Union[bool, float, int, str]]:
<ide> return record_list
<ide>
<ide>
<del>class QuboleCheckHook(QuboleHook):
<add>class QuboleCheckHook(QuboleHook, DbApiHook):
<ide> """Qubole check hook"""
<ide>
<ide> def __init__(self, context, *args, **kwargs) -> None:
<ide><path>airflow/providers/qubole/operators/qubole_check.py
<ide> class _QuboleCheckOperatorMixin:
<ide> """This is a Mixin for Qubole related check operators"""
<ide>
<add> kwargs: dict
<add> results_parser_callable: Optional[Callable]
<add>
<ide> def execute(self, context=None) -> None:
<ide> """Execute a check operation against Qubole"""
<ide> try:
<ide> self._hook_context = context
<del> super().execute(context=context)
<add> super().execute(context=context) # type: ignore[misc]
<ide> except AirflowException as e:
<ide> handle_airflow_exception(e, self.get_hook())
<ide>
<ide> def get_db_hook(self) -> QuboleCheckHook:
<ide> """Get QuboleCheckHook"""
<ide> return self.get_hook()
<ide>
<del> # this overwrite the original QuboleOperator.get_hook() which returns a QuboleHook.
<ide> def get_hook(self) -> QuboleCheckHook:
<del> """Reinitialising the hook, as some template fields might have changed"""
<add> """
<add> Reinitialising the hook, as some template fields might have changed
<add> This method overwrites the original QuboleOperator.get_hook() which returns a QuboleHook.
<add> """
<ide> return QuboleCheckHook(
<ide> context=self._hook_context, results_parser_callable=self.results_parser_callable, **self.kwargs
<ide> )
<ide> class QuboleCheckOperator(_QuboleCheckOperatorMixin, SQLCheckOperator, QuboleOpe
<ide> ui_fgcolor = '#000'
<ide>
<ide> def __init__(
<del> self, *, qubole_conn_id: str = "qubole_default", results_parser_callable: Callable = None, **kwargs
<add> self,
<add> *,
<add> qubole_conn_id: str = "qubole_default",
<add> results_parser_callable: Optional[Callable] = None,
<add> **kwargs,
<ide> ) -> None:
<ide> sql = get_sql_from_qbol_cmd(kwargs)
<ide> kwargs.pop('sql', None)
<ide> def __init__(
<ide> *,
<ide> pass_value: Union[str, int, float],
<ide> tolerance: Optional[Union[int, float]] = None,
<del> results_parser_callable: Callable = None,
<add> results_parser_callable: Optional[Callable] = None,
<ide> qubole_conn_id: str = "qubole_default",
<ide> **kwargs,
<ide> ) -> None: | 3 |
PHP | PHP | add tiny/small int to sqlserver | a4cdd69c993731808bac5b1fc32d4c9072c9e187 | <ide><path>src/Database/Schema/SqlserverSchema.php
<ide> protected function _convertColumn($col, $length = null, $precision = null, $scal
<ide> return ['type' => 'timestamp', 'length' => null];
<ide> }
<ide>
<add> if ($col === 'tinyint') {
<add> return ['type' => 'smallint', 'length' => $precision ?: 3];
<add> }
<add> if ($col === 'smallint') {
<add> return ['type' => 'smallint', 'length' => $precision ?: 5];
<add> }
<ide> if ($col === 'int' || $col === 'integer') {
<ide> return ['type' => 'integer', 'length' => $precision ?: 10];
<ide> }
<ide> if ($col === 'bigint') {
<ide> return ['type' => 'biginteger', 'length' => $precision ?: 20];
<ide> }
<del> if ($col === 'smallint') {
<del> return ['type' => 'integer', 'length' => $precision ?: 5];
<del> }
<del> if ($col === 'tinyint') {
<del> return ['type' => 'integer', 'length' => $precision ?: 3];
<del> }
<ide> if ($col === 'bit') {
<ide> return ['type' => 'boolean', 'length' => null];
<ide> }
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $data = $schema->column($name);
<ide> $out = $this->_driver->quoteIdentifier($name);
<ide> $typeMap = [
<add> 'tinyint' => ' TINYINT',
<add> 'smallint' => ' SMALLINT',
<ide> 'integer' => ' INTEGER',
<ide> 'biginteger' => ' BIGINT',
<ide> 'boolean' => ' BIT',
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public static function convertColumnProvider()
<ide> null,
<ide> ['type' => 'time', 'length' => null]
<ide> ],
<add> [
<add> 'TINYINT',
<add> null,
<add> 4,
<add> null,
<add> ['type' => 'tinyint', 'length' => 4]
<add> ],
<ide> [
<ide> 'SMALLINT',
<ide> null,
<ide> 4,
<ide> null,
<del> ['type' => 'integer', 'length' => 4]
<add> ['type' => 'smallint', 'length' => 4]
<ide> ],
<ide> [
<ide> 'INTEGER',
<ide> public static function columnSqlProvider()
<ide> '[body] NVARCHAR(MAX) COLLATE Japanese_Unicode_CI_AI NOT NULL'
<ide> ],
<ide> // Integers
<add> [
<add> 'post_id',
<add> ['type' => 'smallint', 'length' => 11],
<add> '[post_id] SMALLINT'
<add> ],
<add> [
<add> 'post_id',
<add> ['type' => 'tinyint', 'length' => 11],
<add> '[post_id] TINYINT'
<add> ],
<ide> [
<ide> 'post_id',
<ide> ['type' => 'integer', 'length' => 11], | 2 |
Python | Python | remove double space in the swap plugin | 9cc3f9a19631adc8d98c2e41a06d3cc2a04a2578 | <ide><path>glances/plugins/glances_memswap.py
<ide> def msg_curse(self, args=None):
<ide>
<ide> # Build the string message
<ide> # Header
<del> msg = '{} '.format('SWAP')
<add> msg = '{}'.format('SWAP')
<ide> ret.append(self.curse_add_line(msg, "TITLE"))
<del> msg = ' {:2}'.format(self.trend_msg(self.get_trend('percent')))
<add> msg = ' {:3}'.format(self.trend_msg(self.get_trend('percent')))
<ide> ret.append(self.curse_add_line(msg))
<ide> # Percent memory usage
<ide> msg = '{:>6.1%}'.format(self.stats['percent'] / 100) | 1 |
Go | Go | fix -link parsing | 009024ad6439fad28ab3a9d8db6b6844bfbba8c9 | <ide><path>commands.go
<ide> func (opts AttachOpts) Set(val string) error {
<ide> // LinkOpts stores arguments to `docker run -link`
<ide> type LinkOpts []string
<ide>
<del>func (link LinkOpts) String() string { return fmt.Sprintf("%v", []string(link)) }
<del>func (link LinkOpts) Set(val string) error {
<add>func (link *LinkOpts) String() string { return fmt.Sprintf("%v", []string(*link)) }
<add>func (link *LinkOpts) Set(val string) error {
<ide> if _, err := parseLink(val); err != nil {
<ide> return err
<ide> }
<add> *link = append(*link, val)
<ide> return nil
<ide> }
<ide>
<ide> func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
<ide>
<ide> cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.")
<ide> cmd.Var(flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
<del> cmd.Var(flLinks, "link", "Add link to another container (name:alias)")
<add> cmd.Var(&flLinks, "link", "Add link to another container (name:alias)")
<ide>
<ide> cmd.Var(&flPublish, "p", fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", PortSpecTemplateFormat))
<ide> cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host") | 1 |
Python | Python | fix variable sharing issue with nonneg constraint | 5d2f3101aeec10b0ef14a4d09a32479114e814c5 | <ide><path>keras/constraints.py
<ide> def get_config(self):
<ide>
<ide> class NonNeg(Constraint):
<ide> def __call__(self, p):
<del> p *= T.ge(p, 0)
<add> p = theano.shared(p)
<add> p *= T.ge(p, 0.)
<ide> return p
<ide>
<ide> | 1 |
Ruby | Ruby | remove other old compatibility constants | 1ae9e60b8a369f004d001e885ca71cb0ade2be80 | <ide><path>actionpack/lib/action_controller/metal/compatibility.rb
<ide> module Compatibility
<ide>
<ide> # Temporary hax
<ide> included do
<del> ::ActionController::UnknownAction = ::AbstractController::ActionNotFound
<del> ::ActionController::DoubleRenderError = ::AbstractController::DoubleRenderError
<del>
<ide> # ROUTES TODO: This should be handled by a middleware and route generation
<ide> # should be able to handle SCRIPT_NAME
<ide> self.config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
<ide><path>actionpack/lib/action_controller/metal/exceptions.rb
<ide> def initialize(message = nil)
<ide>
<ide> class UnknownHttpMethod < ActionControllerError #:nodoc:
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>actionpack/test/controller/base_test.rb
<ide> def test_method_missing_should_recieve_symbol
<ide>
<ide> def test_get_on_hidden_should_fail
<ide> use_controller NonEmptyController
<del> assert_raise(ActionController::UnknownAction) { get :hidden_action }
<del> assert_raise(ActionController::UnknownAction) { get :another_hidden_action }
<add> assert_raise(AbstractController::ActionNotFound) { get :hidden_action }
<add> assert_raise(AbstractController::ActionNotFound) { get :another_hidden_action }
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/controller/render_test.rb
<ide> def conditional_hello
<ide>
<ide> def conditional_hello_with_record
<ide> record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123")
<del>
<add>
<ide> if stale?(record)
<ide> render :action => 'hello_world'
<ide> end
<ide> def test_render_text_with_resource
<ide>
<ide> # :ported:
<ide> def test_attempt_to_access_object_method
<del> assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
<add> assert_raise(AbstractController::ActionNotFound, "No action responded to [clone]") { get :clone }
<ide> end
<ide>
<ide> # :ported:
<ide> def test_private_methods
<del> assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout }
<add> assert_raise(AbstractController::ActionNotFound, "No action responded to [determine_layout]") { get :determine_layout }
<ide> end
<ide>
<ide> # :ported:
<ide> def test_render_with_filters
<ide>
<ide> # :ported:
<ide> def test_double_render
<del> assert_raise(ActionController::DoubleRenderError) { get :double_render }
<add> assert_raise(AbstractController::DoubleRenderError) { get :double_render }
<ide> end
<ide>
<ide> def test_double_redirect
<del> assert_raise(ActionController::DoubleRenderError) { get :double_redirect }
<add> assert_raise(AbstractController::DoubleRenderError) { get :double_redirect }
<ide> end
<ide>
<ide> def test_render_and_redirect
<del> assert_raise(ActionController::DoubleRenderError) { get :render_and_redirect }
<add> assert_raise(AbstractController::DoubleRenderError) { get :render_and_redirect }
<ide> end
<ide>
<ide> # specify the one exception to double render rule - render_to_string followed by render
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb
<ide> def call(env)
<ide> when "/pass"
<ide> [404, { "X-Cascade" => "pass" }, self]
<ide> when "/not_found"
<del> raise ActionController::UnknownAction
<add> raise AbstractController::ActionNotFound
<ide> when "/runtime_error"
<ide> raise RuntimeError
<ide> when "/method_not_allowed"
<ide> def call(env)
<ide>
<ide> get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
<ide> assert_response 404
<del> assert_match(/#{ActionController::UnknownAction.name}/, body)
<add> assert_match(/#{AbstractController::ActionNotFound.name}/, body)
<ide>
<ide> get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
<ide> assert_response 405
<ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> def call(env)
<ide> req = ActionDispatch::Request.new(env)
<ide> case req.path
<ide> when "/not_found"
<del> raise ActionController::UnknownAction
<add> raise AbstractController::ActionNotFound
<ide> when "/method_not_allowed"
<ide> raise ActionController::MethodNotAllowed
<ide> when "/not_found_original_exception" | 6 |
Python | Python | fix message when soft timeout exceeded | 2d5996484c70d1385707b73ed5517b6b1b58a2bf | <ide><path>celery/worker/request.py
<ide> def on_timeout(self, soft, timeout):
<ide> task_ready(self)
<ide> if soft:
<ide> warn('Soft time limit (%ss) exceeded for %s[%s]',
<del> timeout, self.name, self.id)
<del> exc = SoftTimeLimitExceeded(timeout)
<add> soft, self.name, self.id)
<add> exc = SoftTimeLimitExceeded(soft)
<ide> else:
<ide> error('Hard time limit (%ss) exceeded for %s[%s]',
<ide> timeout, self.name, self.id) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.