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 |
|---|---|---|---|---|---|
Text | Text | fix typo in issue template | c791f6312b092678c2a152d0605e49c26831cb05 | <ide><path>.github/ISSUE_TEMPLATE/feature-request.md
<ide> about: Suggest a new feature for Flask
<ide>
<ide> <!--
<ide> Replace this comment with a description of what the feature should do.
<del>Include details such as links relevant specs or previous discussions.
<add>Include details such as links to relevant specs or previous discussions.
<ide> -->
<ide>
<ide> <!-- | 1 |
PHP | PHP | fix trailing / present when extensions were used | e1db220414569e78758f97fa95dbdbf2e8acb3fd | <ide><path>lib/Cake/Routing/Route/Route.php
<ide> protected function _writeUrl($params, $pass = array(), $query = array()) {
<ide> $out
<ide> );
<ide> }
<add> if (!empty($params['_ext']) || !empty($query)) {
<add> $out = rtrim($out, '/');
<add> }
<ide> if (!empty($params['_ext'])) {
<ide> $out .= '.' . $params['_ext'];
<ide> }
<ide> if (!empty($query)) {
<del> $out = rtrim($out, '/');
<ide> $out .= '?' . http_build_query($query);
<ide> }
<ide> return $out;
<ide><path>lib/Cake/Test/TestCase/Routing/Route/RouteTest.php
<ide> public function testMatchWithExtension() {
<ide> '_ext' => 'json'
<ide> ));
<ide> $this->assertEquals('/posts/index.json', $result);
<add>
<add> $route = new Route('/:controller/:action/*');
<add> $result = $route->match(array(
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> '_ext' => 'json',
<add> ));
<add> $this->assertEquals('/posts/index.json', $result);
<add>
<add> $result = $route->match(array(
<add> 'controller' => 'posts',
<add> 'action' => 'view',
<add> 1,
<add> '_ext' => 'json',
<add> ));
<add> $this->assertEquals('/posts/view/1.json', $result);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | fix a warning typo | 9065e02d66a86466d687a888c78710728cff652b | <ide><path>packages/react-native-renderer/src/ReactNativeFiberInspector.js
<ide> if (__DEV__) {
<ide> );
<ide> } else {
<ide> console.error(
<del> 'getInspectorDataForViewAtPoint expects to receieve a host component',
<add> 'getInspectorDataForViewAtPoint expects to receive a host component',
<ide> );
<ide>
<ide> return; | 1 |
Ruby | Ruby | fix copy button for irb code examples [ci-skip] | c1c45600012f17632d4e74e3564675d1133b283b | <ide><path>guides/rails_guides/markdown/renderer.rb
<ide> def lexer_language(code_type)
<ide> end
<ide>
<ide> def clipboard_content(code, language)
<del> if language == "bash"
<del> prompt_regexp = /^\$ /
<del> code = code.split("\n").
<del> select { |line| line =~ prompt_regexp }.
<del> map { |line| line.gsub(prompt_regexp, "") }.
<del> join("\n")
<add> prompt_regexp =
<add> case language
<add> when "bash"
<add> /^\$ /
<add> when "irb"
<add> /^irb.*?> /
<add> end
<add>
<add> if prompt_regexp
<add> code = code.lines.grep(prompt_regexp).join.gsub(prompt_regexp, "")
<ide> end
<add>
<ide> ERB::Util.h(code)
<ide> end
<ide> | 1 |
Ruby | Ruby | guess system xquartz version when mdfind fails | 7a4facae2fc4468e2bc80c847ede1e51a1ed6230 | <ide><path>Library/Homebrew/macos/xquartz.rb
<ide> def version
<ide> path = MacOS.app_with_bundle_id(FORGE_BUNDLE_ID) || MacOS.app_with_bundle_id(APPLE_BUNDLE_ID)
<ide> if not path.nil? and path.exist?
<ide> `mdls -raw -name kMDItemVersion "#{path}" 2>/dev/null`.strip
<add> elsif prefix.to_s == "/usr/X11"
<add> # Some users disable Spotlight indexing. If we're working with the
<add> # system X11 distribution, we can't get the version from pkgutil, so
<add> # just use the expected version.
<add> case MacOS.version
<add> when 10.5 then "2.1.6"
<add> when 10.6 then "2.3.6"
<add> when 10.7 then "2.6.3"
<add> else :dunno
<add> end
<ide> else
<del> # Some users disable Spotlight indexing. Try to find it via pkgutil
<add> # Finally, try to find it via pkgutil. This is slow, and only works
<add> # for the upstream XQuartz package, so use it as a last resort.
<ide> MacOS.pkgutil_info(FORGE_PKG_ID) =~ /version: (\d\.\d\.\d).+$/ and $1
<ide> end
<ide> end | 1 |
Ruby | Ruby | remove indexer class from rails guide generator | 0589fe4c3a33ed868e6f10ab7e9f94476a4e48fe | <ide><path>guides/rails_guides/generator.rb
<ide> require "action_view"
<ide>
<ide> require "rails_guides/markdown"
<del>require "rails_guides/indexer"
<ide> require "rails_guides/helpers"
<ide> require "rails_guides/levenshtein"
<ide>
<ide><path>guides/rails_guides/indexer.rb
<del># frozen_string_literal: true
<del>
<del>require "active_support/core_ext/object/blank"
<del>require "active_support/core_ext/string/inflections"
<del>
<del>module RailsGuides
<del> class Indexer
<del> attr_reader :body, :result, :warnings, :level_hash
<del>
<del> def initialize(body, warnings)
<del> @body = body
<del> @result = @body.dup
<del> @warnings = warnings
<del> end
<del>
<del> def index
<del> @level_hash = process(body)
<del> end
<del>
<del> private
<del> def process(string, current_level = 3, counters = [1])
<del> s = StringScanner.new(string)
<del>
<del> level_hash = {}
<del>
<del> while !s.eos?
<del> re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$}
<del> s.match?(re)
<del> if matched = s.matched
<del> matched =~ re
<del> level, idx, title = $1.to_i, $2, $3.strip
<del>
<del> if level < current_level
<del> # This is needed. Go figure.
<del> return level_hash
<del> elsif level == current_level
<del> index = counters.join(".")
<del> idx ||= "#" + title_to_idx(title)
<del>
<del> raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}")
<del>
<del> key = {
<del> title: title,
<del> id: idx
<del> }
<del> # Recurse
<del> counters << 1
<del> level_hash[key] = process(s.post_match, current_level + 1, counters)
<del> counters.pop
<del>
<del> # Increment the current level
<del> last = counters.pop
<del> counters << last + 1
<del> end
<del> end
<del> s.getch
<del> end
<del> level_hash
<del> end
<del>
<del> def title_to_idx(title)
<del> idx = title.strip.parameterize.sub(/^\d+/, "")
<del> if warnings && idx.blank?
<del> puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)"
<del> end
<del> idx
<del> end
<del> end
<del>end | 2 |
Javascript | Javascript | remind the developer to destroy their intervals | 277a5ea05d50fb27243b98570c3ca9394b31e935 | <ide><path>src/ng/interval.js
<ide> function $IntervalProvider() {
<ide> * In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
<ide> * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
<ide> * time.
<add> *
<add> * <div class="alert alert-warning">
<add> * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
<add> * with them. In particular they are not automatically destroyed when a controller's scope or a
<add> * directive's element are destroyed.
<add> * You should take this into consideration and make sure to always cancel the interval at the
<add> * appropriate moment. See the example below for more details on how and when to do this.
<add> * </div>
<ide> *
<ide> * @param {function()} fn A function that should be called repeatedly.
<ide> * @param {number} delay Number of milliseconds between each function call.
<ide> function $IntervalProvider() {
<ide> $scope.blood_1 = $scope.blood_1 - 3;
<ide> $scope.blood_2 = $scope.blood_2 - 4;
<ide> } else {
<del> $interval.cancel(stop);
<add> $scope.stopFight();
<ide> }
<ide> }, 100);
<ide> };
<ide>
<ide> $scope.stopFight = function() {
<del> $interval.cancel(stop);
<del> stop = undefined;
<add> if (angular.isDefined(stop)) {
<add> $interval.cancel(stop);
<add> stop = undefined;
<add> }
<ide> };
<ide>
<ide> $scope.resetFight = function() {
<ide> $scope.blood_1 = 100;
<ide> $scope.blood_2 = 120;
<ide> }
<add>
<add> $scope.$on('$destroy', function() {
<add> // Make sure that the interval is destroyed too
<add> $scope.stopFight();
<add> });
<ide> }
<ide>
<ide> angular.module('time', []) | 1 |
Python | Python | add feature class | 0cc169fcd6c286955db6d36216e492fcc2ef590c | <ide><path>libcloud/base.py
<ide> import hashlib
<ide> from pipes import quote as pquote
<ide>
<add>class Features(object):
<add> AUTH_SSH_KEY = 1
<add> AUTH_PASSWORD = 2
<add>
<ide> class Node(object):
<ide> """
<ide> A Base Node class to derive from.
<ide> def list_sizes(self):
<ide>
<ide> def list_locations(self):
<ide> raise NotImplementedError, 'list_locations not implemented for this driver'
<add>
<add> def has_feature(self, feature):
<add> return False | 1 |
Text | Text | add doc cleaner to menu | bf95f0a1dd41863b81adc3eda302b0389ad3f9e4 | <ide><path>website/docs/api/pipeline-functions.md
<ide> menu:
<ide> - ['merge_entities', 'merge_entities']
<ide> - ['merge_subtokens', 'merge_subtokens']
<ide> - ['token_splitter', 'token_splitter']
<add> - ['doc_cleaner', 'doc_cleaner']
<ide> ---
<ide>
<ide> ## merge_noun_chunks {#merge_noun_chunks tag="function"} | 1 |
Ruby | Ruby | remove database specific json types | 2568414f49cc74522569941004104289d0175e72 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def binary_to_sql(limit) # :nodoc:
<ide> end
<ide> end
<ide>
<del> class MysqlJson < Type::Json # :nodoc:
<del> end
<del>
<ide> class MysqlString < Type::String # :nodoc:
<ide> def serialize(value)
<ide> case value
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
<ide> require_relative "oid/enum"
<ide> require_relative "oid/hstore"
<ide> require_relative "oid/inet"
<del>require_relative "oid/json"
<ide> require_relative "oid/jsonb"
<ide> require_relative "oid/money"
<ide> require_relative "oid/oid"
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/json.rb
<del>module ActiveRecord
<del> module ConnectionAdapters
<del> module PostgreSQL
<del> module OID # :nodoc:
<del> class Json < Type::Json # :nodoc:
<del> end
<del> end
<del> end
<del> end
<del>end | 3 |
Ruby | Ruby | avoid unnecessary allocations/calls | 0488d0021190970c894b30bd2b4b05fbeaa75f83 | <ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def delete_records(records, method)
<ide> if scope.klass.primary_key
<ide> count = scope.destroy_all.length
<ide> else
<del> scope.to_a.each do |record|
<add> scope.each do |record|
<ide> record._run_destroy_callbacks
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def []=(sql, key)
<ide> end
<ide>
<ide> def clear
<del> cache.values.each do |hash|
<add> cache.each_value do |hash|
<ide> hash[:stmt].close
<ide> end
<ide> cache.clear
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def []=(sql, key)
<ide> end
<ide>
<ide> def clear
<del> cache.values.each do |hash|
<add> cache.each_value do |hash|
<ide> dealloc hash[:stmt]
<ide> end
<ide> cache.clear
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def table_rows
<ide> model_class
<ide> end
<ide>
<del> reflection_class._reflections.values.each do |association|
<add> reflection_class._reflections.each_value do |association|
<ide> case association.macro
<ide> when :belongs_to
<ide> # Do not replace association name with association foreign key if they are named the same
<ide><path>activesupport/lib/active_support/dependencies/autoload.rb
<ide> def eager_autoload
<ide> end
<ide>
<ide> def eager_load!
<del> @_autoloads.values.each { |file| require file }
<add> @_autoloads.each_value { |file| require file }
<ide> end
<ide>
<ide> def autoloads | 5 |
PHP | PHP | remove extra newline | f2eea49dec2d44d8fca51fc4e7547494fc0c211e | <ide><path>src/Network/CorsBuilder.php
<ide> */
<ide> namespace Cake\Network;
<ide>
<del>
<ide> /**
<ide> * A builder object that assists in defining Cross Origin Request related
<ide> * headers. | 1 |
Java | Java | fix broken javadoc link in @testpropertysource | 2963fd9e5a8f01eb365469b50d443d56fc7a8ad0 | <ide><path>spring-test/src/main/java/org/springframework/test/context/TestPropertySource.java
<ide> *
<ide> * <h3>Precedence</h3>
<ide> * <p>Properties declared via this attribute have higher precedence than
<del> * properties loaded from resource {@link locations}.
<add> * properties loaded from resource {@link #locations}.
<ide> *
<ide> * <p>This attribute may be used in conjunction with {@link #value}
<ide> * <em>or</em> {@link #locations}. | 1 |
Text | Text | add video link of mit opencourseware. | 9e84b34d4f79f2b01524f913928163fd74690ca6 | <ide><path>guide/english/algorithms/greedy-algorithms/index.md
<ide> Greedy Algorithms help us solve a lot of different kinds of problems. Stay tuned
<ide> <a href="https://www.youtube.com/watch?v=poWB2UCuozA" target="_blank">
<ide> <img src="http://img.youtube.com/vi/poWB2UCuozA/0.jpg" alt="Greedy Problems" width="240" height="180" border="10" />
<ide> </a>
<add>
<add><a href="https://www.youtube.com/watch?v=tKwnms5iRBU" target="_blank">
<add> <img src="http://img.youtube.com/vi/tKwnms5iRBU/0.jpg" alt="Greedy Problems" width="240" height="180" border="10" />
<add></a>
<add>
<add> | 1 |
Python | Python | fix a bug in run_glue.py | 059bb258174319ef1ade3d7179889dd99b1cfb4e | <ide><path>examples/text-classification/run_glue.py
<ide> def main():
<ide> if (
<ide> model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
<ide> and data_args.task_name is not None
<del> and is_regression
<add> and not is_regression
<ide> ):
<ide> # Some have all caps in their config, some don't.
<ide> label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} | 1 |
PHP | PHP | use string functions instead of splfileinfo | 42ca164561cb69a9a0910c347670881921440ccd | <ide><path>src/Console/CommandScanner.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Filesystem\Filesystem;
<ide> use Cake\Utility\Inflector;
<del>use SplFileInfo;
<ide>
<ide> /**
<ide> * Used by CommandCollection and CommandTask to scan the filesystem
<ide> public function scanCore(): array
<ide> protected function inflectCommandNames(array $commands): array
<ide> {
<ide> foreach ($commands as $i => $command) {
<del> $file = new SplFileInfo($command['file']);
<del> $file = $file->getFilename();
<del> $name = Inflector::underscore(preg_replace('/(Shell|Command)\.php$/', '', $file));
<add> $file = basename($command['file'], '.php');
<add> $name = Inflector::underscore(preg_replace('/(Shell|Command)$/', '', $file));
<ide> //if names are equal, we did not use the defaultName()
<ide> if ($name === $command['name']) {
<ide> $command['name'] = str_replace('_', ' ', $command['name']); | 1 |
Javascript | Javascript | add a deprecation warning when importing netinfo | d9c0dfe353eceb91efcec774bab0f65b6792e4fa | <ide><path>Libraries/react-native/react-native-implementation.js
<ide> module.exports = {
<ide> 'webview-moved',
<ide> 'WebView has been extracted from react-native core and will be removed in a future release. ' +
<ide> "It can now be installed and imported from 'react-native-webview' instead of 'react-native'. " +
<del> 'See https://github.com/react-native-community/react-native-webview for more informations.',
<add> 'See https://github.com/react-native-community/react-native-webview',
<ide> );
<ide> return require('WebView');
<ide> },
<ide> module.exports = {
<ide> return require('NativeEventEmitter');
<ide> },
<ide> get NetInfo() {
<add> warnOnce(
<add> 'netinfo-moved',
<add> 'NetInfo has been extracted from react-native core and will be removed in a future release. ' +
<add> "It can now be installed and imported from '@react-native-community/netinfo' instead of 'react-native'. " +
<add> 'See https://github.com/react-native-community/react-native-netinfo',
<add> );
<ide> return require('NetInfo');
<ide> },
<ide> get PanResponder() { | 1 |
Go | Go | add debug output to foreign layer pull | 6b7d028085e0e6ac0c5f224f0a493839e2beeba3 | <ide><path>distribution/pull_v2_windows.go
<ide> import (
<ide> "net/http"
<ide> "os"
<ide>
<add> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/context"
<ide> "github.com/docker/distribution/manifest/schema2"
<ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo
<ide>
<ide> // Find the first URL that results in a 200 result code.
<ide> for _, url := range ld.src.URLs {
<add> logrus.Debugf("Pulling %v from foreign URL %v", ld.digest, url)
<ide> rsc = transport.NewHTTPReadSeeker(http.DefaultClient, url, nil)
<ide> _, err = rsc.Seek(0, os.SEEK_SET)
<ide> if err == nil {
<ide> break
<ide> }
<add> logrus.Debugf("Download for %v failed: %v", ld.digest, err)
<ide> rsc.Close()
<ide> rsc = nil
<ide> } | 1 |
PHP | PHP | fix typehints in collection | 11b06c4f4c0eaffb1bda4af5eaa3c628ac3fc8b4 | <ide><path>src/Database/Schema/Collection.php
<ide> namespace Cake\Database\Schema;
<ide>
<ide> use Cake\Database\Exception;
<del>use Cake\Datasource\ConnectionInterface;
<add>use Cake\Database\Connection;
<ide> use PDOException;
<ide>
<ide> /**
<ide> class Collection
<ide> /**
<ide> * Connection object
<ide> *
<del> * @var \Cake\Datasource\ConnectionInterface
<add> * @var \Cake\Database\Connection
<ide> */
<ide> protected $_connection;
<ide>
<ide> class Collection
<ide> /**
<ide> * Constructor.
<ide> *
<del> * @param \Cake\Datasource\ConnectionInterface $connection The connection instance.
<add> * @param \Cake\Database\Connection $connection The connection instance.
<ide> */
<del> public function __construct(ConnectionInterface $connection)
<add> public function __construct(Connection $connection)
<ide> {
<ide> $this->_connection = $connection;
<ide> $this->_dialect = $connection->driver()->schemaDialect(); | 1 |
Ruby | Ruby | update example test documentation | 75df8b9a77315b3af363c238918eedf52004c9b0 | <ide><path>actionpack/lib/action_controller/metal/http_authentication.rb
<ide> module HttpAuthentication
<ide> # In your integration tests, you can do something like this:
<ide> #
<ide> # def test_access_granted_from_xml
<del> # get(
<del> # "/notes/1.xml", nil,
<del> # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
<del> # )
<add> # @request.env['HTTP_AUTHORIZATION'] => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
<add> # get "/notes/1.xml"
<ide> #
<ide> # assert_equal 200, status
<ide> # end | 1 |
Javascript | Javascript | remove watchdog in test-debug-signal-cluster | b0486b14e5f92ddbbb71ac062cecac49cd477a7c | <ide><path>test/parallel/test-debug-signal-cluster.js
<ide> function onNoMoreDebuggerAgentsOutput() {
<ide> process.exit();
<ide> }
<ide>
<del>setTimeout(function testTimedOut() {
<del> common.fail('test timed out');
<del>}, common.platformTimeout(4000)).unref();
<del>
<ide> process.on('exit', function onExit() {
<ide> // Kill processes in reverse order to avoid timing problems on Windows where
<ide> // the parent process is killed before the children. | 1 |
Javascript | Javascript | remove test condition for dependency=url | 69d69d600326dac6e8ebbb016a525a160b8eea17 | <ide><path>lib/config/defaults.js
<ide> const applyModuleDefaults = (
<ide> }
<ide> if (asset) {
<ide> rules.push({
<del> test: /\.js$/,
<ide> dependency: "url",
<ide> type: "asset/resource"
<ide> }); | 1 |
Javascript | Javascript | move rest of requirejsstuffplugin to es6 | e73cbf3e601070079355bf56e1dfbb4d676b95dd | <ide><path>test/RequireJsStuffPlugin.test.js
<del>var should = require("should");
<del>var sinon = require("sinon");
<del>var RequireJsStuffPlugin = require("../lib/RequireJsStuffPlugin");
<del>var applyPluginWithOptions = require("./helpers/applyPluginWithOptions");
<del>var PluginEnvironment = require("./helpers/PluginEnvironment");
<add>"use strict";
<add>const should = require("should");
<add>const sinon = require("sinon");
<add>const RequireJsStuffPlugin = require("../lib/RequireJsStuffPlugin");
<add>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");
<add>const PluginEnvironment = require("./helpers/PluginEnvironment");
<ide>
<ide> describe("RequireJsStuffPlugin", function() {
<ide> it("has apply function", function() {
<ide> (new RequireJsStuffPlugin()).apply.should.be.a.Function();
<ide> });
<ide>
<ide> describe("when applied", function() {
<del> var eventBindings, eventBinding;
<add> let eventBindings;
<add> let eventBinding;
<ide>
<ide> beforeEach(function() {
<ide> eventBindings = applyPluginWithOptions(RequireJsStuffPlugin);
<ide> describe("RequireJsStuffPlugin", function() {
<ide> });
<ide>
<ide> describe('when called', function() {
<del> var pluginEnvironment, compilationEventBindings, compilation;
<add> let pluginEnvironment;
<add> let compilationEventBindings;
<add> let compilation;
<ide>
<ide> beforeEach(function() {
<ide> pluginEnvironment = new PluginEnvironment();
<ide> describe("RequireJsStuffPlugin", function() {
<ide> set: sinon.spy()
<ide> }
<ide> };
<del> var params = {
<add> const params = {
<ide> normalModuleFactory: pluginEnvironment.getEnvironmentStub()
<ide> };
<ide> eventBinding.handler(compilation, params);
<ide> describe("RequireJsStuffPlugin", function() {
<ide> });
<ide>
<ide> describe('when called with empty parser options', function() {
<del> var parserEventBinding, parserEventContext, expressionMock;
<add> let parserEventBinding;
<add> let parserEventContext;
<add> let expressionMock;
<ide>
<ide> beforeEach(function() {
<ide> parserEventContext = {
<ide> describe("RequireJsStuffPlugin", function() {
<ide> });
<ide>
<ide> it('adds dependency to current state', function() {
<del> var addDependencySpy = parserEventContext.state.current.addDependency;
<del> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> const addDependencySpy = parserEventContext.state.current.addDependency;
<add> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<ide> addDependencySpy.callCount.should.be.exactly(1);
<ide> addedDependency.should.be.exactly('{"module":null,"expression":";","range":10,"loc":5}');
<ide> });
<ide> describe("RequireJsStuffPlugin", function() {
<ide> });
<ide>
<ide> it('adds dependency to current state', function() {
<del> var addDependencySpy = parserEventContext.state.current.addDependency;
<del> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> const addDependencySpy = parserEventContext.state.current.addDependency;
<add> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<ide> addDependencySpy.callCount.should.be.exactly(1);
<ide> addedDependency.should.be.exactly('{"module":null,"expression":"\\"0.0.0\\"","range":10,"loc":5}');
<ide> });
<ide> describe("RequireJsStuffPlugin", function() {
<ide> });
<ide>
<ide> it('adds dependency to current state', function() {
<del> var addDependencySpy = parserEventContext.state.current.addDependency;
<del> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> const addDependencySpy = parserEventContext.state.current.addDependency;
<add> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<ide> addDependencySpy.callCount.should.be.exactly(1);
<ide> addedDependency.should.be.exactly('{"module":null,"expression":"\\"__webpack_require__.oe\\"","range":10,"loc":5}');
<ide> }); | 1 |
Text | Text | add support section in readme | 6b6474d6c0575bdbcb3363f0544885f7da7ddba1 | <ide><path>README.md
<ide> policies, and releases are managed under an
<ide>
<ide> **This project is bound by a [Code of Conduct][].**
<ide>
<del>If you need help using or installing Node.js, please use the
<del>[nodejs/help](https://github.com/nodejs/help) issue tracker.
<del>
<ide>
<ide> # Table of Contents
<ide>
<del>* [Resources for Newcomers](#resources-for-newcomers)
<add>* [Support](#support)
<ide> * [Release Types](#release-types)
<ide> * [Download](#download)
<ide> * [Current and LTS Releases](#current-and-lts-releases)
<ide> If you need help using or installing Node.js, please use the
<ide> * [Collaborators](#collaborators)
<ide> * [Release Team](#release-team)
<ide>
<del>## Resources for Newcomers
<add>## Support
<add>
<add>Node.js contributors have limited availability to address general support
<add>questions. Please make sure you are using a [currently-supported version of
<add>Node.js](https://github.com/nodejs/Release#release-schedule).
<ide>
<del>### Official Resources
<add>When looking for support, please first search for your question in these venues:
<ide>
<del>* [Website][]
<add>* [Node.js Website][]
<ide> * [Node.js Help][]
<del>* [Contributing to the project][]
<del>* IRC (node core development): [#node-dev on chat.freenode.net][]
<add>* [Open or closed issues in the Node.js GitHub organization](https://github.com/issues?utf8=%E2%9C%93&q=sort%3Aupdated-desc+org%3Anodejs+is%3Aissue)
<add>* [Questions tagged 'node.js' on StackOverflow][]
<add>
<add>If you didn't find an answer in one of the venues above, you can:
<ide>
<del>### Unofficial Resources
<add>* Join the **unofficial** [#node.js channel on chat.freenode.net][]. See
<add><http://nodeirc.info/> for more information.
<ide>
<del>* IRC (general questions): [#node.js on chat.freenode.net][]. Please see
<del><http://nodeirc.info/> for more information regarding the `#node.js` IRC
<del>channel.
<add>GitHub issues are meant for tracking enhancements and bugs, not general support.
<ide>
<del>_Please note that unofficial resources are neither managed by (nor necessarily
<del>endorsed by) the Node.js TSC. Specifically, such resources are not
<del>currently covered by the [Node.js Moderation Policy][] and the selection and
<del>actions of resource operators/moderators are not subject to TSC oversight._
<add>Remember, libre != gratis; the open source license grants you the freedom to use
<add>and modify, but not commitments of other people's time. Please be respectful,
<add>and set your expectations accordingly.
<ide>
<ide> ## Release Types
<ide>
<ide> Previous releases may also have been signed with one of the following GPG keys:
<ide> Information on the current Node.js Working Groups can be found in the
<ide> [TSC repository](https://github.com/nodejs/TSC/blob/master/WORKING_GROUPS.md).
<ide>
<add>### Contributing to Node.js
<add>
<add>* [Contributing to the project][]
<add>* IRC (node core development): [#node-dev on chat.freenode.net][]
<add>
<ide> [npm]: https://www.npmjs.com
<del>[Website]: https://nodejs.org/en/
<add>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md
<ide> [Contributing to the project]: CONTRIBUTING.md
<ide> [Node.js Help]: https://github.com/nodejs/help
<ide> [Node.js Moderation Policy]: https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
<del>[#node.js on chat.freenode.net]: https://webchat.freenode.net?channels=node.js&uio=d4
<add>[Node.js Website]: https://nodejs.org/en/
<add>[Questions tagged 'node.js' on StackOverflow]: https://stackoverflow.com/questions/tagged/node.js
<add>[#node.js channel on chat.freenode.net]: https://webchat.freenode.net?channels=node.js&uio=d4
<ide> [#node-dev on chat.freenode.net]: https://webchat.freenode.net?channels=node-dev&uio=d4
<del>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md | 1 |
PHP | PHP | fix style errors | dccc27056654aa82769ebbe1df6889ff94811f84 | <ide><path>src/TestSuite/Stub/ConsoleInput.php
<ide> namespace Cake\TestSuite\Stub;
<ide>
<ide> use Cake\Console\ConsoleInput as ConsoleInputBase;
<del>use Cake\TestSuite\Stub\MissingConsoleInputException;
<ide> use NumberFormatter;
<ide>
<ide> /**
<ide><path>src/TestSuite/Stub/MissingConsoleInputException.php
<ide> <?php
<add>declare(strict_types=1);
<add>
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Validation/Validator.php
<ide> public function __construct()
<ide> public function errors(array $data, bool $newRecord = true): array
<ide> {
<ide> deprecationWarning('`Validator::errors()` is deprecated. Use `Validator::validate()` instead.');
<add>
<ide> return $this->validate($data, $newRecord);
<ide> }
<ide>
<ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\TestSuite;
<ide>
<del>use Cake\Console\Exception\ConsoleException;
<ide> use Cake\Console\Shell;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide> use Cake\TestSuite\Stub\MissingConsoleInputException; | 4 |
Python | Python | fix opt softmax small nit | 3a27ba3d18b9691926b296b0a6a483313b0299ba | <ide><path>src/transformers/models/opt/modeling_opt.py
<ide> def forward(
<ide> attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
<ide> attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
<ide> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
<del> dtype_attn_weights = attn_weights.dtype
<ide>
<ide> # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
<del> if dtype_attn_weights == torch.float16:
<del> attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(dtype_attn_weights)
<add> if attn_weights.dtype == torch.float16:
<add> attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
<ide> else:
<ide> attn_weights = nn.functional.softmax(attn_weights, dim=-1)
<ide> | 1 |
Python | Python | fix integration slow tests | fda703a55374b3caaf4e886016f7de5810fa3571 | <ide><path>tests/test_modeling_albert.py
<ide> def test_model_from_pretrained(self):
<ide> class AlbertModelIntegrationTest(unittest.TestCase):
<ide> @slow
<ide> def test_inference_no_head_absolute_embedding(self):
<del> model = AlbertForPreTraining.from_pretrained("albert-base-v2")
<add> model = AlbertModel.from_pretrained("albert-base-v2")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<del> expected_shape = torch.Size((1, 11, 30000))
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<add> expected_shape = torch.Size((1, 11, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<ide> expected_slice = torch.tensor(
<del> [[[4.6061, 0.7321, -1.7725], [4.6061, 0.7323, -1.7727], [4.6061, 0.7323, -1.7727]]]
<add> [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]
<ide> )
<ide>
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide><path>tests/test_modeling_bert.py
<ide> class BertModelIntegrationTest(unittest.TestCase):
<ide> def test_inference_no_head_absolute_embedding(self):
<ide> model = BertModel.from_pretrained("bert-base-uncased")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> expected_shape = torch.Size((1, 11, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<del> expected_slice = torch.tensor(
<del> [[[-0.0483, 0.1188, -0.0313], [-0.0606, 0.1435, 0.0199], [-0.0235, 0.1519, 0.0175]]]
<del> )
<add> expected_slice = torch.tensor([[[0.4249, 0.1008, 0.7531], [0.3771, 0.1188, 0.7467], [0.4152, 0.1098, 0.7108]]])
<ide>
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide>
<ide> @slow
<ide> def test_inference_no_head_relative_embedding_key(self):
<ide> model = BertModel.from_pretrained("zhiheng-huang/bert-base-uncased-embedding-relative-key")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> expected_shape = torch.Size((1, 11, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<ide> expected_slice = torch.tensor(
<del> [[[0.3492, 0.4126, -0.1484], [0.2274, -0.0549, 0.1623], [0.5889, 0.6797, -0.0189]]]
<add> [[[0.0756, 0.3142, -0.5128], [0.3761, 0.3462, -0.5477], [0.2052, 0.3760, -0.1240]]]
<ide> )
<ide>
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide>
<ide> @slow
<ide> def test_inference_no_head_relative_embedding_key_query(self):
<ide> model = BertModel.from_pretrained("zhiheng-huang/bert-base-uncased-embedding-relative-key-query")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> expected_shape = torch.Size((1, 11, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<del> expected_slice = torch.tensor([[[1.1677, 0.5129, 0.9524], [0.6659, 0.5958, 0.6688], [1.1714, 0.1764, 0.6266]]])
<add> expected_slice = torch.tensor(
<add> [[[0.6496, 0.3784, 0.8203], [0.8148, 0.5656, 0.2636], [-0.0681, 0.5597, 0.7045]]]
<add> )
<ide>
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide><path>tests/test_modeling_convbert.py
<ide> def test_attention_outputs(self):
<ide> @require_torch
<ide> class ConvBertModelIntegrationTest(unittest.TestCase):
<ide> @slow
<del> def test_inference_masked_lm(self):
<add> def test_inference_no_head(self):
<ide> model = ConvBertModel.from_pretrained("YituTech/conv-bert-base")
<del> input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
<add> input_ids = torch.tensor([[1, 2, 3, 4, 5, 6]])
<ide> output = model(input_ids)[0]
<del> print(output[:, :3, :3])
<ide>
<ide> expected_shape = torch.Size((1, 6, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<ide>
<del> # TODO Replace values below with what was printed above.
<ide> expected_slice = torch.tensor(
<del> [[[-0.0348, -0.4686, -0.3064], [0.2264, -0.2699, -0.7423], [0.1032, -0.4501, -0.5828]]]
<add> [[[-0.0864, -0.4898, -0.3677], [0.1434, -0.2952, -0.7640], [-0.0112, -0.4432, -0.5432]]]
<ide> )
<ide>
<ide> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<ide><path>tests/test_modeling_deberta.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<del>
<del>import random
<ide> import unittest
<ide>
<del>import numpy as np
<del>
<ide> from transformers import is_torch_available
<ide> from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
<ide>
<ide> def test_inference_masked_lm(self):
<ide>
<ide> @slow
<ide> def test_inference_no_head(self):
<del> random.seed(0)
<del> np.random.seed(0)
<del> torch.manual_seed(0)
<del> torch.cuda.manual_seed_all(0)
<ide> model = DebertaModel.from_pretrained("microsoft/deberta-base")
<ide>
<ide> input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> # compare the actual values for a slice.
<ide> expected_slice = torch.tensor(
<del> [[[-0.0218, -0.6641, -0.3665], [-0.3907, -0.4716, -0.6640], [0.7461, 1.2570, -0.9063]]]
<add> [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]]
<ide> )
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4), f"{output[:, :3, :3]}")
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4), f"{output[:, 1:4, 1:4]}")
<ide><path>tests/test_modeling_deberta_v2.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<del>
<del>import random
<ide> import unittest
<ide>
<del>import numpy as np
<del>
<ide> from transformers import is_torch_available
<ide> from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
<ide>
<ide> def test_inference_masked_lm(self):
<ide>
<ide> @slow
<ide> def test_inference_no_head(self):
<del> random.seed(0)
<del> np.random.seed(0)
<del> torch.manual_seed(0)
<del> torch.cuda.manual_seed_all(0)
<ide> model = DebertaV2Model.from_pretrained("microsoft/deberta-v2-xlarge")
<ide>
<ide> input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> # compare the actual values for a slice.
<ide> expected_slice = torch.tensor(
<del> [[[-0.2913, 0.2647, 0.5627], [-0.4318, 0.1389, 0.3881], [-0.2929, -0.2489, 0.3452]]]
<add> [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]
<ide> )
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4), f"{output[:, :3, :3]}")
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4), f"{output[:, 1:4, 1:4]}")
<ide><path>tests/test_modeling_distilbert.py
<ide> class DistilBertModelIntergrationTest(unittest.TestCase):
<ide> def test_inference_no_head_absolute_embedding(self):
<ide> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<ide> expected_shape = torch.Size((1, 11, 768))
<ide> self.assertEqual(output.shape, expected_shape)
<ide> expected_slice = torch.tensor(
<del> [[[0.4026, -0.2919, 0.3902], [0.3828, -0.2129, 0.3563], [0.3919, -0.2287, 0.3438]]]
<add> [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]
<ide> )
<ide>
<del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide><path>tests/test_modeling_electra.py
<ide> def test_model_from_pretrained(self):
<ide> class ElectraModelIntegrationTest(unittest.TestCase):
<ide> @slow
<ide> def test_inference_no_head_absolute_embedding(self):
<del> model = ElectraForPreTraining.from_pretrained("google/electra-small-discriminator")
<add> model = ElectraModel.from_pretrained("google/electra-small-discriminator")
<ide> input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
<del> output = model(input_ids)[0]
<del> expected_shape = torch.Size((1, 11))
<add> attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
<add> output = model(input_ids, attention_mask=attention_mask)[0]
<add> expected_shape = torch.Size((1, 11, 256))
<ide> self.assertEqual(output.shape, expected_shape)
<ide> expected_slice = torch.tensor(
<del> [[-8.9253, -4.0305, -3.9306, -3.8774, -4.1873, -4.1280, 0.9429, -4.1672, 0.9281, 0.0410, -3.4823]]
<add> [[[0.4471, 0.6821, -0.3265], [0.4627, 0.5255, -0.3668], [0.4532, 0.3313, -0.4344]]]
<ide> )
<ide>
<del> self.assertTrue(torch.allclose(output, expected_slice, atol=1e-4))
<add> self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
<ide><path>tests/test_modeling_mbart.py
<ide> class MBartEnroIntegrationTest(AbstractSeq2SeqIntegrationTest):
<ide> ]
<ide> tgt_text = [
<ide> "Şeful ONU declară că nu există o soluţie militară în Siria",
<del> 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor face decât să înrăutăţească violenţa şi mizeria pentru milioane de oameni.',
<add> 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor face decât să înrăutăţească violenţa şi mizeria a milioane de oameni.',
<ide> ]
<ide> expected_src_tokens = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, 250004]
<ide>
<ide> def test_enro_generate_one(self):
<ide>
<ide> @slow
<ide> def test_enro_generate_batch(self):
<del> batch: BatchEncoding = self.tokenizer(self.src_text, return_tensors="pt").to(torch_device)
<add> batch: BatchEncoding = self.tokenizer(self.src_text, return_tensors="pt", padding=True, truncation=True).to(
<add> torch_device
<add> )
<ide> translated_tokens = self.model.generate(**batch)
<ide> decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
<ide> assert self.tgt_text == decoded
<ide><path>tests/test_modeling_squeezebert.py
<ide> class SqueezeBertModelIntegrationTest(unittest.TestCase):
<ide> def test_inference_classification_head(self):
<ide> model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli")
<ide>
<del> input_ids = torch.tensor([[0, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]])
<add> input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]])
<ide> output = model(input_ids)[0]
<ide> expected_shape = torch.Size((1, 3))
<ide> self.assertEqual(output.shape, expected_shape)
<del> expected_tensor = torch.tensor([[0.5075, 0.0682, -0.5881]])
<add> expected_tensor = torch.tensor([[0.6401, -0.0349, -0.6041]])
<ide> self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4)) | 9 |
Javascript | Javascript | inspect all prototypes | 02b66b5b866bd8398e7d815d3715ba3f94a5cf65 | <ide><path>lib/internal/util/inspect.js
<ide> function getEmptyFormatArray() {
<ide> return [];
<ide> }
<ide>
<del>function getConstructorName(obj) {
<add>function getConstructorName(obj, ctx) {
<ide> let firstProto;
<ide> while (obj) {
<ide> const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
<ide> function getConstructorName(obj) {
<ide> if (firstProto === null) {
<ide> return null;
<ide> }
<del> // TODO(BridgeAR): Improve prototype inspection.
<del> // We could use inspect on the prototype itself to improve the output.
<ide>
<del> return '';
<add> return `<${inspect(firstProto, {
<add> ...ctx,
<add> customInspect: false
<add> })}>`;
<ide> }
<ide>
<ide> function getPrefix(constructor, tag, fallback) {
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> }
<ide>
<ide> if (ctx.stop !== undefined) {
<del> const name = getConstructorName(value) || value[Symbol.toStringTag];
<add> const name = getConstructorName(value, ctx) || value[Symbol.toStringTag];
<ide> return ctx.stylize(`[${name || 'Object'}]`, 'special');
<ide> }
<ide>
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> function formatRaw(ctx, value, recurseTimes) {
<ide> let keys;
<ide>
<del> const constructor = getConstructorName(value);
<add> const constructor = getConstructorName(value, ctx);
<ide> let tag = value[Symbol.toStringTag];
<ide> if (typeof tag !== 'string')
<ide> tag = '';
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> );
<ide> }
<ide>
<del>// Manipulate the prototype to one that we can not handle.
<add>// Manipulate the prototype in weird ways.
<ide> {
<ide> let obj = { a: true };
<ide> let value = (function() { return function() {}; })();
<ide> Object.setPrototypeOf(value, null);
<ide> Object.setPrototypeOf(obj, value);
<del> assert.strictEqual(util.inspect(obj), '{ a: true }');
<add> assert.strictEqual(util.inspect(obj), '<[Function]> { a: true }');
<add> assert.strictEqual(
<add> util.inspect(obj, { colors: true }),
<add> '<\u001b[36m[Function]\u001b[39m> { a: \u001b[33mtrue\u001b[39m }'
<add> );
<ide>
<ide> obj = { a: true };
<ide> value = [];
<ide> Object.setPrototypeOf(value, null);
<ide> Object.setPrototypeOf(obj, value);
<del> assert.strictEqual(util.inspect(obj), '{ a: true }');
<add> assert.strictEqual(
<add> util.inspect(obj),
<add> '<[Array: null prototype] []> { a: true }'
<add> );
<add>
<add> function StorageObject() {}
<add> StorageObject.prototype = Object.create(null);
<add> assert.strictEqual(
<add> util.inspect(new StorageObject()),
<add> '<[Object: null prototype] {}> {}'
<add> );
<add>
<ide> }
<ide>
<ide> // Check that the fallback always works. | 2 |
Python | Python | check base dir | b4eb1d9491cb96d6608fa83869aace06146ae793 | <ide><path>keras/backend/__init__.py
<ide> import json
<ide> from .common import epsilon, floatx, set_epsilon, set_floatx
<ide>
<del>_keras_dir = os.path.expanduser(os.path.join('~', '.keras'))
<del>if not os.access(_keras_dir, os.W_OK):
<del> _keras_dir = os.path.join('/tmp', '.keras')
<add>_keras_base_dir = os.path.expanduser('~')
<add>if not os.access(_keras_base_dir, os.W_OK):
<add> _keras_base_dir = '/tmp'
<add>
<add>_keras_dir = os.path.join(_keras_base_dir, '.keras')
<ide> if not os.path.exists(_keras_dir):
<ide> os.makedirs(_keras_dir)
<ide> | 1 |
PHP | PHP | remove unused var | 14f78f857dde18a85f1860b9ba77376da9d78ed1 | <ide><path>lib/Cake/Console/Command/UpgradeShell.php
<ide> public function basics() {
<ide> * @return void
<ide> */
<ide> public function request() {
<del> $core = App::core();
<ide> $views = array_diff(App::path('views'), App::core('views'));
<ide> $controllers = array_diff(App::path('controllers'), App::core('controllers'), array(APP));
<ide> $components = array_diff(App::path('components'), App::core('components')); | 1 |
Go | Go | use assertions in image package unit tests | 69d7362058530d7dd97af29dc43fc4d55e73e776 | <ide><path>image/fs_test.go
<ide> import (
<ide> "path/filepath"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/pkg/testutil/assert"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<del>func TestFSGetSet(t *testing.T) {
<add>func defaultFSStoreBackend(t *testing.T) (StoreBackend, func()) {
<ide> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<del> testGetSet(t, fs)
<add> fsBackend, err := NewFSStoreBackend(tmpdir)
<add> assert.NilError(t, err)
<add>
<add> return fsBackend, func() { os.RemoveAll(tmpdir) }
<ide> }
<ide>
<ide> func TestFSGetInvalidData(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<del> id, err := fs.Set([]byte("foobar"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> id, err := store.Set([]byte("foobar"))
<add> assert.NilError(t, err)
<ide>
<ide> dgst := digest.Digest(id)
<ide>
<del> if err := ioutil.WriteFile(filepath.Join(tmpdir, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600); err != nil {
<del> t.Fatal(err)
<del> }
<add> err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600)
<add> assert.NilError(t, err)
<ide>
<del> _, err = fs.Get(id)
<del> if err == nil {
<del> t.Fatal("expected get to fail after data modification.")
<del> }
<add> _, err = store.Get(id)
<add> assert.Error(t, err, "failed to verify")
<ide> }
<ide>
<ide> func TestFSInvalidSet(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<ide> id := digest.FromBytes([]byte("foobar"))
<del> err = os.Mkdir(filepath.Join(tmpdir, contentDirName, string(id.Algorithm()), id.Hex()), 0700)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> err := os.Mkdir(filepath.Join(store.(*fs).root, contentDirName, string(id.Algorithm()), id.Hex()), 0700)
<add> assert.NilError(t, err)
<ide>
<del> _, err = fs.Set([]byte("foobar"))
<del> if err == nil {
<del> t.Fatal("expected error from invalid filesystem data.")
<del> }
<add> _, err = store.Set([]byte("foobar"))
<add> assert.Error(t, err, "is a directory")
<ide> }
<ide>
<ide> func TestFSInvalidRoot(t *testing.T) {
<ide> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide> defer os.RemoveAll(tmpdir)
<ide>
<ide> tcases := []struct {
<ide> func TestFSInvalidRoot(t *testing.T) {
<ide> root := filepath.Join(tmpdir, tc.root)
<ide> filePath := filepath.Join(tmpdir, tc.invalidFile)
<ide> err := os.MkdirAll(filepath.Dir(filePath), 0700)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> f, err := os.Create(filePath)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> f.Close()
<add> defer f.Close()
<add> assert.NilError(t, err)
<ide>
<ide> _, err = NewFSStoreBackend(root)
<del> if err == nil {
<del> t.Fatalf("expected error from root %q and invalid file %q", tc.root, tc.invalidFile)
<del> }
<add> assert.Error(t, err, "not a directory")
<ide>
<ide> os.RemoveAll(root)
<ide> }
<ide>
<ide> }
<ide>
<del>func testMetadataGetSet(t *testing.T, store StoreBackend) {
<add>func TestFSMetadataGetSet(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<add>
<ide> id, err := store.Set([]byte("foo"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> id2, err := store.Set([]byte("bar"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> tcases := []struct {
<ide> id digest.Digest
<ide> func testMetadataGetSet(t *testing.T, store StoreBackend) {
<ide>
<ide> for _, tc := range tcases {
<ide> err = store.SetMetadata(tc.id, tc.key, tc.value)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> actual, err := store.GetMetadata(tc.id, tc.key)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> if bytes.Compare(actual, tc.value) != 0 {
<ide> t.Fatalf("Metadata expected %q, got %q", tc.value, actual)
<ide> }
<ide> }
<ide>
<ide> _, err = store.GetMetadata(id2, "tkey2")
<del> if err == nil {
<del> t.Fatal("expected error for getting metadata for unknown key")
<del> }
<add> assert.Error(t, err, "no such file or directory")
<ide>
<ide> id3 := digest.FromBytes([]byte("baz"))
<ide> err = store.SetMetadata(id3, "tkey", []byte("tval"))
<del> if err == nil {
<del> t.Fatal("expected error for setting metadata for unknown ID.")
<del> }
<add> assert.Error(t, err, "no such file or directory")
<ide>
<ide> _, err = store.GetMetadata(id3, "tkey")
<del> if err == nil {
<del> t.Fatal("expected error for getting metadata for unknown ID.")
<del> }
<del>}
<del>
<del>func TestFSMetadataGetSet(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> testMetadataGetSet(t, fs)
<del>}
<del>
<del>func TestFSDelete(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> testDelete(t, fs)
<del>}
<del>
<del>func TestFSWalker(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> testWalker(t, fs)
<add> assert.Error(t, err, "no such file or directory")
<ide> }
<ide>
<ide> func TestFSInvalidWalker(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<del> fooID, err := fs.Set([]byte("foo"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> fooID, err := store.Set([]byte("foo"))
<add> assert.NilError(t, err)
<ide>
<del> if err := ioutil.WriteFile(filepath.Join(tmpdir, contentDirName, "sha256/foobar"), []byte("foobar"), 0600); err != nil {
<del> t.Fatal(err)
<del> }
<add> err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, "sha256/foobar"), []byte("foobar"), 0600)
<add> assert.NilError(t, err)
<ide>
<ide> n := 0
<del> err = fs.Walk(func(id digest.Digest) error {
<del> if id != fooID {
<del> t.Fatalf("invalid walker ID %q, expected %q", id, fooID)
<del> }
<add> err = store.Walk(func(id digest.Digest) error {
<add> assert.Equal(t, id, fooID)
<ide> n++
<ide> return nil
<ide> })
<del> if err != nil {
<del> t.Fatalf("invalid data should not have caused walker error, got %v", err)
<del> }
<del> if n != 1 {
<del> t.Fatalf("expected 1 walk initialization, got %d", n)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, n, 1)
<ide> }
<ide>
<del>func testGetSet(t *testing.T, store StoreBackend) {
<add>func TestFSGetSet(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<add>
<ide> type tcase struct {
<ide> input []byte
<ide> expected digest.Digest
<ide> func testGetSet(t *testing.T, store StoreBackend) {
<ide>
<ide> randomInput := make([]byte, 8*1024)
<ide> _, err := rand.Read(randomInput)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> // skipping use of digest pkg because it is used by the implementation
<ide> h := sha256.New()
<ide> _, err = h.Write(randomInput)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> tcases = append(tcases, tcase{
<ide> input: randomInput,
<ide> expected: digest.Digest("sha256:" + hex.EncodeToString(h.Sum(nil))),
<ide> })
<ide>
<ide> for _, tc := range tcases {
<ide> id, err := store.Set([]byte(tc.input))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if id != tc.expected {
<del> t.Fatalf("expected ID %q, got %q", tc.expected, id)
<del> }
<del> }
<del>
<del> for _, emptyData := range [][]byte{nil, {}} {
<del> _, err := store.Set(emptyData)
<del> if err == nil {
<del> t.Fatal("expected error for nil input.")
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, id, tc.expected)
<ide> }
<ide>
<ide> for _, tc := range tcases {
<ide> data, err := store.Get(tc.expected)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide> if bytes.Compare(data, tc.input) != 0 {
<ide> t.Fatalf("expected data %q, got %q", tc.input, data)
<ide> }
<ide> }
<add>}
<add>
<add>func TestFSGetUnsetKey(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<ide> for _, key := range []digest.Digest{"foobar:abc", "sha256:abc", "sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2a"} {
<ide> _, err := store.Get(key)
<del> if err == nil {
<del> t.Fatalf("expected error for ID %q.", key)
<del> }
<add> assert.Error(t, err, "no such file or directory")
<ide> }
<add>}
<ide>
<add>func TestFSGetEmptyData(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<add>
<add> for _, emptyData := range [][]byte{nil, {}} {
<add> _, err := store.Set(emptyData)
<add> assert.Error(t, err, "invalid empty data")
<add> }
<ide> }
<ide>
<del>func testDelete(t *testing.T, store StoreBackend) {
<add>func TestFSDelete(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<add>
<ide> id, err := store.Set([]byte("foo"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> id2, err := store.Set([]byte("bar"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> err = store.Delete(id)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> _, err = store.Get(id)
<del> if err == nil {
<del> t.Fatalf("expected getting deleted item %q to fail", id)
<del> }
<add> assert.Error(t, err, "no such file or directory")
<add>
<ide> _, err = store.Get(id2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> err = store.Delete(id2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> _, err = store.Get(id2)
<del> if err == nil {
<del> t.Fatalf("expected getting deleted item %q to fail", id2)
<del> }
<add> assert.Error(t, err, "no such file or directory")
<ide> }
<ide>
<del>func testWalker(t *testing.T, store StoreBackend) {
<add>func TestFSWalker(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<add>
<ide> id, err := store.Set([]byte("foo"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> id2, err := store.Set([]byte("bar"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> tcases := make(map[digest.Digest]struct{})
<ide> tcases[id] = struct{}{}
<ide> func testWalker(t *testing.T, store StoreBackend) {
<ide> n++
<ide> return nil
<ide> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, n, 2)
<add> assert.Equal(t, len(tcases), 0)
<add>}
<ide>
<del> if n != 2 {
<del> t.Fatalf("expected 2 walk initializations, got %d", n)
<del> }
<del> if len(tcases) != 0 {
<del> t.Fatalf("expected empty unwalked set, got %+v", tcases)
<del> }
<add>func TestFSWalkerStopOnError(t *testing.T) {
<add> store, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<del> // stop on error
<del> tcases = make(map[digest.Digest]struct{})
<add> id, err := store.Set([]byte("foo"))
<add> assert.NilError(t, err)
<add>
<add> tcases := make(map[digest.Digest]struct{})
<ide> tcases[id] = struct{}{}
<ide> err = store.Walk(func(id digest.Digest) error {
<del> return errors.New("")
<add> return errors.New("what")
<ide> })
<del> if err == nil {
<del> t.Fatalf("expected error from walker.")
<del> }
<add> assert.Error(t, err, "what")
<ide> }
<ide><path>image/image_test.go
<ide> import (
<ide> "sort"
<ide> "strings"
<ide> "testing"
<add>
<add> "github.com/docker/docker/pkg/testutil/assert"
<ide> )
<ide>
<ide> const sampleImageJSON = `{
<ide> const sampleImageJSON = `{
<ide> }
<ide> }`
<ide>
<del>func TestJSON(t *testing.T) {
<add>func TestNewFromJSON(t *testing.T) {
<ide> img, err := NewFromJSON([]byte(sampleImageJSON))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> rawJSON := img.RawJSON()
<del> if string(rawJSON) != sampleImageJSON {
<del> t.Fatalf("raw JSON of config didn't match: expected %+v, got %v", sampleImageJSON, rawJSON)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, string(img.RawJSON()), sampleImageJSON)
<ide> }
<ide>
<del>func TestInvalidJSON(t *testing.T) {
<add>func TestNewFromJSONWithInvalidJSON(t *testing.T) {
<ide> _, err := NewFromJSON([]byte("{}"))
<del> if err == nil {
<del> t.Fatal("expected JSON parse error")
<del> }
<add> assert.Error(t, err, "invalid image JSON, no RootFS key")
<ide> }
<ide>
<ide> func TestMarshalKeyOrder(t *testing.T) {
<ide> func TestMarshalKeyOrder(t *testing.T) {
<ide> Architecture: "c",
<ide> },
<ide> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> expectedOrder := []string{"architecture", "author", "comment"}
<ide> var indexes []int
<ide><path>image/store_test.go
<ide> package image
<ide>
<ide> import (
<del> "io/ioutil"
<del> "os"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/layer"
<add> "github.com/docker/docker/pkg/testutil/assert"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func TestRestore(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> fs, cleanup := defaultFSStoreBackend(t)
<add> defer cleanup()
<ide>
<ide> id1, err := fs.Set([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> _, err = fs.Set([]byte(`invalid`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> id2, err := fs.Set([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> err = fs.SetMetadata(id2, "parent", []byte(id1))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> is, err := NewImageStore(fs, &mockLayerGetReleaser{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<del> imgs := is.Map()
<del> if actual, expected := len(imgs), 2; actual != expected {
<del> t.Fatalf("invalid images length, expected 2, got %q", len(imgs))
<del> }
<add> assert.Equal(t, len(is.Map()), 2)
<ide>
<ide> img1, err := is.Get(ID(id1))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if actual, expected := img1.computedID, ID(id1); actual != expected {
<del> t.Fatalf("invalid image ID: expected %q, got %q", expected, actual)
<del> }
<del>
<del> if actual, expected := img1.computedID.String(), string(id1); actual != expected {
<del> t.Fatalf("invalid image ID string: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, img1.computedID, ID(id1))
<add> assert.Equal(t, img1.computedID.String(), string(id1))
<ide>
<ide> img2, err := is.Get(ID(id2))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if actual, expected := img1.Comment, "abc"; actual != expected {
<del> t.Fatalf("invalid comment for image1: expected %q, got %q", expected, actual)
<del> }
<del>
<del> if actual, expected := img2.Comment, "def"; actual != expected {
<del> t.Fatalf("invalid comment for image2: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, img1.Comment, "abc")
<add> assert.Equal(t, img2.Comment, "def")
<ide>
<ide> p, err := is.GetParent(ID(id1))
<del> if err == nil {
<del> t.Fatal("expected error for getting parent")
<del> }
<add> assert.Error(t, err, "no such file")
<ide>
<ide> p, err = is.GetParent(ID(id2))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if actual, expected := p, ID(id1); actual != expected {
<del> t.Fatalf("invalid parent: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, p, ID(id1))
<ide>
<ide> children := is.Children(ID(id1))
<del> if len(children) != 1 {
<del> t.Fatalf("invalid children length: %q", len(children))
<del> }
<del> if actual, expected := children[0], ID(id2); actual != expected {
<del> t.Fatalf("invalid child for id1: expected %q, got %q", expected, actual)
<del> }
<del>
<del> heads := is.Heads()
<del> if actual, expected := len(heads), 1; actual != expected {
<del> t.Fatalf("invalid images length: expected %q, got %q", expected, actual)
<del> }
<add> assert.Equal(t, len(children), 1)
<add> assert.Equal(t, children[0], ID(id2))
<add> assert.Equal(t, len(is.Heads()), 1)
<ide>
<ide> sid1, err := is.Search(string(id1)[:10])
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if actual, expected := sid1, ID(id1); actual != expected {
<del> t.Fatalf("searched ID mismatch: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, sid1, ID(id1))
<ide>
<ide> sid1, err = is.Search(digest.Digest(id1).Hex()[:6])
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if actual, expected := sid1, ID(id1); actual != expected {
<del> t.Fatalf("searched ID mismatch: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, sid1, ID(id1))
<ide>
<ide> invalidPattern := digest.Digest(id1).Hex()[1:6]
<ide> _, err = is.Search(invalidPattern)
<del> if err == nil {
<del> t.Fatalf("expected search for %q to fail", invalidPattern)
<del> }
<del>
<add> assert.Error(t, err, "No such image")
<ide> }
<ide>
<ide> func TestAddDelete(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> is, err := NewImageStore(fs, &mockLayerGetReleaser{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> is, cleanup := defaultImageStore(t)
<add> defer cleanup()
<ide>
<ide> id1, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if actual, expected := id1, ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"); actual != expected {
<del> t.Fatalf("create ID mismatch: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, id1, ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"))
<ide>
<ide> img, err := is.Get(id1)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if actual, expected := img.Comment, "abc"; actual != expected {
<del> t.Fatalf("invalid comment in image: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, img.Comment, "abc")
<ide>
<ide> id2, err := is.Create([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> err = is.SetParent(id2, id1)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> pid1, err := is.GetParent(id2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if actual, expected := pid1, id1; actual != expected {
<del> t.Fatalf("invalid parent for image: expected %q, got %q", expected, actual)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, pid1, id1)
<ide>
<ide> _, err = is.Delete(id1)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add>
<ide> _, err = is.Get(id1)
<del> if err == nil {
<del> t.Fatalf("expected get for deleted image %q to fail", id1)
<del> }
<add> assert.Error(t, err, "no such file or directory")
<add>
<ide> _, err = is.Get(id2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> pid1, err = is.GetParent(id2)
<del> if err == nil {
<del> t.Fatalf("expected parent check for image %q to fail, got %q", id2, pid1)
<del> }
<add> assert.NilError(t, err)
<ide>
<add> _, err = is.GetParent(id2)
<add> assert.Error(t, err, "no such file or directory")
<ide> }
<ide>
<ide> func TestSearchAfterDelete(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> is, err := NewImageStore(fs, &mockLayerGetReleaser{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> is, cleanup := defaultImageStore(t)
<add> defer cleanup()
<ide>
<ide> id, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> id1, err := is.Search(string(id)[:15])
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<add> assert.Equal(t, id1, id)
<ide>
<del> if actual, expected := id1, id; expected != actual {
<del> t.Fatalf("wrong id returned from search: expected %q, got %q", expected, actual)
<del> }
<add> _, err = is.Delete(id)
<add> assert.NilError(t, err)
<ide>
<del> if _, err := is.Delete(id); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if _, err := is.Search(string(id)[:15]); err == nil {
<del> t.Fatal("expected search after deletion to fail")
<del> }
<add> _, err = is.Search(string(id)[:15])
<add> assert.Error(t, err, "No such image")
<ide> }
<ide>
<ide> func TestParentReset(t *testing.T) {
<del> tmpdir, err := ioutil.TempDir("", "images-fs-store")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpdir)
<del> fs, err := NewFSStoreBackend(tmpdir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> is, err := NewImageStore(fs, &mockLayerGetReleaser{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> is, cleanup := defaultImageStore(t)
<add> defer cleanup()
<ide>
<ide> id, err := is.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> id2, err := is.Create([]byte(`{"comment": "abc2", "rootfs": {"type": "layers"}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<ide> id3, err := is.Create([]byte(`{"comment": "abc3", "rootfs": {"type": "layers"}}`))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide>
<del> if err := is.SetParent(id, id2); err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, is.SetParent(id, id2))
<add> assert.Equal(t, len(is.Children(id2)), 1)
<ide>
<del> ids := is.Children(id2)
<del> if actual, expected := len(ids), 1; expected != actual {
<del> t.Fatalf("wrong number of children: %d, got %d", expected, actual)
<del> }
<del>
<del> if err := is.SetParent(id, id3); err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, is.SetParent(id, id3))
<add> assert.Equal(t, len(is.Children(id2)), 0)
<add> assert.Equal(t, len(is.Children(id3)), 1)
<add>}
<ide>
<del> ids = is.Children(id2)
<del> if actual, expected := len(ids), 0; expected != actual {
<del> t.Fatalf("wrong number of children after parent reset: %d, got %d", expected, actual)
<del> }
<add>func defaultImageStore(t *testing.T) (Store, func()) {
<add> fsBackend, cleanup := defaultFSStoreBackend(t)
<ide>
<del> ids = is.Children(id3)
<del> if actual, expected := len(ids), 1; expected != actual {
<del> t.Fatalf("wrong number of children after parent reset: %d, got %d", expected, actual)
<del> }
<add> store, err := NewImageStore(fsBackend, &mockLayerGetReleaser{})
<add> assert.NilError(t, err)
<ide>
<add> return store, cleanup
<ide> }
<ide>
<ide> type mockLayerGetReleaser struct{} | 3 |
Javascript | Javascript | use arrow functions instead of `.bind` and `self` | a68b8b708f04e1bb6c4af9226424fd871a1e3ab6 | <ide><path>lib/fs.js
<ide> ReadStream.prototype._read = function(n) {
<ide> return this.push(null);
<ide>
<ide> // the actual read.
<del> var self = this;
<del> fs.read(this.fd, pool, pool.used, toRead, this.pos, onread);
<del>
<del> // move the pool positions, and internal position for reading.
<del> if (this.pos !== undefined)
<del> this.pos += toRead;
<del> pool.used += toRead;
<del>
<del> function onread(er, bytesRead) {
<add> fs.read(this.fd, pool, pool.used, toRead, this.pos, (er, bytesRead) => {
<ide> if (er) {
<del> if (self.autoClose) {
<del> self.destroy();
<add> if (this.autoClose) {
<add> this.destroy();
<ide> }
<del> self.emit('error', er);
<add> this.emit('error', er);
<ide> } else {
<ide> var b = null;
<ide> if (bytesRead > 0) {
<del> self.bytesRead += bytesRead;
<add> this.bytesRead += bytesRead;
<ide> b = thisPool.slice(start, start + bytesRead);
<ide> }
<ide>
<del> self.push(b);
<add> this.push(b);
<ide> }
<del> }
<add> });
<add>
<add> // move the pool positions, and internal position for reading.
<add> if (this.pos !== undefined)
<add> this.pos += toRead;
<add> pool.used += toRead;
<ide> };
<ide>
<ide> ReadStream.prototype._destroy = function(err, cb) {
<ide> fs.FileWriteStream = fs.WriteStream; // support the legacy name
<ide>
<ide>
<ide> WriteStream.prototype.open = function() {
<del> fs.open(this.path, this.flags, this.mode, function(er, fd) {
<add> fs.open(this.path, this.flags, this.mode, (er, fd) => {
<ide> if (er) {
<ide> if (this.autoClose) {
<ide> this.destroy();
<ide> WriteStream.prototype.open = function() {
<ide>
<ide> this.fd = fd;
<ide> this.emit('open', fd);
<del> }.bind(this));
<add> });
<ide> };
<ide>
<ide>
<ide> WriteStream.prototype._write = function(data, encoding, cb) {
<ide> });
<ide> }
<ide>
<del> var self = this;
<del> fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) {
<add> fs.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
<ide> if (er) {
<del> if (self.autoClose) {
<del> self.destroy();
<add> if (this.autoClose) {
<add> this.destroy();
<ide> }
<ide> return cb(er);
<ide> }
<del> self.bytesWritten += bytes;
<add> this.bytesWritten += bytes;
<ide> cb();
<ide> });
<ide> | 1 |
Python | Python | fix padding with large integers | 51ef0c409e20490829218c4d549a3bd4c9b073a2 | <ide><path>numpy/lib/arraypad.py
<ide> def _prepend_const(arr, pad_amt, val, axis=-1):
<ide> return np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr),
<ide> axis=axis)
<ide> else:
<del> return np.concatenate(((np.zeros(padshape) + val).astype(arr.dtype),
<del> arr), axis=axis)
<add> return np.concatenate((np.full(padshape, val, dtype=arr.dtype), arr),
<add> axis=axis)
<ide>
<ide>
<ide> def _append_const(arr, pad_amt, val, axis=-1):
<ide> def _append_const(arr, pad_amt, val, axis=-1):
<ide> return np.concatenate((arr, np.zeros(padshape, dtype=arr.dtype)),
<ide> axis=axis)
<ide> else:
<del> return np.concatenate(
<del> (arr, (np.zeros(padshape) + val).astype(arr.dtype)), axis=axis)
<add> return np.concatenate((arr, np.full(padshape, val, dtype=arr.dtype)),
<add> axis=axis)
<ide>
<ide>
<ide> def _prepend_edge(arr, pad_amt, axis=-1):
<ide><path>numpy/lib/tests/test_arraypad.py
<ide> def test_check_constant_pad_2d(self):
<ide> )
<ide> assert_allclose(test, expected)
<ide>
<add> def test_check_large_integers(self):
<add> uint64_max = 2 ** 64 - 1
<add> arr = np.full(5, uint64_max, dtype=np.uint64)
<add> test = np.pad(arr, 1, mode="constant", constant_values=arr.min())
<add> expected = np.full(7, uint64_max, dtype=np.uint64)
<add> assert_array_equal(test, expected)
<add>
<add> int64_max = 2 ** 63 - 1
<add> arr = np.full(5, int64_max, dtype=np.int64)
<add> test = np.pad(arr, 1, mode="constant", constant_values=arr.min())
<add> expected = np.full(7, int64_max, dtype=np.int64)
<add> assert_array_equal(test, expected)
<add>
<ide>
<ide> class TestLinearRamp(object):
<ide> def test_check_simple(self): | 2 |
PHP | PHP | simplify mailer class | 26f65215f955f5919e313097e0a7ae4340e862a8 | <ide><path>src/Mailer/Mailer.php
<ide> */
<ide> namespace Cake\Mailer;
<ide>
<del>use ArrayAccess;
<ide> use Cake\Datasource\ModelAwareTrait;
<ide> use Cake\Event\EventListenerInterface;
<ide> use Cake\Mailer\Exception\MissingActionException;
<ide> * Our mailer could either be registered in the application bootstrap, or
<ide> * in the Table class' initialize() hook.
<ide> */
<del>abstract class Mailer implements ArrayAccess, EventListenerInterface
<add>abstract class Mailer implements EventListenerInterface
<ide> {
<ide>
<ide> use ModelAwareTrait;
<ide> abstract class Mailer implements ArrayAccess, EventListenerInterface
<ide> */
<ide> static public $name;
<ide>
<del> /**
<del> * Layout.
<del> *
<del> * @var string
<del> */
<del> public $layout;
<del>
<del> /**
<del> * Email view template to render, defaults to the triggered mailer
<del> * action's name.
<del> *
<del> * @var string
<del> */
<del> public $template;
<del>
<ide> /**
<ide> * Email instance.
<ide> *
<ide> public function getName()
<ide> }
<ide>
<ide> /**
<del> * Sets layout to use. Defaults to configured layout template if a custom layout
<del> * could not be found.
<add> * Sets layout to use.
<ide> *
<ide> * @param string $layout Name of the layout to use.
<ide> * @return $this object.
<ide> */
<ide> public function layout($layout)
<ide> {
<del> $this->layout = $layout;
<del> return $this;
<del> }
<del>
<del> /**
<del> * Sets headers.
<del> *
<del> * @param array $headers Headers to set.
<del> * @return $this object.
<del> */
<del> public function setHeaders(array $headers)
<del> {
<del> $this->_email->setHeaders($headers);
<add> $this->_email->viewBuilder()->layout($layout);
<ide> return $this;
<ide> }
<ide>
<del> /**
<del> * Adds headers.
<del> *
<del> * @param array $headers Headers to set.
<del> * @return $this object.
<del> */
<del> public function addHeaders(array $headers)
<add> public function viewBuilder()
<ide> {
<del> $this->_email->addHeaders($headers);
<del> return $this;
<add> return $this->_email->viewBuilder();
<ide> }
<ide>
<ide> /**
<del> * Sets attachments.
<add> * Magic method to forward method class to Email instance.
<ide> *
<del> * @param string|array $attachments String with the filename or array with filenames
<del> * @return $this object.
<del> * @throws \InvalidArgumentException
<add> * @param string $method Method name.
<add> * @param array $args Method arguments
<add> * @return $this
<ide> */
<del> public function attachments($attachments)
<add> public function __call($method, $args)
<ide> {
<del> $this->_email->attachments($attachments);
<add> call_user_func_array([$this->_email, $method], $args);
<ide> return $this;
<ide> }
<ide>
<ide> public function send($action, $args = [], $headers = [])
<ide> ]);
<ide> }
<ide>
<del> $this->setHeaders($headers);
<add> $this->_email->setHeaders($headers);
<add> if (!$this->_email->viewBuilder()->template()) {
<add> $this->_email->viewBuilder()->template($action);
<add> }
<ide>
<ide> call_user_func_array([$this, $action], $args);
<ide>
<del> if ($this->template === null) {
<del> $this->template = $action;
<del> }
<del>
<del> $result = $this->_email
<del> ->profile((array)$this)
<del> ->send();
<add> $result = $this->_email->send();
<ide>
<ide> $this->reset();
<ide> return $result;
<ide> }
<ide>
<del> /**
<del> * Resets email instance to original config.
<del> *
<del> * @return $this object.
<del> */
<del> public function reset()
<del> {
<del> $this->_email->reset();
<del> return $this;
<del> }
<del>
<del> /**
<del> * Checks if the property exists.
<del> *
<del> * @param string $offset Property name.
<del> * @return bool True if it exists.
<del> */
<del> public function offsetExists($offset)
<del> {
<del> return property_exists($this, $offset) ||
<del> method_exists($this->_email, $offset);
<del> }
<del>
<del> /**
<del> * Gets the property value if it exists.
<del> *
<del> * @param string $offset Property name.
<del> * @return mixed Value.
<del> */
<del> public function offsetGet($offset)
<del> {
<del> if (!$this->offsetExists($offset)) {
<del> return null;
<del> }
<del>
<del> if (isset($this->{$offset})) {
<del> return $this->{$offset};
<del> }
<del>
<del> return call_user_func([$this->_email, $offset]);
<del> }
<del>
<del> /**
<del> * Sets property's value.
<del> *
<del> * @param string $offset Property name.
<del> * @param mixed $value Value.
<del> * @return void
<del> */
<del> public function offsetSet($offset, $value)
<del> {
<del> $this->{$offset} = $value;
<del> }
<del>
<del> /**
<del> * Unset a property.
<del> *
<del> * @param string $offset Property name.
<del> * @return void
<del> */
<del> public function offsetUnset($offset)
<del> {
<del> unset($this->{$offset});
<del> }
<del>
<ide> /**
<ide> * Implemented events.
<ide> *
<ide><path>tests/TestCase/Mailer/MailerTest.php
<ide> public function testLayout()
<ide> {
<ide> $result = (new TestMailer())->layout('foo');
<ide> $this->assertInstanceOf('TestApp\Mailer\TestMailer', $result);
<del> $this->assertEquals('foo', $result->layout);
<add> $this->assertEquals('foo', $result->viewBuilder()->layout());
<ide> }
<ide>
<ide> public function testProxies()
<ide> public function testSend()
<ide> ->method('test')
<ide> ->with('foo', 'bar');
<ide>
<del> $mailer->template = 'foobar';
<add> $mailer->template('foobar');
<ide> $mailer->send('test', ['foo', 'bar']);
<ide> $this->assertEquals($mailer->template, 'foobar');
<ide> }
<ide><path>tests/test_app/TestApp/Mailer/TestMailer.php
<ide> public function getEmailForAssertion()
<ide> {
<ide> return $this->_email;
<ide> }
<add>
<add> public function __call($method, $args)
<add> {
<add> if ($method === 'reset') {
<add> $this->template = $this->viewBuilder()->template();
<add> }
<add>
<add> return parent::__call($method, $args);
<add> }
<add>
<ide> } | 3 |
Javascript | Javascript | add error message | 03cdce01084b325f2ed061d4fe027dd160dd48a5 | <ide><path>src/core/DirectGeometry.js
<ide> Object.assign( DirectGeometry.prototype, {
<ide> var hasSkinWeights = skinWeights.length === vertices.length;
<ide>
<ide> //
<add>
<add> if ( faces.length === 0 ) {
<add>
<add> console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
<add>
<add> }
<ide>
<ide> for ( var i = 0; i < faces.length; i ++ ) {
<ide> | 1 |
Text | Text | update example with correct syntax (#383) | 204d3352735051d47bbecfa7ffdd14d0b5911cf6 | <ide><path>README.md
<ide> export default class Error extends React.Component {
<ide> this.props.statusCode
<ide> ? `An error ${this.props.statusCode} occurred on server`
<ide> : 'An error occurred on client'
<del> ]</p>
<add> }</p>
<ide> )
<ide> }
<ide> } | 1 |
Javascript | Javascript | collapse empty suffix parameters correctly | 53061363c7aa1ab9085273d269c6f04ac2162336 | <ide><path>src/ngResource/resource.js
<ide> * `http://example.com:8080/api`), you'll need to escape the colon character before the port
<ide> * number, like this: `$resource('http://example.com\\:8080/api')`.
<ide> *
<add> * If you are using a url with a suffix, just add the suffix, like this:
<add> * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')
<add> * or even `$resource('http://example.com/resource/:resource_id.:format')`
<add> * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
<add> * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
<add> * can escape it with `/\.`.
<add> *
<ide> * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
<ide> * `actions` methods. If any of the parameter value is a function, it will be executed every time
<ide> * when a param value needs to be obtained for a request (unless the param was overridden).
<ide> angular.module('ngResource', ['ng']).
<ide> });
<ide>
<ide> // strip trailing slashes and set the url
<del> config.url = url.replace(/\/+$/, '');
<add> url = url.replace(/\/+$/, '');
<add> // then replace collapse `/.` if found in the last URL path segment before the query
<add> // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
<add> url = url.replace(/\/\.(?=\w+($|\?))/, '.');
<add> // replace escaped `/\.` with `/.`
<add> config.url = url.replace(/\/\\\./, '/.');
<add>
<ide>
<ide> // set params - delegate param encoding to $http
<ide> forEach(params, function(value, key){
<ide><path>test/ngResource/resourceSpec.js
<ide> describe("resource", function() {
<ide> it('should not ignore leading slashes of undefinend parameters that have non-slash trailing sequence', function() {
<ide> var R = $resource('/Path/:a.foo/:b.bar/:c.baz');
<ide>
<del> $httpBackend.when('GET', '/Path/.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/0.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/false.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/1.foo/.bar/.baz').respond('{}');
<del> $httpBackend.when('GET', '/Path/2.foo/3.bar/.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/0.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/false.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/1.foo/.bar.baz').respond('{}');
<add> $httpBackend.when('GET', '/Path/2.foo/3.bar.baz').respond('{}');
<ide> $httpBackend.when('GET', '/Path/4.foo/.bar/5.baz').respond('{}');
<ide> $httpBackend.when('GET', '/Path/6.foo/7.bar/8.baz').respond('{}');
<ide>
<ide> describe("resource", function() {
<ide> expect(person.id).toEqual(456);
<ide> });
<ide>
<add> describe('suffix parameter', function() {
<add>
<add> describe('query', function() {
<add> it('should add a suffix', function() {
<add> $httpBackend.expect('GET', '/users.json').respond([{id: 1, name: 'user1'}]);
<add> var UserService = $resource('/users/:id.json', {id: '@id'});
<add> var user = UserService.query();
<add> $httpBackend.flush();
<add> expect(user).toEqualData([{id: 1, name: 'user1'}]);
<add> });
<add>
<add> it('should not require it if not provided', function(){
<add> $httpBackend.expect('GET', '/users.json').respond([{id: 1, name: 'user1'}]);
<add> var UserService = $resource('/users.json');
<add> var user = UserService.query();
<add> $httpBackend.flush();
<add> expect(user).toEqualData([{id: 1, name: 'user1'}]);
<add> });
<add>
<add> it('should work when query parameters are supplied', function() {
<add> $httpBackend.expect('GET', '/users.json?red=blue').respond([{id: 1, name: 'user1'}]);
<add> var UserService = $resource('/users/:user_id.json', {user_id: '@id'});
<add> var user = UserService.query({red: 'blue'});
<add> $httpBackend.flush();
<add> expect(user).toEqualData([{id: 1, name: 'user1'}]);
<add> });
<add>
<add> it('should work when query parameters are supplied and the format is a resource parameter', function() {
<add> $httpBackend.expect('GET', '/users.json?red=blue').respond([{id: 1, name: 'user1'}]);
<add> var UserService = $resource('/users/:user_id.:format', {user_id: '@id', format: 'json'});
<add> var user = UserService.query({red: 'blue'});
<add> $httpBackend.flush();
<add> expect(user).toEqualData([{id: 1, name: 'user1'}]);
<add> });
<add>
<add> it('should work with the action is overriden', function(){
<add> $httpBackend.expect('GET', '/users.json').respond([{id: 1, name: 'user1'}]);
<add> var UserService = $resource('/users/:user_id', {user_id: '@id'}, {
<add> query: {
<add> method: 'GET',
<add> url: '/users/:user_id.json',
<add> isArray: true
<add> }
<add> });
<add> var user = UserService.query();
<add> $httpBackend.flush();
<add> expect(user).toEqualData([ {id: 1, name: 'user1'} ]);
<add> });
<add> });
<add>
<add> describe('get', function(){
<add> it('should add them to the id', function() {
<add> $httpBackend.expect('GET', '/users/1.json').respond({id: 1, name: 'user1'});
<add> var UserService = $resource('/users/:user_id.json', {user_id: '@id'});
<add> var user = UserService.get({user_id: 1});
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 1, name: 'user1'});
<add> });
<add>
<add> it('should work when an id and query parameters are supplied', function() {
<add> $httpBackend.expect('GET', '/users/1.json?red=blue').respond({id: 1, name: 'user1'});
<add> var UserService = $resource('/users/:user_id.json', {user_id: '@id'});
<add> var user = UserService.get({user_id: 1, red: 'blue'});
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 1, name: 'user1'});
<add> });
<add>
<add> it('should work when the format is a parameter', function() {
<add> $httpBackend.expect('GET', '/users/1.json?red=blue').respond({id: 1, name: 'user1'});
<add> var UserService = $resource('/users/:user_id.:format', {user_id: '@id', format: 'json'});
<add> var user = UserService.get({user_id: 1, red: 'blue'});
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 1, name: 'user1'});
<add> });
<add>
<add> it('should work with the action is overriden', function(){
<add> $httpBackend.expect('GET', '/users/1.json').respond({id: 1, name: 'user1'});
<add> var UserService = $resource('/users/:user_id', {user_id: '@id'}, {
<add> get: {
<add> method: 'GET',
<add> url: '/users/:user_id.json'
<add> }
<add> });
<add> var user = UserService.get({user_id: 1});
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 1, name: 'user1'});
<add> });
<add> });
<add>
<add> describe("save", function() {
<add> it('should append the suffix', function() {
<add> $httpBackend.expect('POST', '/users.json', '{"name":"user1"}').respond({id: 123, name: 'user1'});
<add> var UserService = $resource('/users/:user_id.json', {user_id: '@id'});
<add> var user = UserService.save({name: 'user1'}, callback);
<add> expect(user).toEqualData({name: 'user1'});
<add> expect(callback).not.toHaveBeenCalled();
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 123, name: 'user1'});
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual(user);
<add> expect(callback.mostRecentCall.args[1]()).toEqual({});
<add> });
<add>
<add> it('should append when an id is supplied', function() {
<add> $httpBackend.expect('POST', '/users/123.json', '{"id":123,"name":"newName"}').respond({id: 123, name: 'newName'});
<add> var UserService = $resource('/users/:user_id.json', {user_id: '@id'});
<add> var user = UserService.save({id: 123, name: 'newName'}, callback);
<add> expect(callback).not.toHaveBeenCalled();
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 123, name: 'newName'});
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual(user);
<add> expect(callback.mostRecentCall.args[1]()).toEqual({});
<add> });
<add>
<add> it('should append when an id is supplied and the format is a parameter', function() {
<add> $httpBackend.expect('POST', '/users/123.json', '{"id":123,"name":"newName"}').respond({id: 123, name: 'newName'});
<add> var UserService = $resource('/users/:user_id.:format', {user_id: '@id', format: 'json'});
<add> var user = UserService.save({id: 123, name: 'newName'}, callback);
<add> expect(callback).not.toHaveBeenCalled();
<add> $httpBackend.flush();
<add> expect(user).toEqualData({id: 123, name: 'newName'});
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual(user);
<add> expect(callback.mostRecentCall.args[1]()).toEqual({});
<add> });
<add> });
<add>
<add> describe('escaping /. with /\\.', function() {
<add> it('should work with query()', function() {
<add> $httpBackend.expect('GET', '/users/.json').respond();
<add> $resource('/users/\\.json').query();
<add> });
<add> it('should work with get()', function() {
<add> $httpBackend.expect('GET', '/users/.json').respond();
<add> $resource('/users/\\.json').get();
<add> });
<add> it('should work with save()', function() {
<add> $httpBackend.expect('POST', '/users/.json').respond();
<add> $resource('/users/\\.json').save({});
<add> });
<add> });
<add> });
<ide>
<ide> describe('action-level url override', function() {
<ide>
<ide> it('should support overriding url template with static url', function() {
<ide> $httpBackend.expect('GET', '/override-url?type=Customer&typeId=123').respond({id: 'abc'});
<ide> var TypeItem = $resource('/:type/:typeId', {type: 'Order'}, {
<del> get: {
<del> method: 'GET',
<del> params: {type: 'Customer'},
<del> url: '/override-url'
<del> }
<add> get: {
<add> method: 'GET',
<add> params: {type: 'Customer'},
<add> url: '/override-url'
<add> }
<ide> });
<ide> var item = TypeItem.get({typeId: 123});
<ide> $httpBackend.flush(); | 2 |
Javascript | Javascript | destroy the socket properly and add tests | b60b18379ddf4dfb455080c2e163846af06a4c1e | <ide><path>lib/internal/http2/core.js
<ide> class Http2Session extends EventEmitter {
<ide> // Otherwise, destroy immediately.
<ide> if (!socket.destroyed) {
<ide> if (!error) {
<del> setImmediate(socket.end.bind(socket));
<add> setImmediate(socket.destroy.bind(socket));
<ide> } else {
<ide> socket.destroy(error);
<ide> }
<ide><path>test/parallel/test-http2-many-writes-and-destroy.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>const http2 = require('http2');
<add>
<add>{
<add> const server = http2.createServer((req, res) => {
<add> req.pipe(res);
<add> });
<add>
<add> server.listen(0, () => {
<add> const url = `http://localhost:${server.address().port}`;
<add> const client = http2.connect(url);
<add> const req = client.request({ ':method': 'POST' });
<add>
<add> for (let i = 0; i < 4000; i++) {
<add> req.write(Buffer.alloc(6));
<add> }
<add>
<add> req.on('close', common.mustCall(() => {
<add> console.log('(req onclose)');
<add> server.close();
<add> client.close();
<add> }));
<add>
<add> req.once('data', common.mustCall(() => req.destroy()));
<add> });
<add>}
<ide><path>test/parallel/test-http2-pipe.js
<ide> server.listen(0, common.mustCall(() => {
<ide> const client = http2.connect(`http://localhost:${server.address().port}`);
<ide>
<ide> const req = client.request({ ':method': 'POST' });
<add>
<ide> req.on('response', common.mustCall());
<ide> req.resume();
<ide>
<ide><path>test/parallel/test-http2-server-close-callback.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const http2 = require('http2');
<add>
<add>const server = http2.createServer();
<add>
<add>server.listen(0, common.mustCall(() => {
<add> const client = http2.connect(`http://localhost:${server.address().port}`);
<add> client.on('error', (err) => {
<add> if (err.code !== 'ECONNRESET')
<add> throw err;
<add> });
<add>}));
<add>
<add>server.on('session', common.mustCall((s) => {
<add> setImmediate(() => {
<add> server.close(common.mustCall());
<add> s.destroy();
<add> });
<add>}));
<ide><path>test/parallel/test-http2-server-stream-session-destroy.js
<ide> server.on('stream', common.mustCall((stream) => {
<ide>
<ide> server.listen(0, common.mustCall(() => {
<ide> const client = h2.connect(`http://localhost:${server.address().port}`);
<del> client.on('error', () => {});
<add> client.on('error', (err) => {
<add> if (err.code !== 'ECONNRESET')
<add> throw err;
<add> });
<ide> const req = client.request();
<ide> req.resume();
<ide> req.on('end', common.mustCall());
<del> req.on('close', common.mustCall(() => server.close()));
<del> req.on('error', () => {});
<add> req.on('close', common.mustCall(() => server.close(common.mustCall())));
<add> req.on('error', (err) => {
<add> if (err.code !== 'ECONNRESET')
<add> throw err;
<add> });
<ide> }));
<ide><path>test/parallel/test-http2-session-unref.js
<ide> server.listen(0, common.mustCall(() => {
<ide> // unref destroyed client
<ide> {
<ide> const client = http2.connect(`http://localhost:${port}`);
<del> client.destroy();
<del> client.unref();
<add>
<add> client.on('connect', common.mustCall(() => {
<add> client.destroy();
<add> client.unref();
<add> }));
<ide> }
<ide>
<ide> // unref destroyed client
<ide> {
<ide> const client = http2.connect(`http://localhost:${port}`, {
<ide> createConnection: common.mustCall(() => clientSide)
<ide> });
<del> client.destroy();
<del> client.unref();
<add>
<add> client.on('connect', common.mustCall(() => {
<add> client.destroy();
<add> client.unref();
<add> }));
<ide> }
<ide> }));
<ide> server.emit('connection', serverSide);
<ide><path>test/sequential/test-http2-max-session-memory.js
<ide> const largeBuffer = Buffer.alloc(1e6);
<ide> const server = http2.createServer({ maxSessionMemory: 1 });
<ide>
<ide> server.on('stream', common.mustCall((stream) => {
<add> stream.on('error', (err) => {
<add> if (err.code !== 'ECONNRESET')
<add> throw err;
<add> });
<ide> stream.respond();
<ide> stream.end(largeBuffer);
<ide> })); | 7 |
Ruby | Ruby | add space to conform with style | 6a1715111e16e07a30bd61eaecf059fd90732e59 | <ide><path>activerecord/lib/active_record/named_scope.rb
<ide> def scoped(options = nil)
<ide> # end
<ide> #
<ide> # def self.titles
<del> # map{|article| article.title}
<add> # map {|article| article.title}
<ide> # end
<ide> #
<ide> # end | 1 |
Mixed | Javascript | remove data checks and always re-parse data | 8e7bde25c46c3c76c9c10119e93d2ea744e13f70 | <ide><path>docs/docs/getting-started/v3-migration.md
<ide> The following properties and methods were removed:
<ide>
<ide> * `helpers.addEvent`
<ide> * `helpers.aliasPixel`
<add>* `helpers.arrayEquals`
<ide> * `helpers.configMerge`
<ide> * `helpers.findIndex`
<ide> * `helpers.findNextWhere`
<ide><path>src/core/core.datasetController.js
<ide> import Animations from './core.animations';
<del>import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf, arrayEquals} from '../helpers/helpers.core';
<add>import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf} from '../helpers/helpers.core';
<ide> import {resolve} from '../helpers/helpers.options';
<ide> import {getHoverColor} from '../helpers/helpers.color';
<ide> import {sign} from '../helpers/helpers.math';
<ide> export default class DatasetController {
<ide> this._config = undefined;
<ide> this._parsing = false;
<ide> this._data = undefined;
<del> this._dataCopy = undefined;
<del> this._dataModified = false;
<ide> this._objectData = undefined;
<del> this._labels = undefined;
<ide> this._scaleStacked = {};
<ide>
<ide> this.initialize();
<ide> export default class DatasetController {
<ide> }
<ide>
<ide> /**
<del> * @return {boolean} whether the data was modified
<ide> * @private
<ide> */
<ide> _dataCheck() {
<ide> export default class DatasetController {
<ide> // the internal meta data accordingly.
<ide>
<ide> if (isObject(data)) {
<del> // Object data is currently monitored for replacement only
<del> if (me._objectData === data) {
<del> return false;
<del> }
<ide> me._data = convertObjectDataToArray(data);
<del> me._objectData = data;
<del> } else {
<del> if (me._data === data && !me._dataModified && arrayEquals(data, me._dataCopy)) {
<del> return false;
<del> }
<del>
<add> } else if (me._data !== data) {
<ide> if (me._data) {
<ide> // This case happens when the user replaced the data array instance.
<ide> unlistenArrayEvents(me._data, me);
<ide> }
<del>
<del> // Store a copy to detect direct modifications.
<del> // Note: This is suboptimal, but better than always parsing the data
<del> me._dataCopy = data.slice(0);
<del>
<del> me._dataModified = false;
<del>
<ide> if (data && Object.isExtensible(data)) {
<ide> listenArrayEvents(data, me);
<ide> }
<ide> me._data = data;
<ide> }
<del> return true;
<del> }
<del>
<del> /**
<del> * @private
<del> */
<del> _labelCheck() {
<del> const me = this;
<del> const iScale = me._cachedMeta.iScale;
<del> const labels = iScale ? iScale.getLabels() : me.chart.data.labels;
<del>
<del> if (me._labels === labels) {
<del> return false;
<del> }
<del>
<del> me._labels = labels;
<del> return true;
<ide> }
<ide>
<ide> addElements() {
<ide> export default class DatasetController {
<ide>
<ide> buildOrUpdateElements() {
<ide> const me = this;
<del> const dataChanged = me._dataCheck();
<del> const labelsChanged = me._labelCheck();
<del> const scaleChanged = me._scaleCheck();
<ide> const meta = me._cachedMeta;
<ide> const dataset = me.getDataset();
<ide> let stackChanged = false;
<ide>
<add> me._dataCheck();
<add>
<ide> // make sure cached _stacked status is current
<ide> meta._stacked = isStacked(meta.vScale, meta);
<ide>
<ide> export default class DatasetController {
<ide>
<ide> // Re-sync meta data in case the user replaced the data array or if we missed
<ide> // any updates and so make sure that we handle number of datapoints changing.
<del> me._resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged);
<add> me._resyncElements();
<ide>
<ide> // if stack changed, update stack values for the whole dataset
<ide> if (stackChanged) {
<ide> export default class DatasetController {
<ide> }
<ide> }
<ide>
<del> /**
<del> * @private
<del> */
<del> _scaleCheck() {
<del> const me = this;
<del> const meta = me._cachedMeta;
<del> const iScale = meta.iScale;
<del> const vScale = meta.vScale;
<del> const cache = me._scaleStacked;
<del> return !cache ||
<del> !iScale ||
<del> !vScale ||
<del> cache[iScale.id] !== iScale.options.stacked ||
<del> cache[vScale.id] !== vScale.options.stacked;
<del> }
<del>
<ide> /**
<ide> * @return {number|boolean}
<ide> * @protected
<ide> export default class DatasetController {
<ide> /**
<ide> * @private
<ide> */
<del> _resyncElements(changed) {
<add> _resyncElements() {
<ide> const me = this;
<ide> const meta = me._cachedMeta;
<ide> const numMeta = meta.data.length;
<ide> const numData = me._data.length;
<ide>
<ide> if (numData > numMeta) {
<ide> me._insertElements(numMeta, numData - numMeta);
<del> if (changed && numMeta) {
<del> // _insertElements parses the new elements. The old ones might need parsing too.
<del> me.parse(0, numMeta);
<del> }
<ide> } else if (numData < numMeta) {
<ide> meta.data.splice(numData, numMeta - numData);
<ide> meta._parsed.splice(numData, numMeta - numData);
<del> me.parse(0, numData);
<del> } else if (changed) {
<del> me.parse(0, numData);
<ide> }
<add> // Re-parse the old elements (new elements are parsed in _insertElements)
<add> me.parse(0, Math.min(numData, numMeta));
<ide> }
<ide>
<ide> /**
<ide> export default class DatasetController {
<ide> _onDataPush() {
<ide> const count = arguments.length;
<ide> this._insertElements(this.getDataset().data.length - count, count);
<del> this._dataModified = true;
<ide> }
<ide>
<ide> /**
<ide> * @private
<ide> */
<ide> _onDataPop() {
<ide> this._removeElements(this._cachedMeta.data.length - 1, 1);
<del> this._dataModified = true;
<ide> }
<ide>
<ide> /**
<ide> * @private
<ide> */
<ide> _onDataShift() {
<ide> this._removeElements(0, 1);
<del> this._dataModified = true;
<ide> }
<ide>
<ide> /**
<ide> export default class DatasetController {
<ide> _onDataSplice(start, count) {
<ide> this._removeElements(start, count);
<ide> this._insertElements(start, arguments.length - 2);
<del> this._dataModified = true;
<ide> }
<ide>
<ide> /**
<ide> * @private
<ide> */
<ide> _onDataUnshift() {
<ide> this._insertElements(0, arguments.length);
<del> this._dataModified = true;
<ide> }
<ide> }
<ide>
<ide><path>src/helpers/helpers.core.js
<ide> export function each(loopable, fn, thisArg, reverse) {
<ide> }
<ide> }
<ide>
<del>/**
<del> * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
<del> * @see https://stackoverflow.com/a/14853974
<del> * @param {Array} a0 - The array to compare
<del> * @param {Array} a1 - The array to compare
<del> * @returns {boolean}
<del> */
<del>export function arrayEquals(a0, a1) {
<del> let i, ilen, v0, v1;
<del>
<del> if (!a0 || !a1 || a0.length !== a1.length) {
<del> return false;
<del> }
<del>
<del> for (i = 0, ilen = a0.length; i < ilen; ++i) {
<del> v0 = a0[i];
<del> v1 = a1[i];
<del>
<del> if (v0 instanceof Array && v1 instanceof Array) {
<del> if (!arrayEquals(v0, v1)) {
<del> return false;
<del> }
<del> } else if (v0 !== v1) {
<del> // NOTE: two different object instances will never be equal: {x:20} != {x:20}
<del> return false;
<del> }
<del> }
<del>
<del> return true;
<del>}
<del>
<ide> /**
<ide> * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
<ide> * @param {Array} a0 - The array to compare
<ide><path>test/specs/core.datasetController.tests.js
<ide> describe('Chart.DatasetController', function() {
<ide> expect(meta.data[0].x).toEqual(firstX);
<ide> });
<ide>
<add> // https://github.com/chartjs/Chart.js/issues/7445
<add> it('should re-synchronize metadata when data is objects and directly altered', function() {
<add> var data = [{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}];
<add> var chart = acquireChart({
<add> type: 'line',
<add> data: {
<add> labels: ['a', 'b', 'c'],
<add> datasets: [{
<add> data,
<add> fill: true
<add> }]
<add> }
<add> });
<add>
<add> var meta = chart.getDatasetMeta(0);
<add>
<add> expect(meta.data.length).toBe(3);
<add> const y3 = meta.data[2].y;
<add>
<add> data[0].y = 3;
<add> chart.update();
<add> expect(meta.data[0].y).toEqual(y3);
<add> });
<add>
<ide> it('should re-synchronize metadata when scaleID changes', function() {
<ide> var chart = acquireChart({
<ide> type: 'line',
<ide><path>test/specs/helpers.core.tests.js
<ide> describe('Chart.helpers.core', function() {
<ide> });
<ide> });
<ide>
<del> describe('arrayEquals', function() {
<del> it('should return false if arrays are not the same', function() {
<del> expect(helpers.arrayEquals([], [42])).toBeFalsy();
<del> expect(helpers.arrayEquals([42], ['42'])).toBeFalsy();
<del> expect(helpers.arrayEquals([1, 2, 3], [1, 2, 3, 4])).toBeFalsy();
<del> expect(helpers.arrayEquals(['foo', 'bar'], ['bar', 'foo'])).toBeFalsy();
<del> expect(helpers.arrayEquals([1, 2, 3], [1, 2, 'foo'])).toBeFalsy();
<del> expect(helpers.arrayEquals([1, 2, [3, 4]], [1, 2, [3, 'foo']])).toBeFalsy();
<del> expect(helpers.arrayEquals([{a: 42}], [{a: 42}])).toBeFalsy();
<del> });
<del> it('should return false if arrays are not the same', function() {
<del> var o0 = {};
<del> var o1 = {};
<del> var o2 = {};
<del>
<del> expect(helpers.arrayEquals([], [])).toBeTruthy();
<del> expect(helpers.arrayEquals([1, 2, 3], [1, 2, 3])).toBeTruthy();
<del> expect(helpers.arrayEquals(['foo', 'bar'], ['foo', 'bar'])).toBeTruthy();
<del> expect(helpers.arrayEquals([true, false, true], [true, false, true])).toBeTruthy();
<del> expect(helpers.arrayEquals([o0, o1, o2], [o0, o1, o2])).toBeTruthy();
<del> });
<del> });
<del>
<ide> describe('_elementsEqual', function() {
<ide> it('should return true if arrays are the same', function() {
<ide> expect(helpers._elementsEqual( | 5 |
Text | Text | fix advisory link | a64970db92b3092547ee055d7121c2963dd155e0 | <ide><path>CHANGELOG.md
<ide> Changelog
<ide>
<ide> * Release Apr 3 2022
<ide>
<del>Address https://github.com/advisories/GHSA-8hfj-j24r-96c4
<add>Address https://github.com/moment/moment/security/advisories/GHSA-8hfj-j24r-96c4
<ide>
<ide> ### 2.29.1 [See full changelog](https://gist.github.com/marwahaha/cc478ba01a1292ab4bd4e861d164d99b)
<ide> | 1 |
Ruby | Ruby | replace #max_by with #max | 92d65aace7edfc751c342c019e895d33bbea013c | <ide><path>Library/Contributions/cmd/brew-linkapps.rb
<ide> kegs = rack.subdirs.map { |d| Keg.new(d) }
<ide> next if kegs.empty?
<ide>
<del> keg = kegs.detect(&:linked?) || kegs.max_by(&:version)
<add> keg = kegs.detect(&:linked?) || kegs.max {|a,b| a.version <=> b.version}
<ide>
<ide> Dir["#{keg}/*.app", "#{keg}/bin/*.app", "#{keg}/libexec/*.app"].each do |app|
<ide> puts "Linking #{app}" | 1 |
Ruby | Ruby | fix bad reference to local_bottle_path | 549b07e8df341b25f218b9251ab60644519f1bdb | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_filename f, bottle_version=nil
<ide>
<ide> def install_bottle? f
<ide> return true if ARGV.include? '--install-bottle'
<del> return true if f.downloader and f.downloader.local_bottle_path
<add> return true if f.downloader and defined? f.downloader.local_bottle_path \
<add> and f.downloader.local_bottle_path
<ide> not ARGV.build_from_source? \
<ide> and MacOS.bottles_supported? \
<ide> and ARGV.used_options(f).empty? \ | 1 |
Ruby | Ruby | extract common dirty tracking methods in amo | f97dae5ebe2f19273d3f92e5ea9baba788c8e89f | <ide><path>activemodel/lib/active_model.rb
<ide> module ActiveModel
<ide> autoload :AttributeMethods, 'active_model/attribute_methods'
<ide> autoload :Conversion, 'active_model/conversion'
<ide> autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
<add> autoload :Dirty, 'active_model/dirty'
<ide> autoload :Errors, 'active_model/errors'
<ide> autoload :Name, 'active_model/naming'
<ide> autoload :Naming, 'active_model/naming'
<ide><path>activemodel/lib/active_model/dirty.rb
<add>module ActiveModel
<add> # Track unsaved attribute changes.
<add> #
<add> # A newly instantiated object is unchanged:
<add> # person = Person.find_by_name('Uncle Bob')
<add> # person.changed? # => false
<add> #
<add> # Change the name:
<add> # person.name = 'Bob'
<add> # person.changed? # => true
<add> # person.name_changed? # => true
<add> # person.name_was # => 'Uncle Bob'
<add> # person.name_change # => ['Uncle Bob', 'Bob']
<add> # person.name = 'Bill'
<add> # person.name_change # => ['Uncle Bob', 'Bill']
<add> #
<add> # Save the changes:
<add> # person.save
<add> # person.changed? # => false
<add> # person.name_changed? # => false
<add> #
<add> # Assigning the same value leaves the attribute unchanged:
<add> # person.name = 'Bill'
<add> # person.name_changed? # => false
<add> # person.name_change # => nil
<add> #
<add> # Which attributes have changed?
<add> # person.name = 'Bob'
<add> # person.changed # => ['name']
<add> # person.changes # => { 'name' => ['Bill', 'Bob'] }
<add> #
<add> # Resetting an attribute returns it to its original state:
<add> # person.reset_name! # => 'Bill'
<add> # person.changed? # => false
<add> # person.name_changed? # => false
<add> # person.name # => 'Bill'
<add> #
<add> # Before modifying an attribute in-place:
<add> # person.name_will_change!
<add> # person.name << 'y'
<add> # person.name_change # => ['Bill', 'Billy']
<add> module Dirty
<add> extend ActiveSupport::Concern
<add> include ActiveModel::AttributeMethods
<add>
<add> included do
<add> attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
<add> attribute_method_affix :prefix => 'reset_', :suffix => '!'
<add> end
<add>
<add> # Do any attributes have unsaved changes?
<add> # person.changed? # => false
<add> # person.name = 'bob'
<add> # person.changed? # => true
<add> def changed?
<add> !changed_attributes.empty?
<add> end
<add>
<add> # List of attributes with unsaved changes.
<add> # person.changed # => []
<add> # person.name = 'bob'
<add> # person.changed # => ['name']
<add> def changed
<add> changed_attributes.keys
<add> end
<add>
<add> # Map of changed attrs => [original value, new value].
<add> # person.changes # => {}
<add> # person.name = 'bob'
<add> # person.changes # => { 'name' => ['bill', 'bob'] }
<add> def changes
<add> changed.inject({}) { |h, attr| h[attr] = attribute_change(attr); h }
<add> end
<add>
<add> private
<add> # Map of change <tt>attr => original value</tt>.
<add> def changed_attributes
<add> @changed_attributes ||= {}
<add> end
<add>
<add> # Handle <tt>*_changed?</tt> for +method_missing+.
<add> def attribute_changed?(attr)
<add> changed_attributes.include?(attr)
<add> end
<add>
<add> # Handle <tt>*_change</tt> for +method_missing+.
<add> def attribute_change(attr)
<add> [changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
<add> end
<add>
<add> # Handle <tt>*_was</tt> for +method_missing+.
<add> def attribute_was(attr)
<add> attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
<add> end
<add>
<add> # Handle <tt>*_will_change!</tt> for +method_missing+.
<add> def attribute_will_change!(attr)
<add> begin
<add> value = __send__(attr)
<add> value = value.duplicable? ? value.clone : value
<add> rescue TypeError, NoMethodError
<add> end
<add>
<add> changed_attributes[attr] = value
<add> end
<add>
<add> # Handle <tt>reset_*!</tt> for +method_missing+.
<add> def reset_attribute!(attr)
<add> __send__("#{attr}=", changed_attributes[attr]) if attribute_changed?(attr)
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<add>require 'active_support/core_ext/object/tap'
<add>
<ide> module ActiveRecord
<ide> module AttributeMethods
<del> # Track unsaved attribute changes.
<del> #
<del> # A newly instantiated object is unchanged:
<del> # person = Person.find_by_name('Uncle Bob')
<del> # person.changed? # => false
<del> #
<del> # Change the name:
<del> # person.name = 'Bob'
<del> # person.changed? # => true
<del> # person.name_changed? # => true
<del> # person.name_was # => 'Uncle Bob'
<del> # person.name_change # => ['Uncle Bob', 'Bob']
<del> # person.name = 'Bill'
<del> # person.name_change # => ['Uncle Bob', 'Bill']
<del> #
<del> # Save the changes:
<del> # person.save
<del> # person.changed? # => false
<del> # person.name_changed? # => false
<del> #
<del> # Assigning the same value leaves the attribute unchanged:
<del> # person.name = 'Bill'
<del> # person.name_changed? # => false
<del> # person.name_change # => nil
<del> #
<del> # Which attributes have changed?
<del> # person.name = 'Bob'
<del> # person.changed # => ['name']
<del> # person.changes # => { 'name' => ['Bill', 'Bob'] }
<del> #
<del> # Resetting an attribute returns it to its original state:
<del> # person.reset_name! # => 'Bill'
<del> # person.changed? # => false
<del> # person.name_changed? # => false
<del> # person.name # => 'Bill'
<del> #
<del> # Before modifying an attribute in-place:
<del> # person.name_will_change!
<del> # person.name << 'y'
<del> # person.name_change # => ['Bill', 'Billy']
<ide> module Dirty
<ide> extend ActiveSupport::Concern
<del>
<del> DIRTY_AFFIXES = [
<del> { :suffix => '_changed?' },
<del> { :suffix => '_change' },
<del> { :suffix => '_will_change!' },
<del> { :suffix => '_was' },
<del> { :prefix => 'reset_', :suffix => '!' }
<del> ]
<add> include ActiveModel::Dirty
<ide>
<ide> included do
<del> attribute_method_affix *DIRTY_AFFIXES
<del>
<del> alias_method_chain :save, :dirty
<del> alias_method_chain :save!, :dirty
<del> alias_method_chain :update, :dirty
<del> alias_method_chain :reload, :dirty
<add> alias_method_chain :save, :dirty
<add> alias_method_chain :save!, :dirty
<add> alias_method_chain :update, :dirty
<add> alias_method_chain :reload, :dirty
<ide>
<ide> superclass_delegating_accessor :partial_updates
<ide> self.partial_updates = true
<ide> end
<ide>
<del> # Do any attributes have unsaved changes?
<del> # person.changed? # => false
<del> # person.name = 'bob'
<del> # person.changed? # => true
<del> def changed?
<del> !changed_attributes.empty?
<del> end
<del>
<del> # List of attributes with unsaved changes.
<del> # person.changed # => []
<del> # person.name = 'bob'
<del> # person.changed # => ['name']
<del> def changed
<del> changed_attributes.keys
<del> end
<del>
<del> # Map of changed attrs => [original value, new value].
<del> # person.changes # => {}
<del> # person.name = 'bob'
<del> # person.changes # => { 'name' => ['bill', 'bob'] }
<del> def changes
<del> changed.inject({}) { |h, attr| h[attr] = attribute_change(attr); h }
<del> end
<del>
<ide> # Attempts to +save+ the record and clears changed attributes if successful.
<ide> def save_with_dirty(*args) #:nodoc:
<ide> if status = save_without_dirty(*args)
<ide> def save_with_dirty(*args) #:nodoc:
<ide>
<ide> # Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
<ide> def save_with_dirty!(*args) #:nodoc:
<del> status = save_without_dirty!(*args)
<del> changed_attributes.clear
<del> status
<add> save_without_dirty!(*args).tap { changed_attributes.clear }
<ide> end
<ide>
<ide> # <tt>reload</tt> the record and clears changed attributes.
<ide> def reload_with_dirty(*args) #:nodoc:
<del> record = reload_without_dirty(*args)
<del> changed_attributes.clear
<del> record
<add> reload_without_dirty(*args).tap { changed_attributes.clear }
<ide> end
<ide>
<ide> private
<del> # Map of change <tt>attr => original value</tt>.
<del> def changed_attributes
<del> @changed_attributes ||= {}
<del> end
<del>
<del> # Handle <tt>*_changed?</tt> for +method_missing+.
<del> def attribute_changed?(attr)
<del> changed_attributes.include?(attr)
<del> end
<del>
<del> # Handle <tt>*_change</tt> for +method_missing+.
<del> def attribute_change(attr)
<del> [changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
<del> end
<del>
<del> # Handle <tt>*_was</tt> for +method_missing+.
<del> def attribute_was(attr)
<del> attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
<del> end
<del>
<del> # Handle <tt>reset_*!</tt> for +method_missing+.
<del> def reset_attribute!(attr)
<del> self[attr] = changed_attributes[attr] if attribute_changed?(attr)
<del> end
<del>
<del> # Handle <tt>*_will_change!</tt> for +method_missing+.
<del> def attribute_will_change!(attr)
<del> changed_attributes[attr] = clone_attribute_value(:read_attribute, attr)
<del> end
<del>
<ide> # Wrap write_attribute to remember original attribute value.
<ide> def write_attribute(attr, value)
<ide> attr = attr.to_s | 3 |
Go | Go | move the inspect code away from the image service | b4ffe3a9fb9d25abb1690c506e7a2cb59249c107 | <ide><path>api/server/router/image/backend.go
<ide> import (
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/api/types/image"
<ide> "github.com/docker/docker/api/types/registry"
<add> dockerimage "github.com/docker/docker/image"
<ide> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> type imageBackend interface {
<ide> ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error)
<ide> ImageHistory(imageName string) ([]*image.HistoryResponseItem, error)
<ide> Images(ctx context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error)
<del> LookupImage(name string) (*types.ImageInspect, error)
<add> GetImage(refOrID string, platform *specs.Platform) (retImg *dockerimage.Image, retErr error)
<ide> TagImage(imageName, repository, tag string) (string, error)
<ide> ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error)
<ide> }
<ide><path>api/server/router/image/image.go
<ide> package image // import "github.com/docker/docker/api/server/router/image"
<ide>
<ide> import (
<ide> "github.com/docker/docker/api/server/router"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/layer"
<add> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // imageRouter is a router to talk with the image controller
<ide> type imageRouter struct {
<del> backend Backend
<del> routes []router.Route
<add> backend Backend
<add> referenceBackend reference.Store
<add> imageStore image.Store
<add> layerStore layer.Store
<add> routes []router.Route
<ide> }
<ide>
<ide> // NewRouter initializes a new image router
<del>func NewRouter(backend Backend) router.Router {
<del> r := &imageRouter{backend: backend}
<add>func NewRouter(backend Backend, referenceBackend reference.Store, imageStore image.Store, layerStore layer.Store) router.Router {
<add> r := &imageRouter{
<add> backend: backend,
<add> referenceBackend: referenceBackend,
<add> imageStore: imageStore,
<add> layerStore: layerStore,
<add> }
<ide> r.initRoutes()
<ide> return r
<ide> }
<ide><path>api/server/router/image/image_routes.go
<ide> import (
<ide> "net/http"
<ide> "strconv"
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/containerd/containerd/platforms"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/api/types/versions"
<ide> "github.com/docker/docker/errdefs"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> func (s *imageRouter) deleteImages(ctx context.Context, w http.ResponseWriter, r
<ide> }
<ide>
<ide> func (s *imageRouter) getImagesByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> imageInspect, err := s.backend.LookupImage(vars["name"])
<add> image, err := s.backend.GetImage(vars["name"], nil)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> imageInspect, err := s.toImageInspect(image)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> return httputils.WriteJSON(w, http.StatusOK, imageInspect)
<ide> }
<ide>
<add>func (s *imageRouter) toImageInspect(img *image.Image) (*types.ImageInspect, error) {
<add> refs := s.referenceBackend.References(img.ID().Digest())
<add> repoTags := []string{}
<add> repoDigests := []string{}
<add> for _, ref := range refs {
<add> switch ref.(type) {
<add> case reference.NamedTagged:
<add> repoTags = append(repoTags, reference.FamiliarString(ref))
<add> case reference.Canonical:
<add> repoDigests = append(repoDigests, reference.FamiliarString(ref))
<add> }
<add> }
<add>
<add> var size int64
<add> var layerMetadata map[string]string
<add> layerID := img.RootFS.ChainID()
<add> if layerID != "" {
<add> l, err := s.layerStore.Get(layerID)
<add> if err != nil {
<add> return nil, err
<add> }
<add> defer layer.ReleaseAndLog(s.layerStore, l)
<add> size = l.Size()
<add> layerMetadata, err = l.Metadata()
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> comment := img.Comment
<add> if len(comment) == 0 && len(img.History) > 0 {
<add> comment = img.History[len(img.History)-1].Comment
<add> }
<add>
<add> lastUpdated, err := s.imageStore.GetLastUpdated(img.ID())
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> return &types.ImageInspect{
<add> ID: img.ID().String(),
<add> RepoTags: repoTags,
<add> RepoDigests: repoDigests,
<add> Parent: img.Parent.String(),
<add> Comment: comment,
<add> Created: img.Created.Format(time.RFC3339Nano),
<add> Container: img.Container,
<add> ContainerConfig: &img.ContainerConfig,
<add> DockerVersion: img.DockerVersion,
<add> Author: img.Author,
<add> Config: img.Config,
<add> Architecture: img.Architecture,
<add> Variant: img.Variant,
<add> Os: img.OperatingSystem(),
<add> OsVersion: img.OSVersion,
<add> Size: size,
<add> VirtualSize: size, // TODO: field unused, deprecate
<add> GraphDriver: types.GraphDriverData{
<add> Name: s.layerStore.DriverName(),
<add> Data: layerMetadata,
<add> },
<add> RootFS: rootFSToAPIType(img.RootFS),
<add> Metadata: types.ImageMetadata{
<add> LastTagTime: lastUpdated,
<add> },
<add> }, nil
<add>}
<add>
<add>func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
<add> var layers []string
<add> for _, l := range rootfs.DiffIDs {
<add> layers = append(layers, l.String())
<add> }
<add> return types.RootFS{
<add> Type: rootfs.Type,
<add> Layers: layers,
<add> }
<add>}
<add>
<ide> func (s *imageRouter) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := httputils.ParseForm(r); err != nil {
<ide> return err
<ide><path>cmd/dockerd/daemon.go
<ide> func initRouter(opts routerOptions) {
<ide> // we need to add the checkpoint router before the container router or the DELETE gets masked
<ide> checkpointrouter.NewRouter(opts.daemon, decoder),
<ide> container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
<del> image.NewRouter(opts.daemon.ImageService()),
<add> image.NewRouter(
<add> opts.daemon.ImageService(),
<add> opts.daemon.ReferenceStore,
<add> opts.daemon.ImageService().DistributionServices().ImageStore,
<add> opts.daemon.ImageService().DistributionServices().LayerStore,
<add> ),
<ide> systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.features),
<ide> volume.NewRouter(opts.daemon.VolumesService(), opts.cluster),
<ide> build.NewRouter(opts.buildBackend, opts.daemon, opts.features),
<ide><path>daemon/cluster/executor/backend.go
<ide> import (
<ide> containerpkg "github.com/docker/docker/container"
<ide> clustertypes "github.com/docker/docker/daemon/cluster/provider"
<ide> networkSettings "github.com/docker/docker/daemon/network"
<add> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/libnetwork"
<ide> "github.com/docker/docker/libnetwork/cluster"
<ide> networktypes "github.com/docker/docker/libnetwork/types"
<ide> type VolumeBackend interface {
<ide> type ImageBackend interface {
<ide> PullImage(ctx context.Context, image, tag string, platform *specs.Platform, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error
<ide> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, error)
<del> LookupImage(name string) (*types.ImageInspect, error)
<add> GetImage(refOrID string, platform *specs.Platform) (retImg *image.Image, retErr error)
<ide> }
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> func (c *containerAdapter) pullImage(ctx context.Context) error {
<ide> named, err := reference.ParseNormalizedNamed(spec.Image)
<ide> if err == nil {
<ide> if _, ok := named.(reference.Canonical); ok {
<del> _, err := c.imageBackend.LookupImage(spec.Image)
<add> _, err := c.imageBackend.GetImage(spec.Image, nil)
<ide> if err == nil {
<ide> return nil
<ide> }
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> cluster Cluster
<ide> genericResources []swarm.GenericResource
<ide> metricsPluginListener net.Listener
<add> ReferenceStore refstore.Store
<ide>
<ide> machineMemory uint64
<ide>
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> if err != nil {
<ide> return nil, fmt.Errorf("Couldn't create reference store repository: %s", err)
<ide> }
<add> d.ReferenceStore = rs
<ide>
<ide> distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
<ide> if err != nil {
<ide><path>daemon/images/image_inspect.go
<del>package images // import "github.com/docker/docker/daemon/images"
<del>
<del>import (
<del> "time"
<del>
<del> "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/image"
<del> "github.com/docker/docker/layer"
<del> "github.com/pkg/errors"
<del>)
<del>
<del>// LookupImage looks up an image by name and returns it as an ImageInspect
<del>// structure.
<del>func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) {
<del> img, err := i.GetImage(name, nil)
<del> if err != nil {
<del> return nil, errors.Wrapf(err, "no such image: %s", name)
<del> }
<del>
<del> refs := i.referenceStore.References(img.ID().Digest())
<del> repoTags := []string{}
<del> repoDigests := []string{}
<del> for _, ref := range refs {
<del> switch ref.(type) {
<del> case reference.NamedTagged:
<del> repoTags = append(repoTags, reference.FamiliarString(ref))
<del> case reference.Canonical:
<del> repoDigests = append(repoDigests, reference.FamiliarString(ref))
<del> }
<del> }
<del>
<del> var size int64
<del> var layerMetadata map[string]string
<del> layerID := img.RootFS.ChainID()
<del> if layerID != "" {
<del> l, err := i.layerStore.Get(layerID)
<del> if err != nil {
<del> return nil, err
<del> }
<del> defer layer.ReleaseAndLog(i.layerStore, l)
<del> size = l.Size()
<del> layerMetadata, err = l.Metadata()
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> comment := img.Comment
<del> if len(comment) == 0 && len(img.History) > 0 {
<del> comment = img.History[len(img.History)-1].Comment
<del> }
<del>
<del> lastUpdated, err := i.imageStore.GetLastUpdated(img.ID())
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> return &types.ImageInspect{
<del> ID: img.ID().String(),
<del> RepoTags: repoTags,
<del> RepoDigests: repoDigests,
<del> Parent: img.Parent.String(),
<del> Comment: comment,
<del> Created: img.Created.Format(time.RFC3339Nano),
<del> Container: img.Container,
<del> ContainerConfig: &img.ContainerConfig,
<del> DockerVersion: img.DockerVersion,
<del> Author: img.Author,
<del> Config: img.Config,
<del> Architecture: img.Architecture,
<del> Variant: img.Variant,
<del> Os: img.OperatingSystem(),
<del> OsVersion: img.OSVersion,
<del> Size: size,
<del> VirtualSize: size, // TODO: field unused, deprecate
<del> GraphDriver: types.GraphDriverData{
<del> Name: i.layerStore.DriverName(),
<del> Data: layerMetadata,
<del> },
<del> RootFS: rootFSToAPIType(img.RootFS),
<del> Metadata: types.ImageMetadata{
<del> LastTagTime: lastUpdated,
<del> },
<del> }, nil
<del>}
<del>
<del>func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
<del> var layers []string
<del> for _, l := range rootfs.DiffIDs {
<del> layers = append(layers, l.String())
<del> }
<del> return types.RootFS{
<del> Type: rootfs.Type,
<del> Layers: layers,
<del> }
<del>} | 8 |
Python | Python | add more type hints in celerykubernetesexecutor | 420367d843301e9fc942019586bc9f90f6680ece | <ide><path>airflow/executors/celery_kubernetes_executor.py
<ide> class CeleryKubernetesExecutor(LoggingMixin):
<ide>
<ide> KUBERNETES_QUEUE = conf.get('celery_kubernetes_executor', 'kubernetes_queue')
<ide>
<del> def __init__(self, celery_executor, kubernetes_executor):
<add> def __init__(self, celery_executor: CeleryExecutor, kubernetes_executor: KubernetesExecutor):
<ide> super().__init__()
<ide> self._job_id: Optional[str] = None
<ide> self.celery_executor = celery_executor
<ide> def running(self) -> Set[TaskInstanceKey]:
<ide> return self.celery_executor.running.union(self.kubernetes_executor.running)
<ide>
<ide> @property
<del> def job_id(self):
<add> def job_id(self) -> Optional[str]:
<ide> """
<ide> This is a class attribute in BaseExecutor but since this is not really an executor, but a wrapper
<ide> of executors we implement as property so we can have custom setter.
<ide> """
<ide> return self._job_id
<ide>
<ide> @job_id.setter
<del> def job_id(self, value):
<add> def job_id(self, value: Optional[str]) -> None:
<ide> """job_id is manipulated by SchedulerJob. We must propagate the job_id to wrapped executors."""
<ide> self._job_id = value
<ide> self.kubernetes_executor.job_id = value
<ide> def start(self) -> None:
<ide> self.kubernetes_executor.start()
<ide>
<ide> @property
<del> def slots_available(self):
<add> def slots_available(self) -> int:
<ide> """Number of new tasks this executor instance can accept"""
<ide> return self.celery_executor.slots_available
<ide>
<ide> def queue_command(
<ide> command: CommandType,
<ide> priority: int = 1,
<ide> queue: Optional[str] = None,
<del> ):
<add> ) -> None:
<ide> """Queues command via celery or kubernetes executor"""
<ide> executor = self._router(task_instance)
<ide> self.log.debug("Using executor: %s for %s", executor.__class__.__name__, task_instance.key)
<ide> def heartbeat(self) -> None:
<ide> self.celery_executor.heartbeat()
<ide> self.kubernetes_executor.heartbeat()
<ide>
<del> def get_event_buffer(self, dag_ids=None) -> Dict[TaskInstanceKey, EventBufferValueType]:
<add> def get_event_buffer(
<add> self, dag_ids: Optional[List[str]] = None
<add> ) -> Dict[TaskInstanceKey, EventBufferValueType]:
<ide> """
<ide> Returns and flush the event buffer from celery and kubernetes executor
<ide>
<del> :param dag_ids: to dag_ids to return events for, if None returns all
<add> :param dag_ids: dag_ids to return events for, if None returns all
<ide> :return: a dict of events
<ide> """
<ide> cleared_events_from_celery = self.celery_executor.get_event_buffer(dag_ids)
<ide> def _router(self, simple_task_instance: SimpleTaskInstance) -> Union[CeleryExecu
<ide> return self.kubernetes_executor
<ide> return self.celery_executor
<ide>
<del> def debug_dump(self):
<add> def debug_dump(self) -> None:
<ide> """Called in response to SIGUSR2 by the scheduler"""
<ide> self.log.info("Dumping CeleryExecutor state")
<ide> self.celery_executor.debug_dump() | 1 |
Ruby | Ruby | provide correct information [ci skip] | ed62584391973c1fa3e7d53d71c1b9f16a8f0289 | <ide><path>actionview/lib/action_view/helpers/date_helper.rb
<ide> def time_ago_in_words(from_time, include_seconds_or_options = {})
<ide> # * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
<ide> # Note: You can also use Rails' i18n functionality for this.
<ide> # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
<del> # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
<del> # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
<add> # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt>.
<add> # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt>.
<ide> # * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
<ide> # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
<ide> # first of the given month in order to not create invalid dates like 31 February. | 1 |
Ruby | Ruby | improve performance for `scope_for_create` | b66235d432d0505857ff667e0a1ddecfb5640a56 | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def where_values_hash(relation_table_name = klass.table_name)
<ide> end
<ide>
<ide> def scope_for_create
<del> where_values_hash.merge!(create_with_value.stringify_keys)
<add> hash = where_values_hash
<add> create_with_value.each { |k, v| hash[k.to_s] = v } unless create_with_value.empty?
<add> hash
<ide> end
<ide>
<ide> # Returns true if relation needs eager loading.
<ide><path>activerecord/lib/active_record/relation/where_clause.rb
<ide> def or(other)
<ide> end
<ide>
<ide> def to_h(table_name = nil)
<del> equalities = equalities(predicates)
<del> if table_name
<del> equalities = equalities.select do |node|
<del> node.left.relation.name == table_name
<del> end
<del> end
<del>
<del> equalities.map { |node|
<add> equalities(predicates).each_with_object({}) do |node, hash|
<add> next if table_name&.!= node.left.relation.name
<ide> name = node.left.name.to_s
<ide> value = extract_node_value(node.right)
<del> [name, value]
<del> }.to_h
<add> hash[name] = value
<add> end
<ide> end
<ide>
<ide> def ast | 2 |
Ruby | Ruby | reduce automatic_inverse_of caching logic | f379185a893503e26d160a4f326e610f05e3d6cc | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def scope_chain
<ide> alias :source_macro :macro
<ide>
<ide> def has_inverse?
<del> @options[:inverse_of] || find_inverse_of_automatically
<add> inverse_name
<ide> end
<ide>
<ide> def inverse_of
<del> @inverse_of ||= if options[:inverse_of]
<del> klass.reflect_on_association(options[:inverse_of])
<del> else
<del> find_inverse_of_automatically
<del> end
<add> return unless inverse_name
<add>
<add> @inverse_of ||= klass.reflect_on_association inverse_name
<ide> end
<ide>
<ide> # Clears the cached value of +@inverse_of+ on this object. This will
<ide> def polymorphic?
<ide> INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key]
<ide>
<ide> private
<del> # Attempts to find the inverse association automatically.
<del> # If it cannot find a suitable inverse association, it returns
<add> # Attempts to find the inverse association name automatically.
<add> # If it cannot find a suitable inverse association name, it returns
<ide> # nil.
<del> def find_inverse_of_automatically
<del> if @automatic_inverse_of == false
<del> nil
<del> elsif @automatic_inverse_of.nil?
<del> set_automatic_inverse_of
<del> else
<del> klass.reflect_on_association(@automatic_inverse_of)
<add> def inverse_name
<add> options.fetch(:inverse_of) do
<add> if @automatic_inverse_of == false
<add> nil
<add> else
<add> @automatic_inverse_of = automatic_inverse_of
<add> end
<ide> end
<ide> end
<ide>
<del> # Sets the +@automatic_inverse_of+ instance variable, and returns
<del> # either nil or the inverse association that it finds.
<del> #
<del> # This method caches the inverse association that is found so that
<del> # future calls to +find_inverse_of_automatically+ have much less
<del> # overhead.
<del> def set_automatic_inverse_of
<add> # returns either nil or the inverse association name that it finds.
<add> def automatic_inverse_of
<ide> if can_find_inverse_of_automatically?(self)
<ide> inverse_name = active_record.name.downcase.to_sym
<ide>
<ide> def set_automatic_inverse_of
<ide> end
<ide>
<ide> if valid_inverse_reflection?(reflection)
<del> @automatic_inverse_of = inverse_name
<del> reflection
<del> else
<del> @automatic_inverse_of = false
<del> nil
<add> inverse_name
<ide> end
<del> else
<del> @automatic_inverse_of = false
<del> nil
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | fix some linty things | d5a4d29532bbb7eea91b1ac806ecdfd68a795727 | <ide><path>src/addons/link/ReactLink.js
<ide> function ReactLink(value, requestChange) {
<ide> */
<ide> function createLinkTypeChecker(linkType) {
<ide> var shapes = {
<del> value: typeof linkType === 'undefined'
<del> ? React.PropTypes.any.isRequired
<del> : linkType.isRequired,
<add> value: typeof linkType === 'undefined' ?
<add> React.PropTypes.any.isRequired :
<add> linkType.isRequired,
<ide> requestChange: React.PropTypes.func.isRequired
<ide> };
<ide> return React.PropTypes.shape(shapes);
<ide><path>src/event/EventPluginHub.js
<ide>
<ide> var EventPluginRegistry = require('EventPluginRegistry');
<ide> var EventPluginUtils = require('EventPluginUtils');
<del>var ExecutionEnvironment = require('ExecutionEnvironment');
<ide>
<ide> var accumulate = require('accumulate');
<ide> var forEachAccumulated = require('forEachAccumulated');
<ide><path>src/test/reactComponentExpect.js
<ide> * @nolint
<ide> */
<ide>
<add>"use strict";
<add>
<ide> var ReactTestUtils = require('ReactTestUtils');
<ide>
<ide> var mergeInto = require('mergeInto');
<ide> mergeInto(reactComponentExpect.prototype, {
<ide> // change soon.
<ide> this.toBeDOMComponent();
<ide> var renderedChildren = this.instance()._renderedChildren || {};
<del> for (name in renderedChildren) {
<add> for (var name in renderedChildren) {
<ide> if (!renderedChildren.hasOwnProperty(name)) {
<ide> continue;
<ide> } | 3 |
PHP | PHP | remove redundant check in fileengine | 1a179e61fd9dded143260c2e6538f764ce0a6d21 | <ide><path>src/Cache/Engine/FileEngine.php
<ide> public function read($key)
<ide> $time = time();
<ide> $cachetime = (int)$this->_File->current();
<ide>
<del> if ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime) {
<add> if ($cachetime < $time) {
<ide> if ($this->_config['lock']) {
<ide> $this->_File->flock(LOCK_UN);
<ide> } | 1 |
PHP | PHP | add app()->isproduction() helper | e225b66a7916a9e964e5c09e7f749ca3be28c992 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function isLocal()
<ide> return $this['env'] === 'local';
<ide> }
<ide>
<add> /**
<add> * Determine if application is in production environment.
<add> *
<add> * @return bool
<add> */
<add> public function isProduction()
<add> {
<add> return $this['env'] === 'production';
<add> }
<add>
<ide> /**
<ide> * Detect the application's current environment.
<ide> * | 1 |
Javascript | Javascript | fix arg names in benchmark string_decoder | f48ca9c9c151fa375640862675abf964099fbb1d | <ide><path>test/parallel/test-benchmark-string_decoder.js
<ide> require('../common');
<ide>
<ide> const runBenchmark = require('../common/benchmark');
<ide>
<del>runBenchmark('string_decoder', ['chunk=16',
<add>runBenchmark('string_decoder', ['chunkLen=16',
<ide> 'encoding=utf8',
<del> 'inlen=32',
<add> 'inLen=32',
<ide> 'n=1']); | 1 |
Mixed | Javascript | add finddomnode transform | 20004e94d399541da70d08fd12b64dafb498ebce | <ide><path>npm-react-codemod/README.md
<ide> APIs.
<ide> * Use the `-d` option for a dry-run and use `-p` to print the output
<ide> for comparison
<ide>
<add>### Included Scripts
<add>
<add>`findDOMNode.js` updates `this.getDOMNode()` or `this.refs.foo.getDOMNode()`
<add>calls inside of `React.createClass` components to `React.findDOMNode(foo)`. Note
<add>that it will only look at code inside of `React.createClass` calls and only
<add>update calls on the component instance or its refs. You can use this script to
<add>update most calls to `getDOMNode` and then manually go through the remaining
<add>calls.
<add>
<add> * `react-codemod findDOMNode <file>`
<add>
<ide> ### Recast Options
<ide>
<ide> Options to [recast](https://github.com/benjamn/recast)'s printer can be provided
<ide><path>npm-react-codemod/test/__tests__/transform-tests.js
<ide> function test(transformName, testFileName, options) {
<ide>
<ide> describe('Transform Tests', () => {
<ide>
<add> it('transforms the "findDOMNode" tests correctly', () => {
<add> test('findDOMNode', 'findDOMNode-test');
<add> });
<ide>
<ide>
<ide> });
<ide><path>npm-react-codemod/test/findDOMNode-test.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>var Composer = React.createClass({
<add> componentWillReceiveProps: function(nextProps) {
<add> this.getDOMNode();
<add> return foo(this.refs.input.getDOMNode());
<add> },
<add>
<add> foo: function() {
<add> var ref = 'foo';
<add> var element = this.refs[ref];
<add> var domNode = element.getDOMNode();
<add> },
<add>
<add> bar: function() {
<add> var thing = this.refs.foo;
<add> thing.getDOMNode();
<add> },
<add>
<add> foobar: function() {
<add> passThisOn(this.refs.main.refs.list.getDOMNode());
<add> }
<add>});
<add>
<add>var SomeDialog = React.createClass({
<add> render: function() {
<add> call(this.refs.SomeThing);
<add> return (
<add> <div />
<add> );
<add> }
<add>});
<ide><path>npm-react-codemod/test/findDOMNode-test.output.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>var Composer = React.createClass({
<add> componentWillReceiveProps: function(nextProps) {
<add> React.findDOMNode(this);
<add> return foo(React.findDOMNode(this.refs.input));
<add> },
<add>
<add> foo: function() {
<add> var ref = 'foo';
<add> var element = this.refs[ref];
<add> var domNode = React.findDOMNode(element);
<add> },
<add>
<add> bar: function() {
<add> var thing = this.refs.foo;
<add> React.findDOMNode(thing);
<add> },
<add>
<add> foobar: function() {
<add> passThisOn(React.findDOMNode(this.refs.main.refs.list));
<add> }
<add>});
<add>
<add>var SomeDialog = React.createClass({
<add> render: function() {
<add> call(this.refs.SomeThing);
<add> return (
<add> <div />
<add> );
<add> }
<add>});
<ide><path>npm-react-codemod/transforms/findDOMNode.js
<add>/*eslint-disable no-comma-dangle*/
<add>
<add>'use strict';
<add>
<add>function getDOMNodeToFindDOMNode(file, api, options) {
<add> const j = api.jscodeshift;
<add>
<add> require('./utils/array-polyfills');
<add> const ReactUtils = require('./utils/ReactUtils')(j);
<add>
<add> const printOptions = options.printOptions || {quote: 'single'};
<add> const root = j(file.source);
<add>
<add> const createReactFindDOMNodeCall = arg => j.callExpression(
<add> j.memberExpression(
<add> j.identifier('React'),
<add> j.identifier('findDOMNode'),
<add> false
<add> ),
<add> [arg]
<add> );
<add>
<add> const updateRefCall = (path, refName) => {
<add> j(path)
<add> .find(j.CallExpression, {
<add> callee: {
<add> object: {
<add> type: 'Identifier',
<add> name: refName,
<add> },
<add> property: {
<add> type: 'Identifier',
<add> name: 'getDOMNode',
<add> },
<add> },
<add> })
<add> .forEach(callPath => j(callPath).replaceWith(
<add> createReactFindDOMNodeCall(j.identifier(refName))
<add> ));
<add> };
<add>
<add> const updateToFindDOMNode = classPath => {
<add> var sum = 0;
<add>
<add> // this.getDOMNode()
<add> sum += j(classPath)
<add> .find(j.CallExpression, {
<add> callee: {
<add> object: {
<add> type: 'ThisExpression',
<add> },
<add> property: {
<add> type: 'Identifier',
<add> name: 'getDOMNode',
<add> },
<add> },
<add> })
<add> .forEach(path => j(path).replaceWith(
<add> createReactFindDOMNodeCall(j.thisExpression())
<add> ))
<add> .size();
<add>
<add> // this.refs.xxx.getDOMNode() or this.refs.xxx.refs.yyy.getDOMNode()
<add> sum += j(classPath)
<add> .find(j.MemberExpression, {
<add> object: {
<add> type: 'MemberExpression',
<add> object: {
<add> type: 'MemberExpression',
<add> object: {
<add> type: 'ThisExpression',
<add> },
<add> property: {
<add> type: 'Identifier',
<add> name: 'refs',
<add> },
<add> },
<add> },
<add> })
<add> .closest(j.CallExpression)
<add> .filter(path => (
<add> path.value.callee.property &&
<add> path.value.callee.property.type === 'Identifier' &&
<add> path.value.callee.property.name === 'getDOMNode'
<add> ))
<add> .forEach(path => j(path).replaceWith(
<add> createReactFindDOMNodeCall(path.value.callee.object)
<add> ))
<add> .size();
<add>
<add> // someVariable.getDOMNode() wherre `someVariable = this.refs.xxx`
<add> sum += j(classPath)
<add> .findVariableDeclarators()
<add> .filter(path => {
<add> const init = path.value.init;
<add> const value = init && init.object;
<add> return (
<add> value &&
<add> value.type === 'MemberExpression' &&
<add> value.object &&
<add> value.object.type === 'ThisExpression' &&
<add> value.property &&
<add> value.property.type === 'Identifier' &&
<add> value.property.name === 'refs' &&
<add> init.property &&
<add> init.property.type === 'Identifier'
<add> );
<add> })
<add> .forEach(path => j(path)
<add> .closest(j.FunctionExpression)
<add> .forEach(fnPath => updateRefCall(fnPath, path.value.id.name))
<add> )
<add> .size();
<add>
<add> return sum > 0;
<add> };
<add>
<add> if (
<add> options['no-explicit-require'] ||
<add> ReactUtils.hasReact(root)
<add> ) {
<add> const didTransform = ReactUtils
<add> .findReactCreateClass(root)
<add> .filter(updateToFindDOMNode)
<add> .size() > 0;
<add>
<add> if (didTransform) {
<add> return root.toSource(printOptions) + '\n';
<add> }
<add> }
<add>
<add> return null;
<add>}
<add>
<add>module.exports = getDOMNodeToFindDOMNode; | 5 |
Javascript | Javascript | fix decrypting of arrays | 63c9685ea73f664183685179a33cb3fe5ba6783e | <ide><path>src/parser.js
<ide> var Parser = (function ParserClosure() {
<ide> this.shift();
<ide> var array = [];
<ide> while (!isCmd(this.buf1, ']') && !isEOF(this.buf1))
<del> array.push(this.getObj());
<add> array.push(this.getObj(cipherTransform));
<ide> if (isEOF(this.buf1))
<ide> error('End of file inside array');
<ide> this.shift(); | 1 |
Javascript | Javascript | move globals in web/pdf_find_bar.js | 9192fb966d395416171e33d345659be0733bd11d | <ide><path>web/pdf_find_bar.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<add>/* globals PDFFindController, FindStates, mozL10n */
<ide>
<ide> 'use strict';
<ide>
<del>/* globals PDFFindController, FindStates, mozL10n */
<del>
<ide> /**
<ide> * Creates a "search bar" given set of DOM elements
<ide> * that act as controls for searching, or for setting | 1 |
PHP | PHP | fix mailcontains escaping patterns multiple times | 87c38a031aee1fe7d726fde923918f0ded3fbbad | <ide><path>src/TestSuite/Constraint/Email/MailContains.php
<ide> class MailContains extends MailConstraintBase
<ide> */
<ide> public function matches($other): bool
<ide> {
<add> $other = preg_quote($other, '/');
<ide> $messages = $this->getMessages();
<ide> foreach ($messages as $message) {
<ide> $method = $this->getTypeMethod();
<ide> $message = $message->$method();
<ide>
<del> $other = preg_quote($other, '/');
<ide> if (preg_match("/$other/", $message) > 0) {
<ide> return true;
<ide> } | 1 |
PHP | PHP | add comment to redirect class | 54750487496b121a09b8c2cff4ac5422c3967d51 | <ide><path>system/redirect.php
<ide> public function with($key, $value)
<ide> */
<ide> public static function __callStatic($method, $parameters)
<ide> {
<add> // Get the parameters for the method. Dynamic routes can be generated using an
<add> // array of parameters for routes that contain wildcards, such as /user/(:num).
<add> //
<add> // Example: Redirect::to_profile(array(1));
<add> //
<add> // Here we'll check to see if a parameter was passed. If it wasn't, we'll just
<add> // pass an empty array into the URL generator.
<ide> $parameters = (isset($parameters[0])) ? $parameters[0] : array();
<ide>
<ide> // Dynamically redirect to a secure route URL. | 1 |
PHP | PHP | fix code style 5 | 69015fc853c47ce54d9ad36d8c8874c85ccf0bbb | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function qualifyColumns($columns)
<ide> foreach ($columns as $column) {
<ide> $qualifiedArray[] = $this->qualifyColumn($column);
<ide> }
<add>
<ide> return $qualifiedArray;
<ide> }
<ide> | 1 |
Text | Text | add bmuenzenmeyer to triagers | ac62f8bd3f02c0b4d0e7ebae48b0318a5493bf8c | <ide><path>README.md
<ide> maintaining the Node.js project.
<ide>
<ide> * [Ayase-252](https://github.com/Ayase-252) -
<ide> **Qingyu Deng** <<i@ayase-lab.com>>
<add>* [bmuenzenmeyer](https://github.com/bmuenzenmeyer) -
<add> **Brian Muenzenmeyer** <<brian.muenzenmeyer@gmail.com>> (he/him)
<ide> * [daeyeon](https://github.com/daeyeon) -
<ide> **Daeyeon Jeong** <<daeyeon.dev@gmail.com>> (he/him)
<ide> * [F3n67u](https://github.com/F3n67u) - | 1 |
Ruby | Ruby | add begin/ensure block since we are returning | 591fcbafcd2eea58ac2ede2bb4daed8c713d07da | <ide><path>actionpack/lib/action_dispatch/middleware/body_proxy.rb
<ide> def respond_to?(*args)
<ide> def close
<ide> return if @closed
<ide> @closed = true
<del> @body.close if @body.respond_to? :close
<del> ensure
<del> @block.call
<add> begin
<add> @body.close if @body.respond_to? :close
<add> ensure
<add> @block.call
<add> end
<ide> end
<ide>
<ide> def closed? | 1 |
Ruby | Ruby | move bottle output to erb | fd34bd6b9029d905edc0bf044ab891ccb804e8e8 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> require 'tab'
<ide> require 'keg'
<ide> require 'cmd/versions'
<add>require 'erb'
<ide>
<ide> class BottleMerger < Formula
<ide> # This provides a URL and Version which are the only needed properties of
<ide> class BottleMerger < Formula
<ide> def self.reset_bottle; @bottle = Bottle.new; end
<ide> end
<ide>
<add>BOTTLE_ERB = <<-EOS
<add> bottle do
<add> <% if prefix.to_s != '/usr/local' %>
<add> prefix '<%= prefix %>'
<add> <% end %>
<add> <% if cellar.is_a? Symbol %>
<add> cellar :<%= cellar %>
<add> <% elsif cellar.to_s != '/usr/local' %>
<add> cellar '<%= cellar %>'
<add> <% end %>
<add> <% if revision > 0 %>
<add> revision <%= revision %>
<add> <% end %>
<add> <% checksums.keys.each do |checksum_type| %>
<add> <% checksum, osx = checksums[checksum_type].shift %>
<add> <%= checksum_type %> '<%= checksum %>' => :<%= osx %>
<add> <% end %>
<add> end
<add>EOS
<add>
<ide> module Homebrew extend self
<ide> def keg_contains string, keg
<ide> quiet_system 'fgrep', '--recursive', '--quiet', '--max-count=1', string, keg
<ide> end
<ide>
<ide> def bottle_output bottle
<del> puts "bottle do"
<del> prefix = bottle.prefix.to_s
<del> puts " prefix '#{prefix}'" if prefix != '/usr/local'
<del> cellar = if bottle.cellar.is_a? Symbol
<del> ":#{bottle.cellar}"
<del> elsif bottle.cellar.to_s != '/usr/local/Cellar'
<del> "'bottle.cellar'"
<del> end
<del> puts " cellar #{cellar}" if cellar
<del> puts " revision #{bottle.revision}" if bottle.revision > 0
<del> Checksum::TYPES.each do |checksum_type|
<del> checksum_os_versions = bottle.send checksum_type
<del> next unless checksum_os_versions
<del> os_versions = checksum_os_versions.keys
<del> os_versions.map! {|osx| MacOS::Version.from_symbol osx }
<del> os_versions.sort.reverse.each do |os_version|
<del> osx = os_version.to_sym
<del> checksum = checksum_os_versions[osx]
<del> puts " #{checksum_type} '#{checksum}' => :#{osx}"
<del> end
<del> end
<del> puts "end"
<add> erb = ERB.new BOTTLE_ERB
<add> erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, '')
<ide> end
<ide>
<ide> def bottle_formula f
<ide> def bottle_formula f
<ide> cellar = HOMEBREW_CELLAR.to_s
<ide> tmp_cellar = '/tmp/Cellar'
<ide>
<add> output = nil
<add>
<ide> HOMEBREW_CELLAR.cd do
<ide> ohai "Bottling #{filename}..."
<ide> # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
<ide> def bottle_formula f
<ide> bottle.sha1 sha1 => bottle_tag
<ide>
<ide> puts "./#{filename}"
<del> bottle_output bottle
<add> output = bottle_output bottle
<add> puts output
<ide> end
<ide> end
<ide>
<ide> def merge
<ide> BottleMerger.class_eval bottle_block
<ide> end
<ide> bottle = BottleMerger.new.bottle
<del> bottle_output bottle if bottle
<add> puts bottle_output bottle if bottle
<ide> end
<ide> exit 0
<ide> end | 1 |
Ruby | Ruby | converge three lines into one | aeafc09921116e356494e1effc7cf61435f22104 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def build_joins(manager, joins)
<ide> association_joins = buckets[:association_join] || []
<ide> stashed_association_joins = buckets[:stashed_join] || []
<ide> join_nodes = (buckets[:join_node] || []).uniq
<del> string_joins = (buckets[:string_join] || []).map { |x|
<del> x.strip
<del> }.uniq
<add> string_joins = (buckets[:string_join] || []).map { |x| x.strip }.uniq
<ide>
<ide> join_list = join_nodes + custom_join_ast(manager, string_joins)
<ide> | 1 |
Javascript | Javascript | fix some whitespace issues | 6b08d88d04f4a41849753999e6e18126895086d0 | <ide><path>src/core.js
<ide> jQuery.fn = jQuery.prototype = {
<ide> jQuery.fn.init.prototype = jQuery.fn;
<ide>
<ide> jQuery.extend = jQuery.fn.extend = function() {
<del> var options, name, src, copy, copyIsArray, clone,
<add> var options, name, src, copy, copyIsArray, clone,
<ide> target = arguments[0] || {},
<ide> i = 1,
<ide> length = arguments.length,
<ide><path>src/css.js
<ide> if ( document.defaultView && document.defaultView.getComputedStyle ) {
<ide>
<ide> if ( document.documentElement.currentStyle ) {
<ide> currentStyle = function( elem, name ) {
<del> var left,
<add> var left,
<ide> ret = elem.currentStyle && elem.currentStyle[ name ],
<ide> rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
<ide> style = elem.style;
<ide><path>src/effects.js
<ide> function defaultDisplay( nodeName ) {
<ide> disabled[ idx ] = style.disabled;
<ide> style.disabled = true;
<ide> }
<del>
<del> // To accurately check an element's default display value,
<add>
<add> // To accurately check an element's default display value,
<ide> // create a temp element and check it's default display, this
<ide> // will ensure that the value returned is not a user-tampered
<ide> // value.
<ide> elem = jQuery("<" + nodeName + ">").appendTo("body");
<ide> display = elem.css("display");
<del>
<add>
<ide> // Remove temp element
<ide> elem.remove();
<ide>
<ide> if ( display === "none" || display === "" ) {
<ide> display = "block";
<ide> }
<del>
<add>
<ide> // Store the correct default display
<ide> elemdisplay[ nodeName ] = display;
<ide>
<ide><path>src/event.js
<ide> jQuery.event = {
<ide> handler = returnFalse;
<ide> } else if ( !handler ) {
<ide> // Fixes bug #7229. Fix recommended by jdalton
<del> return;
<add> return;
<ide> }
<ide>
<ide> var handleObjIn, handleObj;
<ide><path>src/offset.js
<ide> jQuery.each( ["Left", "Top"], function( i, name ) {
<ide> if ( win ) {
<ide> win.scrollTo(
<ide> !i ? val : jQuery(win).scrollLeft(),
<del> i ? val : jQuery(win).scrollTop()
<add> i ? val : jQuery(win).scrollTop()
<ide> );
<ide>
<ide> } else {
<ide><path>src/traversing.js
<ide> jQuery.each({
<ide> }, function( name, fn ) {
<ide> jQuery.fn[ name ] = function( until, selector ) {
<ide> var ret = jQuery.map( this, fn, until ),
<del> // The variable 'args' was introduced in
<del> // https://github.com/jquery/jquery/commit/52a0238
<del> // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
<del> // http://code.google.com/p/v8/issues/detail?id=1050
<del> args = slice.call(arguments);
<add> // The variable 'args' was introduced in
<add> // https://github.com/jquery/jquery/commit/52a0238
<add> // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
<add> // http://code.google.com/p/v8/issues/detail?id=1050
<add> args = slice.call(arguments);
<ide>
<ide> if ( !runtil.test( name ) ) {
<ide> selector = until;
<ide><path>test/unit/event.js
<ide> test("unbind(type)", function() {
<ide>
<ide> message = "unbind many with function";
<ide> $elem.bind('error1 error2',error)
<del> .unbind('error1 error2', error )
<del> .trigger('error1').triggerHandler('error2');
<add> .unbind('error1 error2', error )
<add> .trigger('error1').triggerHandler('error2');
<ide>
<ide> message = "unbind many"; // #3538
<ide> $elem.bind('error1 error2',error)
<del> .unbind('error1 error2')
<del> .trigger('error1').triggerHandler('error2');
<add> .unbind('error1 error2')
<add> .trigger('error1').triggerHandler('error2');
<ide>
<ide> message = "unbind without a type or handler";
<ide> $elem.bind("error1 error2.test",error)
<del> .unbind()
<del> .trigger("error1").triggerHandler("error2");
<add> .unbind()
<add> .trigger("error1").triggerHandler("error2");
<ide> });
<ide>
<ide> test("unbind(eventObject)", function() { | 7 |
Javascript | Javascript | add regression test for | d2e7ca0449299d29f66dd682e9c9118c535fd61e | <ide><path>test/simple/test-net-end-without-connect.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var net = require('net');
<add>
<add>var sock = new net.Socket;
<add>sock.end(); // Should not throw. | 1 |
PHP | PHP | pass exception object to view | a021cf29b8cfdceb28b37e36425acf8067297eae | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function renderHttpException(HttpException $e)
<ide>
<ide> if (view()->exists("errors.{$status}"))
<ide> {
<del> return response()->view("errors.{$status}", [], $status);
<add> return response()->view("errors.{$status}", ['e' => $e], $status);
<ide> }
<ide> else
<ide> { | 1 |
Python | Python | fix a bug in cloudfiles driver | d92b13da1042774876c53127dc58b332159aad82 | <ide><path>libcloud/storage/drivers/cloudfiles.py
<ide> except:
<ide> import simplejson as json
<ide>
<del>from libcloud import utils
<add>from libcloud.utils import fixxpath, findtext, in_development_warning
<add>from libcloud.utils import read_in_chunks
<ide> from libcloud.common.types import MalformedResponseError, LibcloudError
<ide> from libcloud.common.base import Response
<ide>
<ide> def download_object_as_stream(self, obj, chunk_size=None):
<ide> object_name),
<ide> method='GET', raw=True)
<ide>
<del> return self._get_object(obj=obj, callback=self._get_object_as_stream,
<add> return self._get_object(obj=obj, callback=read_in_chunks,
<ide> response=response,
<ide> callback_kwargs={ 'iterator': response.response,
<ide> 'chunk_size': chunk_size}, | 1 |
Python | Python | add postmortem metadata for v8 turbofan | 31ce2c1b92855726a5d9ac035e41ef430379e40e | <ide><path>deps/v8/tools/gen-postmortem-metadata.py
<ide> 'JSObject, elements, Object, kElementsOffset',
<ide> 'JSObject, internal_fields, uintptr_t, kHeaderSize',
<ide> 'FixedArray, data, uintptr_t, kHeaderSize',
<add> 'FixedTypedArrayBase, external_pointer, Object, kExternalPointerOffset',
<ide> 'JSArrayBuffer, backing_store, Object, kBackingStoreOffset',
<ide> 'JSArrayBufferView, byte_offset, Object, kByteOffsetOffset',
<ide> 'JSTypedArray, length, Object, kLengthOffset',
<ide> 'SeqTwoByteString, chars, char, kHeaderSize',
<ide> 'SharedFunctionInfo, code, Code, kCodeOffset',
<ide> 'SharedFunctionInfo, scope_info, ScopeInfo, kScopeInfoOffset',
<add> 'SharedFunctionInfo, function_token_position, int, kFunctionTokenPositionOffset',
<add> 'SharedFunctionInfo, start_position_and_type, int, kStartPositionAndTypeOffset',
<add> 'SharedFunctionInfo, end_position, int, kEndPositionOffset',
<add> 'SharedFunctionInfo, internal_formal_parameter_count, int, kFormalParameterCountOffset',
<add> 'SharedFunctionInfo, compiler_hints, int, kCompilerHintsOffset',
<add> 'SharedFunctionInfo, length, int, kLengthOffset',
<ide> 'SlicedString, parent, String, kParentOffset',
<ide> 'Code, instruction_start, uintptr_t, kHeaderSize',
<ide> 'Code, instruction_size, int, kInstructionSizeOffset', | 1 |
PHP | PHP | implement retriesleft correctly | 36618f99b3b022806c587328d6122768afadb10d | <ide><path>src/Illuminate/Cache/RateLimiter.php
<ide> public function attempts($key)
<ide> return $this->cache->get($key, 0);
<ide> }
<ide>
<add> /**
<add> * Get the number of retries left for the given key.
<add> *
<add> * @param string $key
<add> * @param int $maxAttempts
<add> * @return int
<add> */
<add> public function retriesLeft($key, $maxAttempts)
<add> {
<add> $attempts = $this->attempts($key);
<add>
<add> if ($attempts == 0) {
<add> return $maxAttempts;
<add> }
<add>
<add> return $maxAttempts - $attempts + 1;
<add> }
<add>
<ide> /**
<ide> * Clear the hits and lockout for the given key.
<ide> *
<ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php
<ide> protected function incrementLoginAttempts(Request $request)
<ide> */
<ide> protected function retriesLeft(Request $request)
<ide> {
<del> $attempts = app(RateLimiter::class)->attempts(
<del> $this->getThrottleKey($request)
<add> return app(RateLimiter::class)->retriesLeft(
<add> $this->getThrottleKey($request),
<add> $this->maxLoginAttempts()
<ide> );
<del>
<del> return $this->maxLoginAttempts() - $attempts + 1;
<ide> }
<ide>
<ide> /** | 2 |
PHP | PHP | remove extra brackets | 57a6c06ade7bc329316c44c3938888936018a5bb | <ide><path>src/Illuminate/Http/Request.php
<ide> public function is()
<ide> */
<ide> public function routeIs()
<ide> {
<del> if ((! $route = $this->route()) || ! $routeName = $route->getName()) {
<add> if (! $route = $this->route() || ! $routeName = $route->getName()) {
<ide> return false;
<ide> }
<ide> | 1 |
Python | Python | change the process list algorithm | c9f5c9b518d2399a8b19d4edd09e22ad1376ec61 | <ide><path>src/glances.py
<ide> #=====
<ide>
<ide> application = 'glances'
<del>__version__ = "1.4b2"
<add>__version__ = "1.4b3"
<ide> gettext.install(application)
<ide>
<ide> try:
<ide> def __init__(self):
<ide> self.glancesgrabfs = glancesGrabFs()
<ide> except:
<ide> self.glancesgrabfs = {}
<del>
<add>
<ide>
<ide> def __update__(self):
<ide> """
<ide> def __update__(self):
<ide> self.fs = {}
<ide>
<ide> # PROCESS
<del> # Initialiation of the processes list
<del> self.processcount = {'zombie': 0, 'running': 0, 'total': 0, 'stopped': 0, 'sleeping': 0, 'disk sleep': 0}
<del> try:
<del> self.process
<del> except:
<del> self.process = []
<del>
<add> # Initialiation of the running processes list
<add> process_first_grab = False
<ide> try:
<ide> self.process_all
<ide> except:
<ide> self.process_all = [proc for proc in psutil.process_iter()]
<del> for proc in self.process_all[:]:
<add> process_first_grab = True
<add> self.process = []
<add> self.processcount = { 'total': 0 , 'running': 0, 'sleeping': 0 }
<add> # Manage new processes
<add> process_new = [proc.pid for proc in self.process_all]
<add> for proc in psutil.process_iter():
<add> if proc.pid not in process_new:
<add> self.process_all.append(proc)
<add> # Grab stats from process list
<add> for proc in self.process_all[:]:
<add> if (proc.is_running()):
<ide> # Global stats
<ide> try:
<del> self.processcount[str(proc.status)]
<del> except:
<del> pass
<del> else:
<ide> self.processcount[str(proc.status)] += 1
<del> self.processcount['total'] += 1
<del> # Per process stats
<del> try:
<del> # A first value is needed to compute the CPU percent
<del> proc.get_cpu_percent(interval=0)
<del> except:
<del> pass
<del> else:
<del> proc._before = proc
<del> else:
<del> self.process = []
<del> for proc in self.process_all[:]:
<del> # Global stats
<del> try:
<del> self.processcount[str(proc.status)]
<ide> except:
<del> pass
<del> else:
<del> self.processcount[str(proc.status)] += 1
<del> self.processcount['total'] += 1
<add> self.processcount[str(proc.status)] = 1
<add> finally:
<add> self.processcount['total'] += 1
<ide> # Per process stats
<ide> try:
<ide> procstat = {}
<ide> procstat['process_name'] = proc.name
<ide> procstat['proctitle'] = " ".join(str(i) for i in proc.cmdline)
<ide> procstat['proc_size'] = proc.get_memory_info().vms
<ide> procstat['proc_resident'] = proc.get_memory_info().rss
<del> procstat['cpu_percent'] = proc._before.get_cpu_percent(interval=0)
<del> #~ procstat['diskio_read'] = proc.get_io_counters().read_bytes - proc._before.get_io_counters().read_bytes
<del> #~ procstat['diskio_write'] = proc.get_io_counters().write_bytes - proc._before.get_io_counters().write_bytes
<add> procstat['cpu_percent'] = proc.get_cpu_percent(interval=0)
<ide> self.process.append(procstat)
<ide> except:
<del> pass
<del> del(self.process_all)
<add> pass
<add> else:
<add> self.process_all.remove(proc)
<add> # If it is the first grab then empty process list
<add> if (process_first_grab):
<add> self.process = []
<add>
<add> #~ self.processcount = {'zombie': 0, 'running': 0, 'total': 0, 'stopped': 0, 'sleeping': 0, 'disk sleep': 0}
<add> #~ try:
<add> #~ self.process
<add> #~ except:
<add> #~ self.process = []
<add> #~
<add> #~ try:
<add> #~ self.process_all
<add> #~ except:
<add> #~ self.process_all = [proc for proc in psutil.process_iter()]
<add> #~ for proc in self.process_all[:]:
<add> #~ # Global stats
<add> #~ try:
<add> #~ self.processcount[str(proc.status)]
<add> #~ except:
<add> #~ pass
<add> #~ else:
<add> #~ self.processcount[str(proc.status)] += 1
<add> #~ self.processcount['total'] += 1
<add> #~ self.processcount == []
<add> #~ # Per process stats
<add> #~ try:
<add> #~ # A first value is needed to compute the CPU percent
<add> #~ proc.get_cpu_percent(interval=0)
<add> #~ except:
<add> #~ pass
<add> #~ else:
<add> #~ self.process = []
<add> #~ for proc in self.process_all[:]:
<add> #~ # Global stats
<add> #~ try:
<add> #~ self.processcount[str(proc.status)]
<add> #~ except:
<add> #~ pass
<add> #~ else:
<add> #~ self.processcount[str(proc.status)] += 1
<add> #~ self.processcount['total'] += 1
<add> #~ # Per process stats
<add> #~ try:
<add> #~ procstat = {}
<add> #~ procstat['process_name'] = proc.name
<add> #~ procstat['proctitle'] = " ".join(str(i) for i in proc.cmdline)
<add> #~ procstat['proc_size'] = proc.get_memory_info().vms
<add> #~ procstat['proc_resident'] = proc.get_memory_info().rss
<add> #~ procstat['cpu_percent'] = proc.get_cpu_percent(interval=0)
<add> #~ self.process.append(procstat)
<add> #~ except:
<add> #~ pass
<add> #~ del(self.process_all)
<ide>
<ide> # Get the current date/time
<ide> self.now = datetime.datetime.now()
<ide> def getProcessList(self, sortedby = 'auto'):
<ide> # If global Mem > 70% sort by process size
<ide> # Else sort by cpu comsoption
<ide> sortedby = 'cpu_percent'
<del> if ( self.mem['total'] != 0):
<del> if ( ( (self.mem['used'] - self.mem['cache']) * 100 / self.mem['total']) > limits.getSTDWarning()):
<add> try:
<add> memtotal = (self.mem['used'] - self.mem['cache']) * 100 / self.mem['total']
<add> except:
<add> pass
<add> else:
<add> if (memtotal > limits.getSTDWarning()):
<ide> sortedby = 'proc_size'
<ide> elif sortedby == 'process_name':
<ide> sortedReverse = False
<ide> def __init__(self, refresh_time = 1):
<ide> self.cpu_x = 0 ; self.cpu_y = 3
<ide> self.load_x = 20; self.load_y = 3
<ide> self.mem_x = 41; self.mem_y = 3
<del> self.network_x = 0 ; self.network_y = 9
<add> self.network_x = 0 ; self.network_y = 8
<ide> self.diskio_x = 0 ; self.diskio_y = -1
<ide> self.fs_x = 0 ; self.fs_y = -1
<del> self.process_x = 30; self.process_y = 9
<add> self.process_x = 30; self.process_y = 8
<ide> self.log_x = 0 ; self.log_y = -1
<ide> self.help_x = 0; self.help_y = 0
<ide> self.now_x = 79; self.now_y = 3
<ide> def displayCpu(self, cpu):
<ide> # CPU %
<ide> screen_x = self.screen.getmaxyx()[1]
<ide> screen_y = self.screen.getmaxyx()[0]
<del> if ((screen_y > self.cpu_y+6)
<add> if ((screen_y > self.cpu_y+5)
<ide> and (screen_x > self.cpu_x+18)):
<ide> self.term_window.addnstr(self.cpu_y, self.cpu_x, _("Cpu"), 8, self.title_color if self.hascolors else curses.A_UNDERLINE)
<del> self.term_window.addnstr(self.cpu_y, self.cpu_x+10,"%", 8)
<ide>
<ide> if (not cpu):
<ide> self.term_window.addnstr(self.cpu_y+1, self.cpu_x, _("Compute data..."), 15)
<ide> return 0
<del>
<add>
<add> self.term_window.addnstr(self.cpu_y, self.cpu_x+10, "%.1f%%" % (100-cpu['idle']), 8)
<ide> self.term_window.addnstr(self.cpu_y+1, self.cpu_x, _("User:"), 8)
<ide> self.term_window.addnstr(self.cpu_y+2, self.cpu_x, _("Kernel:"), 8)
<ide> self.term_window.addnstr(self.cpu_y+3, self.cpu_x, _("Nice:"), 8)
<del> self.term_window.addnstr(self.cpu_y+4, self.cpu_x, _("Idle:"), 8)
<add> #~ self.term_window.addnstr(self.cpu_y+4, self.cpu_x, _("Idle:"), 8)
<ide>
<ide> alert = self.__getCpuAlert(cpu['user'])
<ide> logs.add(alert, "CPU user", cpu['user'])
<ide> def displayCpu(self, cpu):
<ide> logs.add(alert, "CPU nice", cpu['nice'])
<ide> self.term_window.addnstr(self.cpu_y+3, self.cpu_x+10, "%.1f" % cpu['nice'], 8, self.__colors_list[alert])
<ide>
<del> self.term_window.addnstr(self.cpu_y+4, self.cpu_x+10, "%.1f" % cpu['idle'], 8)
<add> #~ self.term_window.addnstr(self.cpu_y+4, self.cpu_x+10, "%.1f" % cpu['idle'], 8)
<ide>
<ide>
<ide> def displayLoad(self, load, core):
<ide> def displayProcess(self, processcount, processlist, log_count = 0):
<ide> self.term_window.addnstr(self.process_y+1, process_x+10,str(processcount['total']), 8)
<ide> self.term_window.addnstr(self.process_y+1, process_x+20,str(processcount['running']), 8)
<ide> self.term_window.addnstr(self.process_y+1, process_x+30,str(processcount['sleeping']), 8)
<del> self.term_window.addnstr(self.process_y+1, process_x+40,str(processcount['stopped']+stats.getProcessCount()['zombie']), 8)
<add> self.term_window.addnstr(self.process_y+1, process_x+40,str(processcount['total']-stats.getProcessCount()['running']-stats.getProcessCount()['sleeping']), 8)
<ide> # Display the process detail
<del> if ((screen_y > self.process_y+6)
<add> if ((screen_y > self.process_y+7)
<ide> and (screen_x > process_x+49)):
<ide> # Processes detail
<ide> self.term_window.addnstr(self.process_y+3, process_x, _("Cpu %"), 5, curses.A_UNDERLINE if (self.getProcessSortedBy() == 'cpu_percent') else 0)
<ide> def displayProcess(self, processcount, processlist, log_count = 0):
<ide> self.term_window.addnstr(self.process_y+4, self.process_x, _("Compute data..."), 15)
<ide> return 6
<ide>
<del> for processes in range(0, min(screen_y-self.term_h+self.process_y-log_count, len(processlist))):
<add> for processes in range(0, min(screen_y-self.term_h+self.process_y-log_count+2, len(processlist))):
<ide> self.term_window.addnstr(self.process_y+4+processes, process_x, "%.1f" % processlist[processes]['cpu_percent'], 8, self.__getProcessColor(processlist[processes]['cpu_percent']))
<ide> self.term_window.addnstr(self.process_y+4+processes, process_x+7, self.__autoUnit(processlist[processes]['proc_size']), 9)
<ide> self.term_window.addnstr(self.process_y+4+processes, process_x+18, self.__autoUnit(processlist[processes]['proc_resident']), 9)
<ide> def init():
<ide> screen = glancesScreen(refresh_time)
<ide>
<ide>
<del>def main():
<del>
<add>def main():
<ide> # Init stuff
<ide> init()
<ide> | 1 |
Ruby | Ruby | escape $ inreplace 'after' parameter | 3f11c4ab1ff72057d3bb4cc86058512f78f4e818 | <ide><path>Library/Homebrew/brewkit.rb
<ide> def inreplace(path, before, after)
<ide> after=after.to_s
<ide> after.gsub! "\\", "\\\\"
<ide> after.gsub! "/", "\\/"
<add> after.gsub! "$", "\\$"
<ide>
<ide> # FIXME use proper Ruby for teh exceptions!
<ide> safe_system "perl", "-pi", "-e", "s/#{before}/#{after}/g", path | 1 |
PHP | PHP | apply fixes from styleci | 6c0ec9dfeedcb6324c7655f788a794bcf4ae10ba | <ide><path>src/Illuminate/Database/Eloquent/Factories/BelongsToRelationship.php
<ide> public function attributesFor(Model $model)
<ide>
<ide> return $relationship instanceof MorphTo ? [
<ide> $relationship->getMorphType() => (new $this->factory->model)->getMorphClass(),
<del> $relationship->getForeignKeyName() => $this->resolver()
<add> $relationship->getForeignKeyName() => $this->resolver(),
<ide> ] : [
<del> $relationship->getForeignKeyName() => $this->resolver()
<add> $relationship->getForeignKeyName() => $this->resolver(),
<ide> ];
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php
<ide> protected function expandAttributes(array $definition)
<ide> $attribute = $attribute($definition);
<ide> }
<ide>
<del> if ($attribute instanceof Factory) {
<add> if ($attribute instanceof self) {
<ide> return $attribute->create()->getKey();
<ide> } elseif ($attribute instanceof Model) {
<ide> return $attribute->getKey();
<ide> public function state($state)
<ide> 'states' => $this->states->concat([
<ide> is_callable($state) ? $state : function () use ($state) {
<ide> return $state;
<del> }
<del> ])
<add> },
<add> ]),
<ide> ]);
<ide> }
<ide>
<ide> public function sequence(...$sequence)
<ide> return $this->state(new Sequence(...$sequence));
<ide> }
<ide>
<del> public function has(Factory $factory, $relationship = null)
<add> public function has(self $factory, $relationship = null)
<ide> {
<ide> return $this->newInstance([
<ide> 'has' => $this->has->concat([new Relationship(
<ide> $factory, $relationship ?: Str::camel(Str::plural(class_basename($factory->modelName())))
<del> )])
<add> )]),
<ide> ]);
<ide> }
<ide>
<del> public function hasAttached(Factory $factory, $pivot = [], $relationship = null)
<add> public function hasAttached(self $factory, $pivot = [], $relationship = null)
<ide> {
<ide> return $this->newInstance([
<ide> 'has' => $this->has->concat([new BelongsToManyRelationship(
<ide> $factory,
<ide> $pivot,
<ide> $relationship ?: Str::camel(Str::plural(class_basename($factory->modelName())))
<del> )])
<add> )]),
<ide> ]);
<ide> }
<ide>
<del> public function for(Factory $factory, $relationship = null)
<add> public function for(self $factory, $relationship = null)
<ide> {
<ide> return $this->newInstance(['for' => $this->for->concat([new BelongsToRelationship(
<ide> $factory,
<ide> protected function newModel(array $attributes = [])
<ide> */
<ide> public function modelName()
<ide> {
<del> $resolver = static::$modelNameResolver ?: function (Factory $factory) {
<add> $resolver = static::$modelNameResolver ?: function (self $factory) {
<ide> return 'App\\'.Str::replaceLast('Factory', '', class_basename($factory));
<ide> };
<ide> | 2 |
Go | Go | reduce use of const for driver name | aca80d1cda4da98ca8686d58a7c15b41cce96ef6 | <ide><path>libnetwork/drivers/ipvlan/ipvlan.go
<ide> const (
<ide> containerVethPrefix = "eth"
<ide> vethPrefix = "veth"
<ide>
<del> ipvlanType = "ipvlan" // driver type name
<add> driverName = "ipvlan" // driver type name
<ide> parentOpt = "parent" // parent interface -o parent
<ide> driverModeOpt = "ipvlan_mode" // mode -o ipvlan_mode
<ide> driverFlagOpt = "ipvlan_flag" // flag -o ipvlan_flag
<ide> func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
<ide> return err
<ide> }
<ide>
<del> return dc.RegisterDriver(ipvlanType, d, c)
<add> return dc.RegisterDriver(driverName, d, c)
<ide> }
<ide>
<ide> func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
<ide> func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, erro
<ide> }
<ide>
<ide> func (d *driver) Type() string {
<del> return ipvlanType
<add> return driverName
<ide> }
<ide>
<ide> func (d *driver) IsBuiltIn() bool {
<ide><path>libnetwork/drivers/ipvlan/ipvlan_endpoint.go
<ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
<ide> return fmt.Errorf("network id %q not found", nid)
<ide> }
<ide> if ifInfo.MacAddress() != nil {
<del> return fmt.Errorf("%s interfaces do not support custom mac address assignment", ipvlanType)
<add> return fmt.Errorf("ipvlan interfaces do not support custom mac address assignment")
<ide> }
<ide> ep := &endpoint{
<ide> id: eid,
<ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
<ide> if opt, ok := epOptions[netlabel.PortMap]; ok {
<ide> if _, ok := opt.([]types.PortBinding); ok {
<ide> if len(opt.([]types.PortBinding)) > 0 {
<del> logrus.Warnf("%s driver does not support port mappings", ipvlanType)
<add> logrus.Warnf("ipvlan driver does not support port mappings")
<ide> }
<ide> }
<ide> }
<ide> // disallow port exposure --expose
<ide> if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
<ide> if _, ok := opt.([]types.TransportPort); ok {
<ide> if len(opt.([]types.TransportPort)) > 0 {
<del> logrus.Warnf("%s driver does not support port exposures", ipvlanType)
<add> logrus.Warnf("ipvlan driver does not support port exposures")
<ide> }
<ide> }
<ide> }
<ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go
<ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo
<ide> defer osl.InitOSContext()()
<ide> kv, err := kernel.GetKernelVersion()
<ide> if err != nil {
<del> return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err)
<add> return fmt.Errorf("failed to check kernel version for ipvlan driver support: %v", err)
<ide> }
<ide> // ensure Kernel version is >= v4.2 for ipvlan support
<ide> if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) {
<ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo
<ide> if foundExisting {
<ide> return types.InternalMaskableErrorf("restoring existing network %s", config.ID)
<ide> }
<add>
<ide> // update persistent db, rollback on fail
<ide> err = d.storeUpdate(config)
<ide> if err != nil {
<ide> func (d *driver) createNetwork(config *configuration) (bool, error) {
<ide> }
<ide> config.CreatedSlaveLink = true
<ide>
<del> // notify the user in logs they have limited communications
<add> // notify the user in logs that they have limited communications
<ide> logrus.Debugf("Empty -o parent= flags limit communications to other containers inside of network: %s",
<ide> config.Parent)
<ide> } else {
<ide> func (d *driver) createNetwork(config *configuration) (bool, error) {
<ide> return foundExisting, nil
<ide> }
<ide>
<del>// DeleteNetwork the network for the specified driver type
<add>// DeleteNetwork deletes the network for the specified driver type
<ide> func (d *driver) DeleteNetwork(nid string) error {
<ide> defer osl.InitOSContext()()
<ide> n := d.network(nid)
<ide> func (d *driver) DeleteNetwork(nid string) error {
<ide> return nil
<ide> }
<ide>
<del>// parseNetworkOptions parse docker network options
<add>// parseNetworkOptions parses docker network options
<ide> func parseNetworkOptions(id string, option options.Generic) (*configuration, error) {
<ide> var (
<ide> err error
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup.go
<ide> func createIPVlan(containerIfName, parent, ipvlanMode, ipvlanFlag string) (strin
<ide> // Get the link for the master index (Example: the docker host eth iface)
<ide> parentLink, err := ns.NlHandle().LinkByName(parent)
<ide> if err != nil {
<del> return "", fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, parent, err)
<add> return "", fmt.Errorf("error occurred looking up the ipvlan parent iface %s error: %s", parent, err)
<ide> }
<ide> // Create an ipvlan link
<ide> ipvlan := &netlink.IPVlan{
<ide> func createIPVlan(containerIfName, parent, ipvlanMode, ipvlanFlag string) (strin
<ide> }
<ide> if err := ns.NlHandle().LinkAdd(ipvlan); err != nil {
<ide> // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time.
<del> return "", fmt.Errorf("failed to create the %s port: %v", ipvlanType, err)
<add> return "", fmt.Errorf("failed to create the ipvlan port: %v", err)
<ide> }
<ide>
<ide> return ipvlan.Attrs().Name, nil
<ide> func createDummyLink(dummyName, truncNetID string) error {
<ide> }
<ide> parentDummyLink, err := ns.NlHandle().LinkByName(dummyName)
<ide> if err != nil {
<del> return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", ipvlanType, dummyName, err)
<add> return fmt.Errorf("error occurred looking up the ipvlan parent iface %s error: %s", dummyName, err)
<ide> }
<ide> // bring the new netlink iface up
<ide> if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { | 4 |
Mixed | Javascript | add trigger rule tooltip | f94176bc7b28b496c34974b6e2a21781a9afa221 | <ide><path>airflow/www/static/js/gantt.js
<ide> d3.gantt = () => {
<ide> const tip = d3.tip()
<ide> .attr('class', 'tooltip d3-tip')
<ide> .offset([-10, 0])
<del> .html((d) => tiTooltip(d, { includeTryNumber: true }));
<add> .html((d) => tiTooltip(d, null, { includeTryNumber: true }));
<ide>
<ide> let margin = {
<ide> top: 20,
<ide><path>airflow/www/static/js/graph.js
<ide> function updateNodesStates(tis) {
<ide> elem.onmouseover = (evt) => {
<ide> let tt;
<ide> if (taskId in tis) {
<del> tt = tiTooltip(tis[taskId]);
<add> tt = tiTooltip(tis[taskId], tasks[taskId]);
<ide> } else if (node.children) {
<ide> tt = groupTooltip(node, tis);
<ide> } else if (taskId in tasks) {
<ide><path>airflow/www/static/js/task_instances.js
<ide> function generateTooltipDateTimes(startTime, endTime, dagTimezone) {
<ide> return tooltipHTML;
<ide> }
<ide>
<del>export default function tiTooltip(ti, { includeTryNumber = false } = {}) {
<add>export default function tiTooltip(ti, task, { includeTryNumber = false } = {}) {
<ide> let tt = '';
<ide> if (ti.state !== undefined) {
<ide> tt += `<strong>Status:</strong> ${escapeHtml(ti.state)}<br><br>`;
<ide> export default function tiTooltip(ti, { includeTryNumber = false } = {}) {
<ide> if (ti.operator !== undefined) {
<ide> tt += `Operator: ${escapeHtml(ti.operator)}<br>`;
<ide> }
<del>
<add> if (task && task.trigger_rule) {
<add> tt += `Trigger Rule: ${task.trigger_rule}<br>`;
<add> }
<ide> // Calculate duration on the fly if task instance is still running
<ide> if (ti.state === 'running') {
<ide> const startDate = ti.start_date instanceof moment ? ti.start_date : moment(ti.start_date);
<ide><path>airflow/www/views.py
<ide> class GraphForm(DateTimeWithNumRunsWithDagRunsForm):
<ide> 'task_type': t.task_type,
<ide> 'extra_links': t.extra_links,
<ide> 'is_mapped': t.is_mapped,
<add> 'trigger_rule': t.trigger_rule,
<ide> }
<ide> for t in dag.tasks
<ide> } | 4 |
PHP | PHP | simplify code for json_encode() | f07afda7c673c9beaad382eeaf4b19314759b2df | <ide><path>src/View/JsonView.php
<ide> protected function _serialize($serialize)
<ide> }
<ide>
<ide> if (Configure::read('debug')) {
<del> return json_encode($data, $jsonOptions | JSON_PRETTY_PRINT);
<add> $jsonOptions = $jsonOptions | JSON_PRETTY_PRINT;
<ide> }
<del>
<ide> return json_encode($data, $jsonOptions);
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove unused variables | c03b9e5ec4153078923347d53cbd0d7dfc4e2212 | <ide><path>src/Angular.js
<ide> function encodeUriQuery(val, pctEncodeSpaces) {
<ide> var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
<ide>
<ide> function getNgAttribute(element, ngAttr) {
<del> var attr, i, ii = ngAttrPrefixes.length, j, jj;
<add> var attr, i, ii = ngAttrPrefixes.length;
<ide> element = jqLite(element);
<ide> for (i=0; i<ii; ++i) {
<ide> attr = ngAttrPrefixes[i] + ngAttr; | 1 |
Javascript | Javascript | handle initedraw pkey failure | 17bb7b2936a8098a31947854ce261d094f7ca5df | <ide><path>lib/internal/crypto/ec.js
<ide> function createECRawKey(namedCurve, keyData, isPublic) {
<ide> break;
<ide> }
<ide>
<del> if (isPublic) {
<del> handle.initEDRaw(namedCurve, keyData, kKeyTypePublic);
<del> return new PublicKeyObject(handle);
<add> const keyType = isPublic ? kKeyTypePublic : kKeyTypePrivate;
<add> if (!handle.initEDRaw(namedCurve, keyData, keyType)) {
<add> throw lazyDOMException('Failure to generate key object');
<ide> }
<ide>
<del> handle.initEDRaw(namedCurve, keyData, kKeyTypePrivate);
<del> return new PrivateKeyObject(handle);
<add> return isPublic ? new PublicKeyObject(handle) : new PrivateKeyObject(handle);
<ide> }
<ide>
<ide> async function ecGenerateKey(algorithm, extractable, keyUsages) {
<ide><path>lib/internal/crypto/keys.js
<ide> function getKeyObjectHandleFromJwk(key, ctx) {
<ide> }
<ide>
<ide> const handle = new KeyObjectHandle();
<del> if (isPublic) {
<del> handle.initEDRaw(
<del> `NODE-${key.crv.toUpperCase()}`,
<del> keyData,
<del> kKeyTypePublic);
<del> } else {
<del> handle.initEDRaw(
<del> `NODE-${key.crv.toUpperCase()}`,
<del> keyData,
<del> kKeyTypePrivate);
<add>
<add> const keyType = isPublic ? kKeyTypePublic : kKeyTypePrivate;
<add> if (!handle.initEDRaw(`NODE-${key.crv.toUpperCase()}`, keyData, keyType)) {
<add> throw new ERR_CRYPTO_INVALID_JWK();
<ide> }
<ide>
<ide> return handle; | 2 |
Javascript | Javascript | add two stream implementations | 0dce02229159bec58a651f3185b87d2bcc76659b | <ide><path>src/geo/stream-buffer.js
<add>function d3_geo_streamBuffer() {
<add> this._buffer = [];
<add> this._point = d3_geo_pathCircle(4.5);
<add>}
<add>
<add>var d3_geo_streamBufferPrototype = {
<add> point: d3_geo_streamBufferPoint,
<add>
<add> // While inside a line, override point to moveTo then lineTo.
<add> lineStart: function() { this.point = d3_geo_streamBufferPointLineStart; },
<add> lineEnd: d3_geo_streamBufferLineEnd,
<add>
<add> // While inside a polygon, override lineEnd to closePath.
<add> polygonStart: function() { this.lineEnd = d3_geo_streamBufferLineEndPolygon; },
<add> polygonEnd: function() { this.lineEnd = d3_geo_streamBufferLineEnd; },
<add>
<add> toString: function() {
<add> var s = this._buffer.join("");
<add> this._buffer = [];
<add> return s;
<add> }
<add>}
<add>
<add>function d3_geo_streamBufferPoint(x, y) {
<add> this._buffer.push("M", x, ",", y, this._point);
<add>}
<add>
<add>function d3_geo_streamBufferPointLineStart(x, y) {
<add> this._buffer.push("M", x, ",", y);
<add> this.point = d3_geo_streamBufferPointLine;
<add>}
<add>
<add>function d3_geo_streamBufferPointLine(x, y) {
<add> this._buffer.push("L", x, ",", y);
<add>}
<add>
<add>function d3_geo_streamBufferLineEnd() {
<add> this.point = d3_geo_streamBufferPoint;
<add>}
<add>
<add>function d3_geo_streamBufferLineEndPolygon() {
<add> this._buffer.push("Z");
<add>}
<ide><path>src/geo/stream-context.js
<add>function d3_geo_streamContext() {
<add> this._pointRadius = 4.5;
<add>}
<add>
<add>var d3_geo_streamContextPrototype = {
<add> point: d3_geo_streamContextPoint,
<add>
<add> // While inside a line, override point to moveTo then lineTo.
<add> lineStart: function() { this.point = d3_geo_streamContextPointLineStart; },
<add> lineEnd: d3_geo_streamContextLineEnd,
<add>
<add> // While inside a polygon, override lineEnd to closePath.
<add> polygonStart: function() { this.lineEnd = d3_geo_streamContextLineEndPolygon; },
<add> polygonEnd: function() { this.lineEnd = d3_geo_streamContextLineEnd; }
<add>}
<add>
<add>function d3_geo_streamContextPoint(x, y) {
<add> this._context.moveTo(x, y);
<add> this._context.arc(x, y, this._pointRadius, 0, 2 * π);
<add>}
<add>
<add>function d3_geo_streamContextPointLineStart(x, y) {
<add> this._context.moveTo(x, y);
<add> this.point = d3_geo_streamContextPointLine;
<add>}
<add>
<add>function d3_geo_streamContextPointLine(x, y) {
<add> this._context.lineTo(x, y);
<add>}
<add>
<add>function d3_geo_streamContextLineEnd() {
<add> this.point = d3_geo_streamContextPoint;
<add>}
<add>
<add>function d3_geo_streamContextLineEndPolygon() {
<add> this._context.closePath();
<add>} | 2 |
Javascript | Javascript | simplify one ajax call and add explanatory comment | 0ac28ed293681cb8f2e9fdd11efa0021da039c84 | <ide><path>src/ajax/script.js
<ide> jQuery.ajaxTransport( "script", function( s ) {
<ide> return {
<ide> send: function( _, complete ) {
<ide> script = jQuery("<script>").prop({
<del> async: true,
<ide> charset: s.scriptCharset,
<ide> src: s.url
<ide> }).on(
<ide><path>src/manipulation/_evalUrl.js
<ide> define([
<ide> jQuery._evalUrl = function( url ) {
<ide> return jQuery.ajax({
<ide> url: url,
<add>
<add> // Make this explicit, since user can override this through ajaxSetup (#11264)
<ide> type: "GET",
<ide> dataType: "script",
<ide> cache: true, | 2 |
PHP | PHP | fix memory leak in translatorregistry | c08ea60ea1d04d3106572c4c6555e2202e18eb9e | <ide><path>src/I18n/TranslatorRegistry.php
<ide> public function get(string $name, ?string $locale = null): ?Translator
<ide> $keyName = str_replace('/', '.', $name);
<ide> $key = "translations.{$keyName}.{$locale}";
<ide> $translator = $this->_cacher->get($key);
<add> gc_collect_cycles();
<ide> if (!$translator || !$translator->getPackage()) {
<ide> $translator = $this->_getTranslator($name, $locale);
<ide> $this->_cacher->set($key, $translator); | 1 |
Text | Text | add readme file for the archive directory | 28fc387cf0c933128d0adad6d633c8f4a719d8ee | <ide><path>archive/README.md
<add>This code provides helper functions for dealing with archive files.
<add>
<add>**TODO**: Move this to either `pkg` or (if not possible) to `utils`. | 1 |
Mixed | Text | remove references to xxxbuffergeometry | fbac88d731b85fc9b25c69ce7161edd2566ed40c | <ide><path>threejs/lessons/fr/threejs-primitives.md
<ide> La plupart des primitives ci-dessous ont des valeurs par défaut
<ide> pour certains ou tous leurs paramètres. Vous pouvez donc les
<ide> utiliser en fonction de vos besoins.
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">Une Boîte</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">Un Cercle plat</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">Un Cône</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">Un Cylindre</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">Un Dodécaèdre (12 côtés)</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">Une forme 2D extrudée avec un biseautage optionnel. Ici, nous extrudons une forme de cœur. Notez qu'il s'agit du principe de fonctionnement pour les <code>TextBufferGeometry</code> et les <code>TextGeometry</code>.</div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">Un Icosaèdre (20 côtés)</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, bougies, bougeoirs, verres à vin, verres à boire, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">Un Octaèdre (8 côtés)</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">Une surface générée en fournissant à la fonction un point 2D d'une grille et retourne le point 3D correspondant.</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">Un plan 2D</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">Prend un ensemble de triangles centrés autour d'un point et les projette sur une sphère</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">Un disque 2D avec un trou au centre</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">Un tracé 2D qui se triangule</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">une sphère</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">Un tétraèdre (4 côtés)</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">Texte 3D généré à partir d'une police 3D et d'une chaîne de caractères</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">Un tore (donut)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">Un nœud torique</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">Extrusion contrôlée d'un cercle le long d'un tracé</div>
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">Une Boîte</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">Un Cercle plat</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">Un Cône</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">Un Cylindre</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">Un Dodécaèdre (12 côtés)</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">Une forme 2D extrudée avec un biseautage optionnel. Ici, nous extrudons une forme de cœur. Notez qu'il s'agit du principe de fonctionnement pour les <code>TextGeometry</code> et les <code>TextGeometry</code>.</div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">Un Icosaèdre (20 côtés)</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, bougies, bougeoirs, verres à vin, verres à boire, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">Un Octaèdre (8 côtés)</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">Une surface générée en fournissant à la fonction un point 2D d'une grille et retourne le point 3D correspondant.</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">Un plan 2D</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">Prend un ensemble de triangles centrés autour d'un point et les projette sur une sphère</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">Un disque 2D avec un trou au centre</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">Un tracé 2D qui se triangule</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">une sphère</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">Un tétraèdre (4 côtés)</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">Texte 3D généré à partir d'une police 3D et d'une chaîne de caractères</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">Un tore (donut)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">Un nœud torique</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">Extrusion contrôlée d'un cercle le long d'un tracé</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">Un objet d'aide qui prend une autre
<ide> géométrie en entrée et génère des arêtes que si l'angle entre les faces est supérieur à un certain
<ide> seuil. Par exemple, si vous regardez en haut de la boîte, elle montre une ligne passant par chaque
<ide> n'y aurait que 3 points. Si vous essayez de le dessiner en utilisant un matéria
<ide> triangulaire à un <code>WireframeGeometry</code> vous obtenez une nouvelle géométrie qui comporte
<ide> 3 segments de lignes utilisant 6 points.</div>
<ide>
<del>Vous remarquerez que la plupart d'entre eux proviennent soit du type `Geometry` soit
<del>du type `BufferGeometry`. Le choix entre ces deux types est question de compromis entre flexibilité et performance.
<del>
<del>Le choix des primitives basées sur le type `BufferGeometry` s'oriente sur le critère de la performance. Les
<del>sommets de la géométrie sont générés directement dans un format de tableau typé efficace, prêt à
<del>être envoyé au GPU pour le rendu. Cela signifie qu'ils sont plus rapides à démarrer et prennent
<del>moins de mémoire, mais si vous voulez modifier leurs données, ils nécessitent ce qui est souvent
<del>considéré comme une programmation plus ardue.
<del>
<del>Le choix des primitives basées sur le type `Geometry` s'oriente sur le critère de la flexiblité car elles sont les plus faciles à manipuler.
<del>Elles sont construites à partir de classes JavaScript comme `Vector3` pour les points 3D et `Face3`
<del>pour les triangles.
<del>Elles demandent beaucoup de mémoire et avant de pouvoir être rendues à l'écran, three.js devra les convertir
<del>en une représentation correspondante à `BufferGeometry`.
<del>
<del>Si vous savez que vous n'allez pas manipuler une primitive
<del>ou si vous êtes à l'aise pour appliquer des calculs modifiant
<del>leurs données internes, alors il est préférable d'opter pour les primitives
<del>basées sur `BufferGeometry`. Si, par contre, vous
<del>souhaitez modifier certaines choses avant le rendu, vous trouverez
<del>peut-être les primitives basées sur la `Geometry` plus faciles à manipuler.
<del>
<del>Pour prendre un exemple simple, une `BufferGeometry` ne peut pas facilement
<del>avoir de nouveaux sommets ajoutés. Le nombre de sommets utilisés
<del>est décidé au moment de la création, le stockage est créé, puis les données
<del>relatives aux sommets sont fournies. Alors que pour `Geometry`, vous
<del>pouvez ajouter des sommets au fur et à mesure.
<del>
<ide> Nous reviendrons sur la création de géométrie personnalisée dans
<del>[un autre article](threejs-custom-geometry.html). Pour l'instant,
<add>[un autre article](threejs-custom-buffer-geometry.html). Pour l'instant,
<ide> faisons un exemple en créant chaque type de primitive. Nous
<ide> commencerons par les [exemples vus dans l'article précédent](threejs-responsive.html).
<ide>
<ide> qui constituent une forme. Pour un solide comme une sphère
<ide> ou un cube, il n'y a généralement pas de raison de dessiner les
<ide> côtés arrières des triangles car ils sont tous tournés ver l'intérieur
<ide> de la forme. Dans notre cas, cependant, nous dessinons des objets
<del>comme la `PlaneBufferGeometry` ou la `ShapeBufferGeometry`
<add>comme la `PlaneGeometry` ou la `ShapeGeometry`
<ide> qui sont bidimensionnnels et n'ont donc pas d'intérieur.
<ide> Sans le paramètre `side: THREE.DoubleSide` elle disparaîtraient
<ide> quand on regarderait leur dos.
<ide> Par exemple, la création d'une boîte :
<ide> const width = 8; // largeur
<ide> const height = 8; // hauteur
<ide> const depth = 8; // profondeur
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> Voici le résultat :
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<ide> Il y a quelques exceptions notables au modèle ci-dessus.
<del>La plus grande est probablement le `TextBufferGeometry`. Il doit charger
<add>La plus grande est probablement le `TextGeometry`. Il doit charger
<ide> des données de police en 3D avant de pouvoir générer un maillage pour le texte.
<ide> Ces données se chargent de manière asynchrone, nous devons donc attendre
<ide> qu'elles soient chargées avant d'essayer de créer la géométrie. En "promettant"
<ide> Et enfin, nous créons la géométrie et appelons `addObject` pour l'ajouter à
<ide>
<ide> async function doit() {
<ide> const font = await loadFont('../resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> prend une taille ([`size`](PointsMaterial.size)) pour la grosseur des points.
<ide> const radius = 7; // rayon
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add>const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2, // en unités du monde
<ide> géométries des sphères prennant en paramètres le nombre de divisions à fair
<ide> haut en bas. Par exemple :
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> La première sphère a un tour de 5 segments et 3 de haut, soit 15 segments ou 30 triangles.
<ide> ayez besoin d'un grand nombre de segments, mais si vous enlevez les lignes et le
<ide> nous obtenons ceci :
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> Il est moins perceptible que celle de droite avec 5000 triangles est meilleure que celle avec
<ide> Parfois, il est facile de choisir. Par exemple, vous pouvez aussi choisir
<ide> de subdiviser un plan.
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> Le plan à gauche est composé de 2 triangles. Le plan de droite est composé de 200 triangles.
<ide> Vous devrez décider vous-même du compromis qui convient le mieux à cas d'util
<ide> Si aucune des formes ci-dessus ne correspond à votre cas d'utilisation, vous pouvez
<ide> charger la géométrie par exemple à partir d'un [fichier .obj](threejs-load-obj.html)
<ide> ou d'un [fichier .gltf](threejs-load-gltf.html).
<del>Vous pouvez également créer votre [Geometry](threejs-custom-geometry.html)
<del>ou votre [BufferGeometry](threejs-custom-buffergeometry.html).
<add>Vous pouvez également créer votre [BufferGeometry](threejs-custom-buffergeometry.html).
<ide>
<ide> Voyons maintenant l'article traitant sur [comment fonctionne un graphe de scène three.js et comment l'utiliser](threejs-scenegraph.html).
<ide>
<ide><path>threejs/lessons/ja/threejs-primitives.md
<ide> Three.jsは多くのプリミティブがあります。
<ide> そのため、必要に応じて、上手く使い分けることができます。
<ide>
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">立方体</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">2次元の円</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">円錐</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">円筒</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">十二面体(12面のもの)</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">立方体</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">2次元の円</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">円錐</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">円筒</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">十二面体(12面のもの)</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">
<ide> 押し出しでできた2次元形状、ベベルオプション付き。
<del>これは<code>TextBufferGeometry</code>と<code>TextGeometry</code>のそれぞれの基礎になることに注意してください。</div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">二十面体(20面のもの)</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">線を回転させてできる形状。例としてはこんなところでしょうか:ランプやボーリングのピン、ろうそく、ろうそく立て、ワイングラス、ドリンクグラス、などなど...。点の連続として2次元の輪郭を与え、その輪郭を軸の周りで回転させる際に、どのくらい細分化するかthree.jsに指示することができます。</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">八面体(8面)</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">関数を与えることでできる表面。この関数は、グリッド上2次元の点を引数に取り、対応する3次元の点を返す。</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2次元の四角形</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">三角形を点の周りに集めて球体にする</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">真ん中に穴のあいた円盤</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">三角形分割された2次元の輪郭</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">球体</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">四面体(4面のもの)</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3Dフォントと文字列からできた、3Dテキスト</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">円環(ドーナツ)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">円環(結び目)</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">経路をなぞらせた管</div>
<add>これは<code>TextGeometry</code>と<code>TextGeometry</code>のそれぞれの基礎になることに注意してください。</div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">二十面体(20面のもの)</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">線を回転させてできる形状。例としてはこんなところでしょうか:ランプやボーリングのピン、ろうそく、ろうそく立て、ワイングラス、ドリンクグラス、などなど...。点の連続として2次元の輪郭を与え、その輪郭を軸の周りで回転させる際に、どのくらい細分化するかthree.jsに指示することができます。</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">八面体(8面)</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">関数を与えることでできる表面。この関数は、グリッド上2次元の点を引数に取り、対応する3次元の点を返す。</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">2次元の四角形</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">三角形を点の周りに集めて球体にする</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">真ん中に穴のあいた円盤</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">三角形分割された2次元の輪郭</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">球体</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">四面体(4面のもの)</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">3Dフォントと文字列からできた、3Dテキスト</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">円環(ドーナツ)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">円環(結び目)</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">経路をなぞらせた管</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">異なるジオメトリを入力として、その面同士の角度が閾値以上なら角を作り出す、補助オブジェクト。例えば、記事の最初の方で紹介した立方体を見てみると、それぞれの面に、立方体を作っている全ての三角形の線が表示されています。<code>EdgesGeometry</code>を代わりに使うことで、面内の線は全て除去されます。下記のthresholdAngleを調整してみてください。閾値以下の角が消えて見えるでしょう。</div>
<ide> <div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">1つの角ごとに1つの線分(2点)を持つジオメトリを生成する。WebGLは線分を作るのに2点が必要なので、この機能がないと、しばしば角を忘れたり、余分な角を作ってしまうでしょう。例えば、たった3点しかない1つの三角形あるとします。<code>wireframe: true</code>のマテリアルを使ってそれを描こうとした場合、1本の線分しか得られません。<code>WireframeGeometry</code>にその三角形のジオメトリを渡すと、6点からなる3つの線分を持った新しいジオメトリを生成します。</div>
<ide>
<del>ほとんどのプリミティブは`Geometry`か`BufferGeometry`の2つの種類があることに気づいたかもしれません。
<del>この2つの違いは、高い柔軟性とパフォーマンスです。
<del>
<del>`BufferGeometry`に基づいたプリミティブはパフォーマンス志向の種類です。
<del>ジオメトリの頂点は、GPUにアップロードして描画するのに適した配列形式へ、直接変換されます。
<del>これは、起動が速く省メモリであることを意味しますが、データの修正により複雑なプログラミングが必要になることが多いです。
<del>
<del>`Geometry`に基づいたプリミティブは柔軟で、操作しやすい種類です。
<del>これらは、3次元の点のための`Vector3`、三角形のための`Face3`のようなJavaScriptに基づくクラスからできています。結構メモリを必要としますし、three.jsにレンダリングされる前に、対応する`BufferGeometry`表現に似たものに変換する必要があります。
<del>
<del>プリミティブを操作しないことが分かっているか、計算をして内部を操作することに抵抗がないなら、
<del>`BufferGeometry`に基づいたプリミティブを使うのがベストです。
<del>一方で、描画前に多少の変更をしたいなら、`Geometry`に基づいたプリミティブを使うと、
<del>より簡単に扱うことができます。
<del>
<del>単純な例だと、`BufferGeometry`は新しい頂点群を簡単に追加できません。
<del>使う頂点の数は作成時に宣言され、記憶領域が確保され、データが書き込まれます。
<del>一方、`Geometry`は、みなさんがしたいように頂点群を追加できます。
<del>
<del>[別の記事](threejs-custom-geometry.html)で、カスタムジオメトリの作成について説明します。
<add>[別の記事](threejs-custom-buffergeometry.html)で、カスタムジオメトリの作成について説明します。
<ide> 今はそれぞれの種類のプリミティブを作成する例を作ってみます。
<ide> [以前の記事](threejs-responsive.html)を例に始めましょう。
<ide>
<ide> function createMaterial() {
<ide> これはthreeに形状を作るときに三角形の両面を描くように指示します。
<ide> 球体や立方体のような立体形状には、形状の内側を向いている裏側を描く
<ide> 理由はありません。
<del>しかしこの例だと、2次元で裏側が存在しない`PlaneBufferGeometry`や`ShapeBufferGeometry`のようなものも描こうとしています。
<add>しかしこの例だと、2次元で裏側が存在しない`PlaneGeometry`や`ShapeGeometry`のようなものも描こうとしています。
<ide> `side: THREE.DoubleSide`を設定しないと、裏側を見たときに消えてしまうことでしょう。
<ide>
<ide> `side: THREE.DoubleSide`に**not**が設定された方が、描画が速くなります。
<ide> function addSolidGeometry(x, y, geometry) {
<ide> const width = 8;
<ide> const height = 8;
<ide> const depth = 8;
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> function addSolidGeometry(x, y, geometry) {
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<ide> 上記のパターンには、2つの特筆すべき例外があります。
<del>一番大きなものは、たぶん`TextBufferGeometry`です。テキストのメッシュを作るときは、事前に3Dフォントデータを読み込む必要があります。このデータの読み込みは非同期的に行われるので、ジオメトリを作ろうとする前に、読み込みを待つ必要があります。フォントの読み込みにpromiseを使うと、もっと速く読み込むことができます。
<add>一番大きなものは、たぶん`TextGeometry`です。テキストのメッシュを作るときは、事前に3Dフォントデータを読み込む必要があります。このデータの読み込みは非同期的に行われるので、ジオメトリを作ろうとする前に、読み込みを待つ必要があります。フォントの読み込みにpromiseを使うと、もっと速く読み込むことができます。
<ide> `FontLoader`を作成し、読み込みが完了するとフォントを提供してくれるpromiseを返す`loadFont`関数を作ります。
<ide> 次に、`doit` と呼ばれる`async`関数を作り、`await`を使ってフォントを読み込みます。
<ide> 最後に、ジオメトリを作り、`addObject`を呼んでシーンに追加します。
<ide> function addSolidGeometry(x, y, geometry) {
<ide>
<ide> async function doit() {
<ide> const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> threeが知る手助けをします。
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add>const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2, // in world units
<ide> const material = new THREE.PointsMaterial({
<ide> 例えば、
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 最初の球体は、15セグメントまたは30個の三角形になる、周囲に5セグメント、高さ3です。
<ide> const material = new THREE.PointsMaterial({
<ide> 影をならすことで、このようになります。
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> 5000個の三角形からできる右側の球体が、たった480個の三角形からできる真ん中の球体よりも良いかは、明らかではありません。
<ide> const material = new THREE.PointsMaterial({
<ide> 選ぶのが簡単なときもあります。例えば、平面の細分化を選ぶこともできます。
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 左側の四角形は2個の三角形からできています。右側の四角形は200個の三角形からできています。
<ide> const material = new THREE.PointsMaterial({
<ide>
<ide> みなさんの用途に適した形状がないなら、例えば、[.obj file](threejs-load-obj.html)
<ide> や[.gltf file](threejs-load-gltf.html)からジオメトリを読み込むことができます。
<del>[カスタムジオメトリ](threejs-custom-geometry.html)
<del>や[カスタムBufferGeometry](threejs-custom-buffergeometry.html)を作ることもできます。
<add>[カスタムBufferGeometry](threejs-custom-buffergeometry.html)を作ることもできます。
<ide>
<ide> 次は、[threeのシーングラフの動き方と使い方](threejs-scenegraph.html)を説明します。
<ide>
<ide><path>threejs/lessons/kr/threejs-primitives.md
<ide> Three.js에는 다양한 원시 모델이 있습니다. 먼저 Three.js의 원
<ide> 앞으로 소개할 원시 모델들은 대부분 기본값이 있으므로 필요에 따라
<ide> 인자를 넣어주면 됩니다.
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">육면체(Box)</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">원(flat circle)</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">원뿔(Cone)</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">원통(Cylinder)</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">십이면체(Dodecahedron)</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">사각(bevel)을 주어 깍아낸(extruded) 2D 모양입니다.
<del>아래에서는 하트 모양으로 깍아냈죠. <code>ExtrudedBufferGeometry</code>는 나중에 설명할
<del><code>TextBufferGeometry</code>과 <code>TextGeometry</code>의 기초 모델입니다.</div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">이십면체(Icosahedron)</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">선(line)을 회전시켜 만든 모양입니다. 램프, 볼링핀, 초, 초 받침, 와인잔, 유리잔 등이 있죠(물레로 도자기를 만드는 것처럼. 역주). 2D 형태를 점(point, Vector2 클래스를 말함. 역주)을 사용해 지정하고, Three.js에게 축을 따라 세분값(아래 예제의 <code>segments</code> 값. 역주)과 회전값(아래 예제의 <code>phiLength</code> 값. 역주)을 지정해주면 됩니다.</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">팔면체(Octahedron)</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">2D 격자값(격자 하나의 벡터값)을 받아 3D 값을 반환하는 함수를 인자로 전달하여 면을 만듭니다.</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2D 평면(2D plane)</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">다면체입니다. 주어진 3D 점들(아래 <code>verticesOfCube</code>. 역주)을 중심으로 삼각형(아래 <code>indicesOfFaces</code>. 역주)을 구 형태로 잇습니다.</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">중앙이 빈 2D 디스크(disc)입니다.</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">삼각형으로 이루어진 2D 윤곽선입니다.</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">구(Sphere)</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">사면체(tetrahedron)</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3D 폰트와 문자열로 만든 3D 텍스트입니다.</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">원환체(torus), 도넛(donut)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">원환체 매듭(torus knot)</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">패스를 따라 이어진 원입니다.</div>
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">육면체(Box)</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">원(flat circle)</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">원뿔(Cone)</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">원통(Cylinder)</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">십이면체(Dodecahedron)</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">사각(bevel)을 주어 깍아낸(extruded) 2D 모양입니다.
<add>아래에서는 하트 모양으로 깍아냈죠. <code>ExtrudedGeometry</code>는 나중에 설명할
<add><code>TextGeometry</code>과 <code>TextGeometry</code>의 기초 모델입니다.</div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">이십면체(Icosahedron)</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">선(line)을 회전시켜 만든 모양입니다. 램프, 볼링핀, 초, 초 받침, 와인잔, 유리잔 등이 있죠(물레로 도자기를 만드는 것처럼. 역주). 2D 형태를 점(point, Vector2 클래스를 말함. 역주)을 사용해 지정하고, Three.js에게 축을 따라 세분값(아래 예제의 <code>segments</code> 값. 역주)과 회전값(아래 예제의 <code>phiLength</code> 값. 역주)을 지정해주면 됩니다.</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">팔면체(Octahedron)</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">2D 격자값(격자 하나의 벡터값)을 받아 3D 값을 반환하는 함수를 인자로 전달하여 면을 만듭니다.</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">2D 평면(2D plane)</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">다면체입니다. 주어진 3D 점들(아래 <code>verticesOfCube</code>. 역주)을 중심으로 삼각형(아래 <code>indicesOfFaces</code>. 역주)을 구 형태로 잇습니다.</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">중앙이 빈 2D 디스크(disc)입니다.</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">삼각형으로 이루어진 2D 윤곽선입니다.</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">구(Sphere)</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">사면체(tetrahedron)</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">3D 폰트와 문자열로 만든 3D 텍스트입니다.</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">원환체(torus), 도넛(donut)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">원환체 매듭(torus knot)</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">패스를 따라 이어진 원입니다.</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">다른 <code>geometry</code>를 받는 헬퍼 객체로, 각 면 사이의 각이 일정 값 이상일 때만 모서리를 표시합니다. 상단의 육면체 예제를 보면 육면체를 만드는 삼각형이 표면에 전부 표시된 것을 확인할 수 있는데, <code>EdgesGeometry</code>를 사용할 경우 표면에 있던 선들이 전부 사라집니다. 아래 예제의 <code>thresholdAngle</code> 값을 조정해 해당 값 이하인 모서리가 전부 사라지는 것을 확인해보세요.</div>
<ide> <div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">매개변수로 받은 <code>geometry</code>의 모서리 하나당 하나의 선분(2개의 점)을 가진 <code>geometry</code>를 생성합니다. WebGl은 보통 선분 하나당 2개의 점을 필요로 합니다. 때문에 이 모델을 사용하지 않는 경우, 모서리가 없어지거나 추가되는 현상이 발생할 수 있습니다. 예를 들어 2D 삼각형을 만드는 경우, 대부분 3개의 점을 이용해 삼각형을 만들려고 할 겁니다. <code>wireframe: true</code>라는 옵션이 있기는 하나, 이를 이용해 삼각형을 만들면 (WebGl은 삼각형을 만들 때 6개의 점을 요구하므로. 역주) 출력되는 건 선 하나 뿐일 겁니다. 삼각형 <code>geometry</code>를 <code>WireframeGeometry</code>에 넘겨주면 6개의 점과 3개의 선분을 가진 새 <code>geometry</code>를 생성합니다.</div>
<ide>
<del>눈치채셨겠지만 대부분의 원시 모델은 `Geometry`와 `BufferGeometry`가
<del>짝을 이룹니다. 다른 차이점들도 있지만 둘의 가장 큰 차이점은 성능과
<del>확장성입니다.
<del>
<del>`BufferGeometry` 기반의 원시 모델은 성능에 최적화된 모델입니다.
<del>`geometry`의 정점들은 바로 렌더링 시 GPU에서 불러오기 좋은 배열
<del>형태로 최적화됩니다. 때문에 초기화 속도도 빠르고 메모리 점유율도
<del>낮지만, 이 `geometry`의 데이터를 수정하려면 복잡한 프로그래밍 과정을
<del>거쳐야 합니다.
<del>
<del>이에 반해 `Geometry` 기반의 원시 모델은 훨씬 다루기 쉽습니다.
<del>3D 정점을 만드는 데는 `Vector3` 클래스, 삼각형을 만드는 데는
<del>`Face3` 클래스 등 자바스크립트 기반 클래스로 이루어져 있죠.
<del>다만 `BufferGeometry`에 비해 약간 많은 메모리를 더 차지하고,
<del>렌더링을 위해 Three.js가 이 모델과 유사한 `BufferGeometry`로
<del>변형시키는 과정이 들어간다는 것이 단점입니다.
<del>
<del>원시 모델을 사용하지 않을 계획이거나, 기하학 모델을 수학적으로
<del>계산하는 데 익숙하다면, `BufferGeometry` 기반의 원시 모델을
<del>사용하는 것이 좋습니다. 렌더링 전에 어떤 값을 수정해야 한다면
<del>`Geometry`가 훨씬 다루기 쉽겠죠.
<del>
<del>하나 예를 들면, `BufferGeometry`는 정점을 추가하는 것이 어렵습니다.
<del>`BufferGeometry`는 생성 시에 정점의 수가 정해지며, 메모리에 할당되고,
<del>그 다음 정점 데이터를 채워 넣습니다. 반면에 `Geometry`는 생성 후에도
<del>얼마든지 정점을 추가할 수 있죠.
<del>
<del>[커스텀 geometry를 만드는 법](threejs-custom-geometry.html)에 대해서는
<add>[커스텀 geometry를 만드는 법](threejs-custom-buffergeometry.html)에 대해서는
<ide> 나중에 자세히 다룰 것이므로, 지금은 각 원시 모델로 예제를 만들어 보겠습니다.
<ide> 예제 코드는 [지난 글](threejs-responsive.html)에서 썼던 예제를 쓸 거에요.
<ide>
<ide> function createMaterial() {
<ide> 위 예제에서는 `material`에 `side: THREE.DoubleSide` 옵션을
<ide> 지정했습니다. 이는 Three.js에게 삼각형의 양면 모두를 렌더링하라고
<ide> 알려주는 것이죠. 구나 정육면체 같은 물체는 보이지 않는 안쪽 면을
<del>굳이 렌더링할 이유가 없지만, 예제의 경우 `PlaneBufferGeometry`나
<del>`ShapeBufferGeometry` 등 안쪽 면이 없는 물체를 만들 것이므로
<add>굳이 렌더링할 이유가 없지만, 예제의 경우 `PlaneGeometry`나
<add>`ShapeGeometry` 등 안쪽 면이 없는 물체를 만들 것이므로
<ide> `side: THREE.DoubleSide` 옵션을 설정하지 않으면 반대편에서 봤을 때
<ide> 물체가 사라진 것처럼 보일 겁니다.
<ide>
<ide> function addSolidGeometry(x, y, geometry) {
<ide> const width = 8;
<ide> const height = 8;
<ide> const depth = 8;
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> 아래 코드를 보면 각 `geometry`마다 비슷한 단락으로 이루어진 것을 확인할 수 있습니다.
<ide>
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<del>몇몇 예외가 보일 텐데, 가장 크게 두드러진 것은 아마 `TextBufferGeometry`일 겁니다.
<del>`TextBufferGeometry`는 텍스트의 `mesh`를 생성하기 위해 3D 폰트 데이터를 필요로 합니다.
<add>몇몇 예외가 보일 텐데, 가장 크게 두드러진 것은 아마 `TextGeometry`일 겁니다.
<add>`TextGeometry`는 텍스트의 `mesh`를 생성하기 위해 3D 폰트 데이터를 필요로 합니다.
<ide> 이 데이터는 비동기로 로드되므로, 객체를 생성하기 전에 3D 폰트 데이터가 로드되기를 기다려야
<ide> 하죠. 폰트 로드 과정을 프로미스화 하면 이 과정를 더 쉽게 만들 수 있습니다. 먼저 `FontLoader`를
<ide> 생성하고, Promise를 반환하는 `loadFont` 함수를 만들어 요청을 Promise로 감쌉니다.
<ide> function addSolidGeometry(x, y, geometry) {
<ide>
<ide> async function doit() {
<ide> const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> function addLineGeometry(x, y, geometry) {
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add>const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2, // 글로벌 단위
<ide> const material = new THREE.PointsMaterial({
<ide> 받습니다.
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 위 그림에서 첫 번째 구체는 둘레로 5개, 높이로 3개의 면으로 분할되었습니다.
<ide> const material = new THREE.PointsMaterial({
<ide> 아래와 같은 결과가 나옵니다.
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> 5000 삼각형인 오른쪽 구체가 480 삼각형인 중간 구체보다 훨씬 좋다고
<ide> const material = new THREE.PointsMaterial({
<ide> 물론 선택이 쉬운 경우도 있습니다. 예를 들어 평면을 분할한다고 해보죠.
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 왼쪽의 평면은 2 삼각형입니다. 오른쪽 평면은 200 삼각형이죠.
<ide> const material = new THREE.PointsMaterial({
<ide>
<ide> 원시 모델 중 어떤 것도 실제 프로젝트에 적용하기가 어렵다면,
<ide> [.obj 파일](threejs-load-obj.html) 또는 [.gltf 파일](threejs-load-gltf.html)을
<del>로드하여 사용할 수 있습니다. 또는 [커스텀 Geometry](threejs-custom-geometry.html)나
<add>로드하여 사용할 수 있습니다. 또는
<ide> [커스텀 BufferGeometry](threejs-custom-buffergeometry.html)를 생성할 수도 있죠.
<ide>
<ide> 다음 장에서는 [씬 그래프와 그 사용법](threejs-scenegraph.html)에 대해
<ide><path>threejs/lessons/resources/threejs-primitives.js
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> });
<ide>
<ide> const diagrams = {
<del> BoxBufferGeometry: {
<add> BoxGeometry: {
<ide> ui: {
<ide> width: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> height: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> depthSegments: { type: 'range', min: 1, max: 10, },
<ide> },
<ide> create(width = 8, height = 8, depth = 8) {
<del> return new THREE.BoxBufferGeometry(width, height, depth);
<add> return new THREE.BoxGeometry(width, height, depth);
<ide> },
<ide> create2(width = 8, height = 8, depth = 8, widthSegments = 4, heightSegments = 4, depthSegments = 4) {
<del> return new THREE.BoxBufferGeometry(
<add> return new THREE.BoxGeometry(
<ide> width, height, depth,
<ide> widthSegments, heightSegments, depthSegments);
<ide> },
<ide> },
<del> CircleBufferGeometry: {
<add> CircleGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> segments: { type: 'range', min: 1, max: 50, },
<ide> thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> },
<ide> create(radius = 7, segments = 24) {
<del> return new THREE.CircleBufferGeometry(radius, segments);
<add> return new THREE.CircleGeometry(radius, segments);
<ide> },
<ide> create2(radius = 7, segments = 24, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
<del> return new THREE.CircleBufferGeometry(
<add> return new THREE.CircleGeometry(
<ide> radius, segments, thetaStart, thetaLength);
<ide> },
<ide> },
<del> ConeBufferGeometry: {
<add> ConeGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> height: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> },
<ide> create(radius = 6, height = 8, radialSegments = 16) {
<del> return new THREE.ConeBufferGeometry(radius, height, radialSegments);
<add> return new THREE.ConeGeometry(radius, height, radialSegments);
<ide> },
<ide> create2(radius = 6, height = 8, radialSegments = 16, heightSegments = 2, openEnded = true, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
<del> return new THREE.ConeBufferGeometry(
<add> return new THREE.ConeGeometry(
<ide> radius, height,
<ide> radialSegments, heightSegments,
<ide> openEnded,
<ide> thetaStart, thetaLength);
<ide> },
<ide> },
<del> CylinderBufferGeometry: {
<add> CylinderGeometry: {
<ide> ui: {
<ide> radiusTop: { type: 'range', min: 0, max: 10, precision: 1, },
<ide> radiusBottom: { type: 'range', min: 0, max: 10, precision: 1, },
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> },
<ide> create(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12) {
<del> return new THREE.CylinderBufferGeometry(
<add> return new THREE.CylinderGeometry(
<ide> radiusTop, radiusBottom, height, radialSegments);
<ide> },
<ide> create2(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12, heightSegments = 2, openEnded = false, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
<del> return new THREE.CylinderBufferGeometry(
<add> return new THREE.CylinderGeometry(
<ide> radiusTop, radiusBottom, height,
<ide> radialSegments, heightSegments,
<ide> openEnded,
<ide> thetaStart, thetaLength);
<ide> },
<ide> },
<del> DodecahedronBufferGeometry: {
<add> DodecahedronGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> detail: { type: 'range', min: 0, max: 5, precision: 0, },
<ide> },
<ide> create(radius = 7) {
<del> return new THREE.DodecahedronBufferGeometry(radius);
<add> return new THREE.DodecahedronGeometry(radius);
<ide> },
<ide> create2(radius = 7, detail = 2) {
<del> return new THREE.DodecahedronBufferGeometry(radius, detail);
<add> return new THREE.DodecahedronGeometry(radius, detail);
<ide> },
<ide> },
<del> ExtrudeBufferGeometry: {
<add> ExtrudeGeometry: {
<ide> ui: {
<ide> steps: { type: 'range', min: 1, max: 100, },
<ide> depth: { type: 'range', min: 1, max: 20, precision: 1, },
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> bevelSegments,
<ide> };
<ide>
<del> const geometry = new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
<add> const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
<ide> return geometry;
<ide> },
<ide> src: `
<ide> const extrudeSettings = {
<ide> bevelSegments: 2, // ui: bevelSegments
<ide> };
<ide>
<del>const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
<add>const geometry = THREE.ExtrudeGeometry(shape, extrudeSettings);
<ide> `,
<ide> create2(steps = 100) {
<ide> const outline = new THREE.Shape([
<ide> const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
<ide> extrudePath: shape,
<ide> };
<ide>
<del> const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
<add> const geometry = new THREE.ExtrudeGeometry(outline, extrudeSettings);
<ide> return geometry;
<ide> },
<ide> src2: `
<ide> const extrudeSettings = {
<ide> extrudePath: shape,
<ide> };
<ide>
<del>const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
<add>const geometry = new THREE.ExtrudeGeometry(outline, extrudeSettings);
<ide> return geometry;
<ide> `,
<ide> },
<del> IcosahedronBufferGeometry: {
<add> IcosahedronGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> detail: { type: 'range', min: 0, max: 5, precision: 0, },
<ide> },
<ide> create(radius = 7) {
<del> return new THREE.IcosahedronBufferGeometry(radius);
<add> return new THREE.IcosahedronGeometry(radius);
<ide> },
<ide> create2(radius = 7, detail = 2) {
<del> return new THREE.IcosahedronBufferGeometry(radius, detail);
<add> return new THREE.IcosahedronGeometry(radius, detail);
<ide> },
<ide> },
<del> LatheBufferGeometry: {
<add> LatheGeometry: {
<ide> ui: {
<ide> segments: { type: 'range', min: 1, max: 50, },
<ide> phiStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> return geometry;
<ide> for (let i = 0; i < 10; ++i) {
<ide> points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
<ide> }
<del> return new THREE.LatheBufferGeometry(points);
<add> return new THREE.LatheGeometry(points);
<ide> },
<ide> create2(segments = 12, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5) {
<ide> const points = [];
<ide> for (let i = 0; i < 10; ++i) {
<ide> points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
<ide> }
<del> return new THREE.LatheBufferGeometry(
<add> return new THREE.LatheGeometry(
<ide> points, segments, phiStart, phiLength);
<ide> },
<ide> },
<del> OctahedronBufferGeometry: {
<add> OctahedronGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> detail: { type: 'range', min: 0, max: 5, precision: 0, },
<ide> },
<ide> create(radius = 7) {
<del> return new THREE.OctahedronBufferGeometry(radius);
<add> return new THREE.OctahedronGeometry(radius);
<ide> },
<ide> create2(radius = 7, detail = 2) {
<del> return new THREE.OctahedronBufferGeometry(radius, detail);
<add> return new THREE.OctahedronGeometry(radius, detail);
<ide> },
<ide> },
<del> ParametricBufferGeometry: {
<add> ParametricGeometry: {
<ide> ui: {
<ide> stacks: { type: 'range', min: 1, max: 50, },
<ide> slices: { type: 'range', min: 1, max: 50, },
<ide> return geometry;
<ide> target.set(x, y, z).multiplyScalar(0.75);
<ide> }
<ide>
<del> return new THREE.ParametricBufferGeometry(
<add> return new THREE.ParametricGeometry(
<ide> klein, slices, stacks);
<ide> },
<ide> },
<del> PlaneBufferGeometry: {
<add> PlaneGeometry: {
<ide> ui: {
<ide> width: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> height: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> widthSegments: { type: 'range', min: 1, max: 10, },
<ide> heightSegments: { type: 'range', min: 1, max: 10, },
<ide> },
<ide> create(width = 9, height = 9) {
<del> return new THREE.PlaneBufferGeometry(width, height);
<add> return new THREE.PlaneGeometry(width, height);
<ide> },
<ide> create2(width = 9, height = 9, widthSegments = 2, heightSegments = 2) {
<del> return new THREE.PlaneBufferGeometry(
<add> return new THREE.PlaneGeometry(
<ide> width, height,
<ide> widthSegments, heightSegments);
<ide> },
<ide> },
<del> PolyhedronBufferGeometry: {
<add> PolyhedronGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> detail: { type: 'range', min: 0, max: 5, precision: 0, },
<ide> return geometry;
<ide> 2, 3, 7, 7, 6, 2,
<ide> 4, 5, 6, 6, 7, 4,
<ide> ];
<del> return new THREE.PolyhedronBufferGeometry(
<add> return new THREE.PolyhedronGeometry(
<ide> verticesOfCube, indicesOfFaces, radius, detail);
<ide> },
<ide> },
<del> RingBufferGeometry: {
<add> RingGeometry: {
<ide> ui: {
<ide> innerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> outerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> return geometry;
<ide> thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
<ide> },
<ide> create(innerRadius = 2, outerRadius = 7, thetaSegments = 18) {
<del> return new THREE.RingBufferGeometry(
<add> return new THREE.RingGeometry(
<ide> innerRadius, outerRadius, thetaSegments);
<ide> },
<ide> create2(innerRadius = 2, outerRadius = 7, thetaSegments = 18, phiSegments = 2, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
<del> return new THREE.RingBufferGeometry(
<add> return new THREE.RingGeometry(
<ide> innerRadius, outerRadius,
<ide> thetaSegments, phiSegments,
<ide> thetaStart, thetaLength);
<ide> },
<ide> },
<del> ShapeBufferGeometry: {
<add> ShapeGeometry: {
<ide> ui: {
<ide> curveSegments: { type: 'range', min: 1, max: 30, },
<ide> },
<ide> return geometry;
<ide> shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
<ide> shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
<ide> shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
<del> return new THREE.ShapeBufferGeometry(shape);
<add> return new THREE.ShapeGeometry(shape);
<ide> },
<ide> create2(curveSegments = 5) {
<ide> const shape = new THREE.Shape();
<ide> return geometry;
<ide> shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
<ide> shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
<ide> shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
<del> return new THREE.ShapeBufferGeometry(shape, curveSegments);
<add> return new THREE.ShapeGeometry(shape, curveSegments);
<ide> },
<ide> },
<del> SphereBufferGeometry: {
<add> SphereGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> widthSegments: { type: 'range', min: 1, max: 30, },
<ide> return geometry;
<ide> thetaLength: { type: 'range', min: 0, max: 1, mult: Math.PI },
<ide> },
<ide> create(radius = 7, widthSegments = 12, heightSegments = 8) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> create2(radius = 7, widthSegments = 12, heightSegments = 8, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 0.5) {
<del> return new THREE.SphereBufferGeometry(
<add> return new THREE.SphereGeometry(
<ide> radius,
<ide> widthSegments, heightSegments,
<ide> phiStart, phiLength,
<ide> thetaStart, thetaLength);
<ide> },
<ide> },
<del> TetrahedronBufferGeometry: {
<add> TetrahedronGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> detail: { type: 'range', min: 0, max: 5, precision: 0, },
<ide> },
<ide> create(radius = 7) {
<del> return new THREE.TetrahedronBufferGeometry(radius);
<add> return new THREE.TetrahedronGeometry(radius);
<ide> },
<ide> create2(radius = 7, detail = 2) {
<del> return new THREE.TetrahedronBufferGeometry(radius, detail);
<add> return new THREE.TetrahedronGeometry(radius, detail);
<ide> },
<ide> },
<del> TextBufferGeometry: {
<add> TextGeometry: {
<ide> ui: {
<ide> text: { type: 'text', maxLength: 30, },
<ide> size: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> return geometry;
<ide> create(text = 'three.js', size = 3, height = 0.2, curveSegments = 12, bevelEnabled = true, bevelThickness = 0.15, bevelSize = 0.3, bevelSegments = 5) {
<ide> return new Promise((resolve) => {
<ide> fontPromise.then((font) => {
<del> resolve(new THREE.TextBufferGeometry(text, {
<add> resolve(new THREE.TextGeometry(text, {
<ide> font: font,
<ide> size,
<ide> height,
<ide> const loader = new THREE.FontLoader();
<ide>
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
<ide> const text = 'three.js'; // ui: text
<del> const geometry = new THREE.TextBufferGeometry(text, {
<add> const geometry = new THREE.TextGeometry(text, {
<ide> font: font,
<ide> size: 3, // ui: size
<ide> height: 0.2, // ui: height
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font
<ide> });
<ide> `,
<ide> },
<del> TorusBufferGeometry: {
<add> TorusGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> radialSegments: { type: 'range', min: 1, max: 30, },
<ide> tubularSegments: { type: 'range', min: 1, max: 100, },
<ide> },
<ide> create(radius = 5, tubeRadius = 2, radialSegments = 8, tubularSegments = 24) {
<del> return new THREE.TorusBufferGeometry(
<add> return new THREE.TorusGeometry(
<ide> radius, tubeRadius,
<ide> radialSegments, tubularSegments);
<ide> },
<ide> },
<del> TorusKnotBufferGeometry: {
<add> TorusKnotGeometry: {
<ide> ui: {
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font
<ide> q: { type: 'range', min: 1, max: 20, },
<ide> },
<ide> create(radius = 3.5, tubeRadius = 1.5, radialSegments = 8, tubularSegments = 64, p = 2, q = 3) {
<del> return new THREE.TorusKnotBufferGeometry(
<add> return new THREE.TorusKnotGeometry(
<ide> radius, tubeRadius, tubularSegments, radialSegments, p, q);
<ide> },
<ide> },
<del> TubeBufferGeometry: {
<add> TubeGeometry: {
<ide> ui: {
<ide> tubularSegments: { type: 'range', min: 1, max: 100, },
<ide> radius: { type: 'range', min: 1, max: 10, precision: 1, },
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font
<ide> }
<ide>
<ide> const path = new CustomSinCurve(4);
<del> return new THREE.TubeBufferGeometry(
<add> return new THREE.TubeGeometry(
<ide> path, tubularSegments, radius, radialSegments, closed);
<ide> },
<ide> },
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font
<ide> create() {
<ide> return {
<ide> lineGeometry: new THREE.EdgesGeometry(
<del> new THREE.BoxBufferGeometry(8, 8, 8)),
<add> new THREE.BoxGeometry(8, 8, 8)),
<ide> };
<ide> },
<ide> create2(thresholdAngle = 1) {
<ide> return {
<ide> lineGeometry: new THREE.EdgesGeometry(
<del> new THREE.SphereBufferGeometry(7, 6, 3), thresholdAngle),
<add> new THREE.SphereGeometry(7, 6, 3), thresholdAngle),
<ide> };
<ide> },
<del> nonBuffer: false,
<ide> addConstCode: false,
<ide> src: `
<ide> const size = 8;
<ide> const widthSegments = 2;
<ide> const heightSegments = 2;
<ide> const depthSegments = 2;
<del>const boxGeometry = new THREE.BoxBufferGeometry(
<add>const boxGeometry = new THREE.BoxGeometry(
<ide> size, size, size,
<ide> widthSegments, heightSegments, depthSegments);
<ide> const geometry = new THREE.EdgesGeometry(boxGeometry);
<ide> const geometry = new THREE.EdgesGeometry(boxGeometry);
<ide> const radius = 7;
<ide> const widthSegments = 6;
<ide> const heightSegments = 3;
<del>const sphereGeometry = new THREE.SphereBufferGeometry(
<add>const sphereGeometry = new THREE.SphereGeometry(
<ide> radius, widthSegments, heightSegments);
<ide> const thresholdAngle = 1; // ui: thresholdAngle
<ide> const geometry = new THREE.EdgesGeometry(sphereGeometry, thresholdAngle);
<ide> const geometry = new THREE.EdgesGeometry(sphereGeometry, thresholdAngle);
<ide> create(widthSegments = 2, heightSegments = 2, depthSegments = 2) {
<ide> const size = 8;
<ide> return {
<del> lineGeometry: new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(
<add> lineGeometry: new THREE.WireframeGeometry(new THREE.BoxGeometry(
<ide> size, size, size,
<ide> widthSegments, heightSegments, depthSegments)),
<ide> };
<ide> },
<del> nonBuffer: false,
<ide> addConstCode: false,
<ide> src: `
<ide> const size = 8;
<ide> const widthSegments = 2; // ui: widthSegments
<ide> const heightSegments = 2; // ui: heightSegments
<ide> const depthSegments = 2; // ui: depthSegments
<ide> const geometry = new THREE.WireframeGeometry(
<del> new THREE.BoxBufferGeometry(
<add> new THREE.BoxGeometry(
<ide> size, size, size,
<ide> widthSegments, heightSegments, depthSegments));
<ide> `,
<ide> const geometry = new THREE.WireframeGeometry(
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2,
<ide> const geometry = new THREE.WireframeGeometry(
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 3 * window.devicePixelRatio,
<ide> const geometry = new THREE.WireframeGeometry(
<ide> };
<ide> },
<ide> },
<del> SphereBufferGeometryLow: {
<add> SphereGeometryLow: {
<ide> create(radius = 7, widthSegments = 5, heightSegments = 3) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> },
<del> SphereBufferGeometryMedium: {
<add> SphereGeometryMedium: {
<ide> create(radius = 7, widthSegments = 24, heightSegments = 10) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> },
<del> SphereBufferGeometryHigh: {
<add> SphereGeometryHigh: {
<ide> create(radius = 7, widthSegments = 50, heightSegments = 50) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> },
<del> SphereBufferGeometryLowSmooth: {
<add> SphereGeometryLowSmooth: {
<ide> create(radius = 7, widthSegments = 5, heightSegments = 3) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> showLines: false,
<ide> flatShading: false,
<ide> },
<del> SphereBufferGeometryMediumSmooth: {
<add> SphereGeometryMediumSmooth: {
<ide> create(radius = 7, widthSegments = 24, heightSegments = 10) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> showLines: false,
<ide> flatShading: false,
<ide> },
<del> SphereBufferGeometryHighSmooth: {
<add> SphereGeometryHighSmooth: {
<ide> create(radius = 7, widthSegments = 50, heightSegments = 50) {
<del> return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> },
<ide> showLines: false,
<ide> flatShading: false,
<ide> },
<del> PlaneBufferGeometryLow: {
<add> PlaneGeometryLow: {
<ide> create(width = 9, height = 9, widthSegments = 1, heightSegments = 1) {
<del> return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
<add> return new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);
<ide> },
<ide> },
<del> PlaneBufferGeometryHigh: {
<add> PlaneGeometryHigh: {
<ide> create(width = 9, height = 9, widthSegments = 10, heightSegments = 10) {
<del> return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
<add> return new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);
<ide> },
<ide> },
<ide> };
<ide> const geometry = new THREE.WireframeGeometry(
<ide> const right = addDiv(pair, 'desc');
<ide> addDeepLink(right, '#', `#${base.id}`);
<ide> addLink(right, name);
<del> if (info.nonBuffer !== false) {
<del> addElem(right, 'span', '', ', ');
<del> addLink(right, name.replace('Buffer', ''));
<del> }
<ide> addDiv(right, '.note').innerHTML = text;
<ide>
<ide> // I get that this is super brittle. I think I'd have to
<ide><path>threejs/lessons/ru/threejs-primitives.md
<ide> Three.js имеет большое количество примитивов. П
<ide> создание и загрузку данных из нескольких программ 3D-моделирования.
<ide> А сейчас давайте рассмотрим некоторые из доступных примитивов.
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">Прямоугольный параллелепипед</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">Круг</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">Конус</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">Цилиндр</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">Додекаэдр (12 граней)</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">Выдавленная 2d фигура с скругленными краями.
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">Прямоугольный параллелепипед</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">Круг</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">Конус</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">Цилиндр</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">Додекаэдр (12 граней)</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">Выдавленная 2d фигура с скругленными краями.
<ide> Здесь мы выдавливаем форму сердца. Обратите внимание, это основа
<del>для <code>TextBufferGeometry</code> и <code>TextGeometry</code> соответственно.</div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">Икосаэдр (20 граней)</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">Форма, созданная вращением линии. Например, лампы, кегли для боулинга, свечи, подсвечники, бокалы для вина, стаканы для питья и т. Д. Вы указываете 2-мерный силуэт в виде серии точек, а затем указываете three.js , сколько секций нужно сделать, когда он вращает силуэт вокруг оси.</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">Октаэдр (8 граней)</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">Поверхность, созданная путем предоставления функции, которая берет 2d точку из сетки и возвращает соответствующую 3d точку.</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2D плоскость</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">Берет набор треугольников с центром вокруг точки и проецирует их на сферу</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">2D диск с отверстием в центре</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">2D контур, который строится из треугольников</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">Сфера</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">Тераэдр (4 грани)</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3D-текст, сгенерированный из 3D-шрифта и строки</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">Тор (пончик)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">Торический узел</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">Труба - круг проходящий путь</div>
<add>для <code>TextGeometry</code> и <code>TextGeometry</code> соответственно.</div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">Икосаэдр (20 граней)</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Форма, созданная вращением линии. Например, лампы, кегли для боулинга, свечи, подсвечники, бокалы для вина, стаканы для питья и т. Д. Вы указываете 2-мерный силуэт в виде серии точек, а затем указываете three.js , сколько секций нужно сделать, когда он вращает силуэт вокруг оси.</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">Октаэдр (8 граней)</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">Поверхность, созданная путем предоставления функции, которая берет 2d точку из сетки и возвращает соответствующую 3d точку.</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">2D плоскость</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">Берет набор треугольников с центром вокруг точки и проецирует их на сферу</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">2D диск с отверстием в центре</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">2D контур, который строится из треугольников</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">Сфера</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">Тераэдр (4 грани)</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">3D-текст, сгенерированный из 3D-шрифта и строки</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">Тор (пончик)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">Торический узел</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">Труба - круг проходящий путь</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">Вспомогательный объект, который принимает другую геометрию в качестве входных данных и генерирует ребра, только если угол между гранями больше некоторого порога. Например, если вы посмотрите на прямоугольник сверху, он показывает линию, проходящую через каждую грань, показывая каждый треугольник, из которого состоит прямоугольник. Используя EdgesGeometry, вместо этого удаляются средние линии.</div>
<ide> <div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">Создает геометрию, которая содержит один отрезок (2 точки) на ребро в заданной геометрии. Без этого вы часто теряете ребра или получаете дополнительные ребра, поскольку WebGL обычно требует 2 точки на отрезок. Например, если бы у вас был только один треугольник, было бы только 3 очка. Если вы попытаетесь нарисовать его, используя материал с <code>wireframe: true</code> вы получите только одну линию. А передача этой triangle geometry в <code>WireframeGeometry</code> создаст новую геометрию, которая имеет 3 отрезка линий, используя 6 точек..</div>
<ide>
<del>Вы можете заметить, что большинство из них приходят парами `Geometry`
<del>или `BufferGeometry`. Разница между этими двумя типами заключается
<del>в гибкости и производительности.
<del>
<del>`BufferGeometry` основанные на примитивах типы ориентированы на производительность.
<del>Вершины для геометрии генерируются непосредственно в эффективный формат
<del>типизированного массива, готовый для загрузки в графический процессор
<del>для рендеринга. Это означает, что они быстрее запускаются и занимают
<del>меньше памяти, но если вы хотите изменить их данные, они берут то,
<del>что часто считается более сложным программированием для манипулирования.
<del>
<del>`Geometry` основанные на примитивах являются более гибкими, легче манипулировать типом.
<del>Они построены на основе классов JavaScript, таких как `Vector3` для 3D-точки, `Face3`
<del>для треугольников. Они занимают немного памяти, и прежде чем их можно будет отобразить,
<del>нужно будет преобразовать их во что-то похожее на соответствующее
<del>`BufferGeometry` представление.
<del>
<del>Если вы знаете, что не собираетесь манипулировать примитивом или если вам удобно
<del>выполнять математику на прямую, чтобы манипулировать их внутренностями, то лучше
<del>использовать основанные на `BufferGeometry` примитивы.
<del>Если, с другой стороны, вы хотите изменить некоторые вещи перед рендерингом,
<del>вам может быть проще работать с примитивами основанными на `Geometry`.
<del>
<del>В качестве простого примера в `BufferGeometry` не могут быть легко добавлены новые вершины.
<del>Количество используемых вершин определяется во время создания, создается
<del>хранилище, а затем заполняются данные для вершин. В то время как с `Geometry`
<del>вы можете добавлять вершины по мере необходимости.
<del>
<ide> Мы рассмотрим создание пользовательской геометрии в другой статье.
<ide> А пока давайте создадим пример создания каждого типа примитива.
<ide> Начнем с [примеров из предыдущей статьи](threejs-responsive.html).
<ide> function createMaterial() {
<ide> такой как сфера или куб, обычно нет причин рисовать
<ide> задние стороны треугольников, поскольку все они обращены
<ide> внутрь фигуры. В нашем случае мы рисуем несколько вещей,
<del>таких как `PlaneBufferGeometry` и `ShapeBufferGeometry`
<add>таких как `PlaneGeometry` и `ShapeGeometry`
<ide> которые являются двухмерными и поэтому не имеют внутренней
<ide> части. Без установки `side: THREE.DoubleSide` они исчезнут,
<ide> при взгляде на их задние стороны.
<ide> function addSolidGeometry(x, y, geometry) {
<ide> const width = 8;
<ide> const height = 8;
<ide> const depth = 8;
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> function addSolidGeometry(x, y, geometry) {
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<ide> Есть несколько заметных исключений из шаблона выше.
<del>Самым большим, вероятно, является `TextBufferGeometry`. Он должен
<add>Самым большим, вероятно, является `TextGeometry`. Он должен
<ide> загрузить данные 3D шрифта, прежде чем он сможет сгенерировать
<ide> сетку для текста. Эти данные загружаются асинхронно, поэтому
<ide> нам нужно дождаться их загрузки, прежде чем пытаться создать
<ide> function addSolidGeometry(x, y, geometry) {
<ide> {
<ide> const loader = new THREE.FontLoader();
<ide> loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> function addLineGeometry(x, y, geometry) {
<ide> Например
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> Первая сфера имеет 5 сегментов вокруг и 3 высоты, что составляет 15 сегментов
<ide> function addLineGeometry(x, y, geometry) {
<ide> и мы получим это
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> Сейчас не очень понятно, что тот, который справа с 5000 треугольниками,
<ide> function addLineGeometry(x, y, geometry) {
<ide> Иногда выбрать легко. Например, вы можете выбрать разделение для плоскости.
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> Плоскость слева - это 2 треугольника. Плоскость справа - это 200 треугольников.
<ide><path>threejs/lessons/threejs-primitives.md
<ide> primitives.
<ide> Many of the primitives below have defaults for some or all of their
<ide> parameters so you can use more or less depending on your needs.
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">A Box</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">A flat circle</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">A Cone</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">A Cylinder</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">A dodecahedron (12 sides)</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">An extruded 2d shape with optional bevelling.
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">A Box</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">A flat circle</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">A Cone</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">A Cylinder</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">A dodecahedron (12 sides)</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">An extruded 2d shape with optional bevelling.
<ide> Here we are extruding a heart shape. Note this is the basis
<del>for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.</div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would be: lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">An Octahedron (8 sides)</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">A surface generated by providing a function that takes a 2D point from a grid and returns the corresponding 3d point.</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">A 2D plane</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">A 2D disc with a hole in the center</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">A 2D outline that gets triangulated</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">A sphere</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">A tetrahedron (4 sides)</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3D text generated from a 3D font and a string</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">A torus (donut)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">A torus knot</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">A circle traced down a path</div>
<add>for <code>TextGeometry</code> and <code>TextGeometry</code> respectively.</div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">An icosahedron (20 sides)</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">A shape generated by spinning a line. Examples would be: lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">An Octahedron (8 sides)</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">A surface generated by providing a function that takes a 2D point from a grid and returns the corresponding 3d point.</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">A 2D plane</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">A 2D disc with a hole in the center</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">A 2D outline that gets triangulated</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">A sphere</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">A tetrahedron (4 sides)</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">3D text generated from a 3D font and a string</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">A torus (donut)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">A torus knot</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">A circle traced down a path</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an <code>EdgesGeometry</code> instead the middle lines are removed. Adjust the thresholdAngle below and you'll see the edges below that threshold disappear.</div>
<ide> <div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. Without this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code>wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <code>WireframeGeometry</code> will generate a new geometry that has 3 lines segments using 6 points..</div>
<ide>
<del>You might notice of most of them come in pairs of `Geometry`
<del>or `BufferGeometry`. The difference between the 2 types is effectively flexibility
<del>vs performance.
<del>
<del>`BufferGeometry` based primitives are the performance oriented
<del>types. The vertices for the geometry are generated directly
<del>into an efficient typed array format ready to be uploaded to the GPU
<del>for rendering. This means they are faster to start up
<del>and take less memory but if you want to modify their
<del>data they take what is often considered more complex
<del>programming to manipulate.
<del>
<del>`Geometry` based primitives are the more flexible, easier to manipulate
<del>type. They are built from JavaScript based classes like `Vector3` for
<del>3D points, `Face3` for triangles.
<del>They take quite a bit of memory and before they can be rendered three.js will need to
<del>convert them to something similar to the corresponding `BufferGeometry` representation.
<del>
<del>If you know you are not going to manipulate a primitive or
<del>if you're comfortable doing the math to manipulate their
<del>internals then it's best to go with the `BufferGeometry`
<del>based primitives. If on the other hand you want to change
<del>a few things before rendering you might find the `Geometry`
<del>based primitives easier to deal with.
<del>
<del>As an simple example a `BufferGeometry`
<del>can not have new vertices easily added. The number of vertices used is
<del>decided at creation time, storage is created, and then data for vertices
<del>are filled in. Whereas for `Geometry` you can add vertices as you go.
<del>
<del>We'll go over creating custom geometry in [another article](threejs-custom-geometry.html). For now
<add>We'll go over creating custom geometry in [another article](threejs-custom-buffergeometry.html). For now
<ide> let's make an example creating each type of primitive. We'll start
<ide> with the [examples from the previous article](threejs-responsive.html).
<ide>
<ide> that make up a shape. For a solid shape like a sphere
<ide> or a cube there's usually no reason to draw the
<ide> back sides of triangles as they all face inside the
<ide> shape. In our case though we are drawing a few things
<del>like the `PlaneBufferGeometry` and the `ShapeBufferGeometry`
<add>like the `PlaneGeometry` and the `ShapeGeometry`
<ide> which are 2 dimensional and so have no inside. Without
<ide> setting `side: THREE.DoubleSide` they would disappear
<ide> when looking at their back sides.
<ide> For example creating a box
<ide> const width = 8;
<ide> const height = 8;
<ide> const depth = 8;
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> Here's the result:
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<ide> There are a couple of notable exceptions to the pattern above.
<del>The biggest is probably the `TextBufferGeometry`. It needs to load
<add>The biggest is probably the `TextGeometry`. It needs to load
<ide> 3D font data before it can generate a mesh for the text.
<ide> That data loads asynchronously so we need to wait for it
<ide> to load before trying to create the geometry. By promisifiying
<ide> And finally create the geometry and call `addObject` to add it the scene.
<ide>
<ide> async function doit() {
<ide> const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> to take you directly to the docs for that shape.
<ide>
<ide> There is one other pair of classes that doesn't really fit the patterns above. Those are
<ide> the `PointsMaterial` and the `Points` class. `Points` is like `LineSegments` above in that it takes a
<del>a `Geometry` or `BufferGeometry` but draws points at each vertex instead of lines.
<add>a `BufferGeometry` but draws points at each vertex instead of lines.
<ide> To use it you also need to pass it a `PointsMaterial` which
<ide> take a [`size`](PointsMaterial.size) for how large to make the points.
<ide>
<ide> ```js
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add>const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2, // in world units
<ide> might be the sphere geometries. Spheres take parameters for
<ide> how many divisions to make around and how many top to bottom. For example
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> The first sphere has 5 segments around and 3 high which is 15 segments
<ide> look like you need a high number of segments but remove the lines
<ide> and the flat shading and we get this
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> It's now not so clear that the one on the right with 5000 triangles
<ide> Sometimes it's easy to choose. For example you can also choose
<ide> to subdivide a plane.
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> The plane on the left is 2 triangles. The plane on the right
<ide> tradeoff is for your particular situation.
<ide> If none of the shapes above fit your use case you can load
<ide> geometry for example from a [.obj file](threejs-load-obj.html)
<ide> or a [.gltf file](threejs-load-gltf.html).
<del>You can also create your own [custom Geometry](threejs-custom-geometry.html)
<del>or [custom BufferGeometry](threejs-custom-buffergeometry.html).
<add>You can also create your own [custom BufferGeometry](threejs-custom-buffergeometry.html).
<ide>
<ide> Next up let's go over [how three's scene graph works and how
<ide> to use it](threejs-scenegraph.html).
<ide><path>threejs/lessons/zh_cn/threejs-primitives.md
<ide> Three.js 有很多图元。图元就是一些 3D 的形状,在运行时根据
<ide> 下面的很多图元都有默认的部分或者全部参数,所以可以根据你的需要选择使用。
<ide>
<ide>
<del><div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">盒子</div>
<del><div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">平面圆</div>
<del><div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">锥形</div>
<del><div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">圆柱</div>
<del><div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">十二面体</div>
<del><div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">受挤压的 2D 形状,及可选的斜切。
<del>这里我们挤压了一个心型。注意,这分别是 <code>TextBufferGeometry</code> 和 <code>TextGeometry</code> 的基础。<div>
<del><div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">二十面体</div>
<del><div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">绕着一条线旋转形成的形状。例如:灯泡、保龄球瓶、蜡烛、蜡烛台、酒瓶、玻璃杯等。你提供一系列点作为 2D 轮廓,并告诉 Three.js 沿着某条轴旋转时需要将侧面分成多少块。</div>
<del><div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">八面体</div>
<del><div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">通过提供一个函数(将网格中 2D 的点转成对应的 3D 点)生成的表面。</div>
<del><div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2D 平面</div>
<del><div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">将一些环绕着中心点的三角形投影到球体上</div>
<del><div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">中间有洞的 2D 圆盘</div>
<del><div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">2D 的三角轮廓</div>
<del><div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">球体</div>
<del><div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">四面体</div>
<del><div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">根据 3D 字体和字符串生成的 3D 文字</div>
<del><div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">圆环体(甜甜圈)</div>
<del><div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">环形节</div>
<del><div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">圆环沿着路径</div>
<add><div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">盒子</div>
<add><div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">平面圆</div>
<add><div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">锥形</div>
<add><div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">圆柱</div>
<add><div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">十二面体</div>
<add><div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">受挤压的 2D 形状,及可选的斜切。
<add>这里我们挤压了一个心型。注意,这分别是 <code>TextGeometry</code> 和 <code>TextGeometry</code> 的基础。<div>
<add><div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">二十面体</div>
<add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">绕着一条线旋转形成的形状。例如:灯泡、保龄球瓶、蜡烛、蜡烛台、酒瓶、玻璃杯等。你提供一系列点作为 2D 轮廓,并告诉 Three.js 沿着某条轴旋转时需要将侧面分成多少块。</div>
<add><div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">八面体</div>
<add><div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">通过提供一个函数(将网格中 2D 的点转成对应的 3D 点)生成的表面。</div>
<add><div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">2D 平面</div>
<add><div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">将一些环绕着中心点的三角形投影到球体上</div>
<add><div id="Diagram-RingGeometry" data-primitive="RingGeometry">中间有洞的 2D 圆盘</div>
<add><div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">2D 的三角轮廓</div>
<add><div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">球体</div>
<add><div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">四面体</div>
<add><div id="Diagram-TextGeometry" data-primitive="TextGeometry">根据 3D 字体和字符串生成的 3D 文字</div>
<add><div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">圆环体(甜甜圈)</div>
<add><div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">环形节</div>
<add><div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">圆环沿着路径</div>
<ide> <div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">一个工具对象,将一个几何体作为输入,生成面夹角大于某个阈值的那条边。例如,你从顶上看一个盒子,你会看到有一条线穿过这个面,因为每个组成这个盒子的三角形都显示出来了。而如果使用 <code>EdgesGeometry</code> 中间的线就会被移除。调整下面的 thresholdAngle,你就会看到夹角小于这个值的边消失了。</div>
<ide> <div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">对于给定的几何体,生成每个边包含一个线段(2 个点)的几何体。如果不这样,通常缺边或者多边,因为 WebGL 中每条边通常需要 2 个点。例如,如果你只有一个三角形,就只有 3 个点 。如果你用 <code>wireframe: true</code> 的材质来绘制它,你只能得到一条线。将这个三角形几何体传给 <code>WireframeGeometry</code> 就能生成一个新的几何体,这个几何体用 6 个点组成 3 条线段。</div>
<ide>
<ide> Three.js 有很多图元。图元就是一些 3D 的形状,在运行时根据
<ide> 使用顶点的数量在创建时就定好了,相应的创建存储,填充顶点数据。
<ide> 但用 `Geometry` 你就能随时添加顶点。
<ide>
<del>我们会在 [另一篇文章](threejs-custom-geometry.html) 中来讲创建自定义几何体。
<add>我们会在 [另一篇文章](threejs-custom-buffergeometry.html) 中来讲创建自定义几何体。
<ide> 现在,我们来为创建每一个图元作为例子。
<ide> 我们从 [上一篇文章的例子](threejs-responsive.html) 开始。
<ide>
<ide> function createMaterial() {
<ide>
<ide> 同时,我们将 `side: THREE.DoubleSide` 传给材质。这告诉 Three.js 绘制组成形状的三角形的两个面。
<ide> 对于实心的形状,像球体或立方体,通常不需要绘制三角形的背面,因为它们全部朝向内部。
<del>对于我们的情况,我们会绘制一些像 `PlaneBufferGeometry` 和 `ShapeBufferGeometry` 这样的二维图形,没有内部,
<add>对于我们的情况,我们会绘制一些像 `PlaneGeometry` 和 `ShapeGeometry` 这样的二维图形,没有内部,
<ide> 如果不设置 `side: THREE.DoubleSide`,当从反面看时它们会消失。
<ide>
<ide> 需要注意的是,如果 **不** 设置 `side: THREE.DoubleSide` 绘制会更快,所以最好只在需要的时候设置它。
<ide> function addSolidGeometry(x, y, geometry) {
<ide> const width = 8;
<ide> const height = 8;
<ide> const depth = 8;
<del> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
<add> addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
<ide> }
<ide> ```
<ide>
<ide> function addSolidGeometry(x, y, geometry) {
<ide>
<ide> {{{example url="../threejs-primitives.html" }}}
<ide>
<del>上面的模式有一些值得注意的例外。最大的可能就是 `TextBufferGeometry`。在为文字生成网格前需要先加载 3D 字体数据。
<add>上面的模式有一些值得注意的例外。最大的可能就是 `TextGeometry`。在为文字生成网格前需要先加载 3D 字体数据。
<ide> 数据的加载是异步的,所以在尝试创建几何体前需要等待。通过将字体加载 Promise 化,我们可以让这个过程更简单。
<ide> 我们创建一个 `FontLoader`,然后 `loadFont` 函数返回一个 `promise`,`promise` 的 `resolve` 会给我们字体。
<ide> 接着我们创建一个 `async` 函数 `doit`,使用 `await` 加载字体。最后创建几何体,调用 `addOjbect` 将它添加到场景中。
<ide> function addSolidGeometry(x, y, geometry) {
<ide>
<ide> async function doit() {
<ide> const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
<del> const geometry = new THREE.TextBufferGeometry('three.js', {
<add> const geometry = new THREE.TextGeometry('three.js', {
<ide> font: font,
<ide> size: 3.0,
<ide> height: .2,
<ide> function addLineGeometry(x, y, geometry) {
<ide> const radius = 7;
<ide> const widthSegments = 12;
<ide> const heightSegments = 8;
<del>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add>const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
<ide> const material = new THREE.PointsMaterial({
<ide> color: 'red',
<ide> size: 0.2, // in world units
<ide> const material = new THREE.PointsMaterial({
<ide> 一个很好的例子就是球形几何体。它可以这些参数:一圈组成的片数、从上到下的数量等。例如:
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLow"></div>
<del><div data-diagram="SphereBufferGeometryMedium"></div>
<del><div data-diagram="SphereBufferGeometryHigh"></div>
<add><div data-diagram="SphereGeometryLow"></div>
<add><div data-diagram="SphereGeometryMedium"></div>
<add><div data-diagram="SphereGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 第一个球体一圈有 5 分片,高度为 3,一共 15 片,或者 30 个三角形。
<ide> const material = new THREE.PointsMaterial({
<ide> 由你决定需要细分成多少。看起来你可能需要较多数量的分片,但去除线,设置平面着色,我们就得到了:
<ide>
<ide> <div class="spread">
<del><div data-diagram="SphereBufferGeometryLowSmooth"></div>
<del><div data-diagram="SphereBufferGeometryMediumSmooth"></div>
<del><div data-diagram="SphereBufferGeometryHighSmooth"></div>
<add><div data-diagram="SphereGeometryLowSmooth"></div>
<add><div data-diagram="SphereGeometryMediumSmooth"></div>
<add><div data-diagram="SphereGeometryHighSmooth"></div>
<ide> </div>
<ide>
<ide> 现在并不明显是否右边有 5000 个三角形的比中间只有 480 个三角形的好更多。
<ide> const material = new THREE.PointsMaterial({
<ide> 有时候很容易选择。例如你可以选择将平面细分。
<ide>
<ide> <div class="spread">
<del><div data-diagram="PlaneBufferGeometryLow"></div>
<del><div data-diagram="PlaneBufferGeometryHigh"></div>
<add><div data-diagram="PlaneGeometryLow"></div>
<add><div data-diagram="PlaneGeometryHigh"></div>
<ide> </div>
<ide>
<ide> 左边的平面有 2 个三角形,右边的平面有 200 个三角形。不像球体,在多数平面的应用场景中,并没有什么折中的方法。
<ide> const material = new THREE.PointsMaterial({
<ide> 你需要根据你的具体情况选择合适的方案。
<ide>
<ide> 如果上面的形状不符合你的使用需求,你可以从 [.obj 文件](threejs-load-obj.html) 或 [.gltf 文件](threejs-load-gltf.html) 加载几何体。
<del>你也可以创建 [自定义 Geometry](threejs-custom-geometry.html) 或 [自定义 BufferGeometry](threejs-custom-buffergeometry.html)。
<add>你也可以创建 [自定义 Geometry](threejs-custom-buffergeometry.html)。
<ide>
<ide> 接下来是 [Three.js 的场景图是如何工作的及如何使用它](threejs-scenegraph.html)。
<ide> | 7 |
Javascript | Javascript | hide runtime in examples by default | 80fca63e7be6c81189e52b85e1a7cf8d693aa59c | <ide><path>examples/build-common.js
<ide> var fs = require("fs");
<ide> var extraArgs = "";
<ide>
<ide> var targetArgs = global.NO_TARGET_ARGS ? "" : " ./example.js js/output.js";
<del>var displayReasons = global.NO_REASONS ? "" : " --display-reasons --display-used-exports";
<add>var displayReasons = global.NO_REASONS ? "" : " --display-reasons --display-used-exports --display-provided-exports";
<ide> (function doIt(remainingTimes) {
<ide> cp.exec("node ../../bin/webpack.js" + displayReasons + " --display-chunks --display-modules --display-origins --display-entrypoints --output-public-path \"js/\" -p " + extraArgs + targetArgs, function (error, stdout, stderr) {
<ide> if(stderr && remainingTimes === 1)
<ide><path>examples/template-common.js
<ide> function lessStrict(regExpStr) {
<ide> return regExpStr;
<ide> }
<ide>
<add>var runtimeRegexp = /(```\s*(?:js|javascript)\n)(\/\*\*\*\*\*\*\/ \(function\(modules\) \{ \/\/ webpackBootstrap\n(?:.|\n)*\n\/\*\*\*\*\*\*\/ \}\)\n\/\**\/\n)/;
<add>
<ide> module.exports = function(template, baseDir, stdout, prefix) {
<ide>
<ide> var regexp = new RegExp("\\{\\{" + (prefix ? prefix+":" : "") + "([^:\\}]+)\\}\\}", "g")
<ide> module.exports = function(template, baseDir, stdout, prefix) {
<ide> if(match === "stdout")
<ide> return stdout;
<ide> return fs.readFileSync(path.join(baseDir, match), "utf-8").replace(/[\r\n]*$/, "");
<del> }).replace(cwd, ".").replace(webpack, "(webpack)").replace(webpackParent, "(webpack)/~");
<add> })
<add> .replace(/\r\n/g, "\n")
<add> .replace(cwd, ".")
<add> .replace(webpack, "(webpack)")
<add> .replace(webpackParent, "(webpack)/~")
<add> .replace(runtimeRegexp, function(match) {
<add> match = runtimeRegexp.exec(match);
<add> return "<details><summary>`/******/ (function(modules) { /* webpackBootstrap */ })`</summary>\n" + match[1] + match[2] + "```\n</details>\n" + match[1];
<add> });
<ide>
<ide> }
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | add a header for the directive info section | 1b4289ce769e1c32cde6e5b246c1a176b9ecf491 | <ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide> if (self.priority !== undefined) {
<ide> list.push('This directive executes at priority level ' + self.priority + '.');
<ide> }
<del> dom.ul(list);
<add>
<add> if (list.length) {
<add> dom.h('Directive info', function() {
<add> dom.ul(list);
<add> });
<add> }
<ide> },
<ide>
<ide> html_usage_overview: function(dom){ | 1 |
Go | Go | fix duplicate layers in manifest | 35081ea4b6711b1cfccb67b0f0d691b7adc85ff6 | <ide><path>graph/push.go
<ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o
<ide> }
<ide>
<ide> layersSeen := make(map[string]bool)
<del> layers := []*image.Image{layer}
<add> layers := []*image.Image{}
<ide> for ; layer != nil; layer, err = s.graph.GetParent(layer) {
<ide> if err != nil {
<ide> return err | 1 |
PHP | PHP | trim comment bloat on response class | e334fd80b6167c48f26ec82b6abc993b0c0635dc | <ide><path>system/response.php
<ide> public static function make($content, $status = 200)
<ide> */
<ide> public static function prepare($response)
<ide> {
<del> // --------------------------------------------------------------
<del> // If the response is a Redirect instance, grab the Response.
<del> // The Redirect class manages a Response instance internally.
<del> // --------------------------------------------------------------
<add> // If the response is a Redirect instance, grab the Response. The Redirect class
<add> // manages a Response instance internally.
<ide> if ($response instanceof Redirect)
<ide> {
<ide> $response = $response->response; | 1 |
Javascript | Javascript | parse quarter from string | ca4184ae21f239dc90a1f0be398469b3b07eeecd | <ide><path>moment.js
<ide> isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
<ide>
<ide> // format tokens
<del> formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
<add> formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
<ide> localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
<ide>
<ide> // parsing token regexes
<ide> function getParseRegexForToken(token, config) {
<ide> var a, strict = config._strict;
<ide> switch (token) {
<add> case 'Q':
<add> return parseTokenOneDigit;
<ide> case 'DDDD':
<ide> return parseTokenThreeDigits;
<ide> case 'YYYY':
<ide> var a, datePartArray = config._a;
<ide>
<ide> switch (token) {
<add> // QUARTER
<add> case 'Q':
<add> if (input != null) {
<add> datePartArray[MONTH] = (toInt(input) - 1) * 3;
<add> }
<add> break;
<ide> // MONTH
<ide> case 'M' : // fall through to MM
<ide> case 'MM' :
<ide><path>test/moment/create.js
<ide> exports.create = {
<ide> "string with format" : function (test) {
<ide> moment.lang('en');
<ide> var a = [
<add> ['YYYY-Q', '2014-4'],
<ide> ['MM-DD-YYYY', '12-02-1999'],
<ide> ['DD-MM-YYYY', '12-02-1999'],
<ide> ['DD/MM/YYYY', '12/02/1999'],
<ide> exports.create = {
<ide> },
<ide>
<ide> "strict parsing" : function (test) {
<add> test.equal(moment("2014-", "YYYY-Q", true).isValid(), false, "fail missing quarter");
<add>
<ide> test.equal(moment("2012-05", "YYYY-MM", true).format("YYYY-MM"), "2012-05", "parse correct string");
<ide> test.equal(moment(" 2012-05", "YYYY-MM", true).isValid(), false, "fail on extra whitespace");
<ide> test.equal(moment("foo 2012-05", "[foo] YYYY-MM", true).format('YYYY-MM'), "2012-05", "handle fixed text"); | 2 |
Go | Go | expose daemonhost to client users | 6ce6ae1cd11d888e0c8ede20926b86981cee5ce1 | <ide><path>client/client.go
<ide> func (cli *Client) UpdateClientVersion(v string) {
<ide>
<ide> }
<ide>
<add>// DaemonHost returns the host associated with this instance of the Client.
<add>// This operation doesn't acquire a mutex.
<add>func (cli *Client) DaemonHost() string {
<add> return cli.host
<add>}
<add>
<ide> // ParseHost verifies that the given host strings is valid.
<ide> func ParseHost(host string) (string, string, string, error) {
<ide> protoAddrParts := strings.SplitN(host, "://", 2)
<ide><path>client/interface.go
<ide> type CommonAPIClient interface {
<ide> SystemAPIClient
<ide> VolumeAPIClient
<ide> ClientVersion() string
<add> DaemonHost() string
<ide> ServerVersion(ctx context.Context) (types.Version, error)
<ide> UpdateClientVersion(v string)
<ide> } | 2 |
Javascript | Javascript | remove unused method | fc7834f9acc8463c6cae146d973d3f224b49696e | <ide><path>src/parser.js
<ide> function parser(text, json){
<ide> return {
<ide> assignable: assertConsumed(assignable),
<ide> primary: assertConsumed(primary),
<del> statements: assertConsumed(statements),
<del> filter: assertConsumed(filter)
<add> statements: assertConsumed(statements)
<ide> };
<ide>
<ide> function assertConsumed(fn) { | 1 |
Javascript | Javascript | add urlfor to router | c01c19f023efa4279a4d9465c8aaa951e05a847b | <ide><path>packages/ember-states/lib/routable.js
<ide> var paramForClass = function(classObject) {
<ide> return Ember.String.underscore(last) + "_id";
<ide> };
<ide>
<add>var merge = function(original, hash) {
<add> for (var prop in hash) {
<add> if (!hash.hasOwnProperty(prop)) { continue; }
<add> original[prop] = hash[prop];
<add> }
<add>};
<add>
<ide> Ember.Routable = Ember.Mixin.create({
<ide> init: function() {
<ide> var redirection;
<ide> Ember.Routable = Ember.Mixin.create({
<ide> }
<ide> },
<ide>
<del> absoluteRoute: function(manager) {
<add> absoluteRoute: function(manager, hash) {
<ide> var parentState = get(this, 'parentState');
<ide> var path = '';
<ide>
<ide> if (get(parentState, 'isRoutable')) {
<del> path = parentState.absoluteRoute(manager);
<add> path = parentState.absoluteRoute(manager, hash);
<ide> }
<ide>
<ide> var matcher = get(this, 'routeMatcher'),
<del> hash = get(manager, 'stateMeta').get(this);
<add> meta = get(manager, 'stateMeta').get(this);
<ide>
<add> hash = hash || {};
<add> merge(hash, meta);
<ide> var generated = matcher.generate(hash);
<ide>
<ide> if (generated !== "") {
<ide><path>packages/ember-states/lib/state_manager.js
<ide> Ember.StateManager = Ember.State.extend(
<ide> }
<ide> },
<ide>
<add> /**
<add> Finds a state by its state path.
<add>
<add> Example:
<add>
<add> manager = Ember.StateManager.create({
<add> root: Ember.State.create({
<add> dashboard: Ember.State.create()
<add> })
<add> });
<add>
<add> manager.findStatesByPath(manager, "root.dashboard")
<add>
<add> // returns the dashboard state
<add>
<add> @param {Ember.State} root the state to start searching from
<add> @param {String} path the state path to follow
<add> @returns {Ember.State} the state at the end of the path
<add> */
<add> findStatesByPath: function(root, path) {
<add> var parts = path.split('.'), state = root;
<add>
<add> for (var i=0, l=parts.length; i<l; i++) {
<add> state = get(get(state, 'states'), parts[i]);
<add> }
<add>
<add> return state;
<add> },
<add>
<ide> findStatesByRoute: function(state, route) {
<ide> if (!route || route === "") { return undefined; }
<ide> var r = route.split('.'), ret = [];
<ide> Ember.StateManager = Ember.State.extend(
<ide> }).join(".");
<ide> },
<ide>
<add> urlFor: function(path, hash) {
<add> var state = this.findStatesByPath(this, path);
<add> return state.absoluteRoute(this, hash);
<add> },
<add>
<ide> transitionTo: function(name, context) {
<ide> // 1. Normalize arguments
<ide> // 2. Ensure that we are in the correct state
<ide><path>packages/ember-states/tests/routable_test.js
<ide> test("you cannot have a redirectsTo in a non-leaf state", function () {
<ide> });
<ide> });
<ide> });
<add>
<add>module("urlFor", {
<add>
<add>});
<add>
<add>test("urlFor returns an absolute route", function() {
<add> var router = Ember.Router.create({
<add> root: Ember.State.create({
<add> dashboard: Ember.State.create({
<add> route: '/dashboard'
<add> })
<add> })
<add> });
<add>
<add> var url = router.urlFor('root.dashboard');
<add> equal(url, "/dashboard");
<add>});
<add>
<add>test("urlFor supports dynamic segments", function() {
<add> var router = Ember.Router.create({
<add> root: Ember.State.create({
<add> dashboard: Ember.State.create({
<add> route: '/dashboard',
<add>
<add> posts: Ember.State.create({
<add> route: '/posts/:post_id'
<add> })
<add> })
<add> })
<add> });
<add>
<add> var url = router.urlFor('root.dashboard.posts', { post_id: 1 });
<add> equal(url, "/dashboard/posts/1");
<add>});
<add>
<add>test("urlFor supports using the current information for dynamic segments", function() {
<add> var router = Ember.Router.create({
<add> namespace: {
<add> Post: {
<add> toString: function() { return "Post"; },
<add> find: function() { return { id: 1 }; }
<add> }
<add> },
<add>
<add> root: Ember.State.create({
<add> dashboard: Ember.State.create({
<add> route: '/dashboard',
<add>
<add> posts: Ember.State.create({
<add> route: '/posts/:post_id',
<add>
<add> index: Ember.State.create({
<add> route: '/'
<add> }),
<add>
<add> manage: Ember.State.create({
<add> route: '/manage'
<add> })
<add> })
<add> })
<add> })
<add> });
<add>
<add> Ember.run(function() {
<add> router.route('/dashboard/posts/1');
<add> });
<add>
<add> var url = router.urlFor('root.dashboard.posts.manage');
<add> equal(url, '/dashboard/posts/1/manage');
<add>});
<add>
<add>test("urlFor supports merging the current information for dynamic segments", function() {
<add> var router = Ember.Router.create({
<add> namespace: {
<add> Post: {
<add> toString: function() { return "Post"; },
<add> find: function() { return { id: 1 }; }
<add> },
<add>
<add> Widget: {
<add> toString: function() { return "Widget"; },
<add> find: function() { return { id: 2 }; }
<add> }
<add> },
<add>
<add> root: Ember.State.create({
<add> dashboard: Ember.State.create({
<add> route: '/dashboard',
<add>
<add> posts: Ember.State.create({
<add> route: '/posts/:post_id',
<add>
<add> index: Ember.State.create({
<add> route: '/'
<add> }),
<add>
<add> manage: Ember.State.create({
<add> route: '/manage/:widget_id'
<add> })
<add> })
<add> })
<add> })
<add> });
<add>
<add> Ember.run(function() {
<add> router.route('/dashboard/posts/1');
<add> });
<add>
<add> var url = router.urlFor('root.dashboard.posts.manage', { widget_id: 2 });
<add> equal(url, '/dashboard/posts/1/manage/2');
<add>});
<add> | 3 |
Text | Text | remove documentation references to dockerinit | e72192be404c9a8489191d43fd6e5c429081d5c8 | <ide><path>project/PACKAGERS.md
<ide> the file "./VERSION". This binary is usually installed somewhere like
<ide>
<ide> ### Dynamic Daemon / Client-only Binary
<ide>
<del>If you are only interested in a Docker client binary, set `DOCKER_CLIENTONLY` to a non-empty value using something similar to the following: (which will prevent the extra step of compiling dockerinit)
<add>If you are only interested in a Docker client binary, set `DOCKER_CLIENTONLY` to a non-empty value using something similar to the following:
<ide>
<ide> ```bash
<ide> export DOCKER_CLIENTONLY=1
<ide> following:
<ide> This will create "./bundles/$VERSION/dynbinary/docker-$VERSION", which for
<ide> client-only builds is the important file to grab and install as appropriate.
<ide>
<del>For daemon builds, you will also need to grab and install
<del>"./bundles/$VERSION/dynbinary/dockerinit-$VERSION", which is created from the
<del>minimal set of Docker's codebase that _must_ be compiled statically (and is thus
<del>a pure static binary). The acceptable locations Docker will search for this file
<del>are as follows (in order):
<del>
<del>* as "dockerinit" in the same directory as the daemon binary (ie, if docker is
<del> installed at "/usr/bin/docker", then "/usr/bin/dockerinit" will be the first
<del> place this file is searched for)
<del>* "/usr/libexec/docker/dockerinit" or "/usr/local/libexec/docker/dockerinit"
<del> ([FHS 3.0 Draft](https://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec))
<del>* "/usr/lib/docker/dockerinit" or "/usr/local/lib/docker/dockerinit" ([FHS
<del> 2.3](https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA))
<del>
<del>If (and please, only if) one of the paths above is insufficient due to distro
<del>policy or similar issues, you may use the `DOCKER_INITPATH` environment variable
<del>at compile-time as follows to set a different path for Docker to search:
<del>
<del>```bash
<del>export DOCKER_INITPATH=/usr/lib/docker.io/dockerinit
<del>```
<del>
<del>If you find yourself needing this, please don't hesitate to reach out to Tianon
<del>to see if it would be reasonable or helpful to add more paths to Docker's list,
<del>especially if there's a relevant standard worth referencing (such as the FHS).
<del>
<del>Also, it goes without saying, but for the purposes of the daemon please consider
<del>these two binaries ("docker" and "dockerinit") as if they were a single unit.
<del>Mixing and matching can cause undesired consequences, and will fail to run
<del>properly.
<del>
<ide> ## System Dependencies
<ide>
<ide> ### Runtime Dependencies | 1 |
Javascript | Javascript | remove buildid from dynamic import urls | 337fb6a9aadb61c916f0121c899e463819cd3f33 | <ide><path>server/build/babel/plugins/handle-import.js
<ide> const buildImport = (args) => (template(`
<ide> eval('require.ensure = function (deps, callback) { callback(require) }')
<ide> require.ensure([], (require) => {
<ide> let m = require(SOURCE)
<del> m.__webpackChunkName = '${args.name}.js'
<add> m.__webpackChunkName = '${args.name}'
<ide> resolve(m);
<del> }, 'chunks/${args.name}.js');
<add> }, 'chunks/${args.name}');
<ide> })
<ide> :
<ide> new (require('next/dynamic').SameLoopPromise)((resolve, reject) => {
<ide> const buildImport = (args) => (template(`
<ide> } catch(error) {
<ide> reject(error)
<ide> }
<del> }, 'chunks/${args.name}.js');
<add> }, 'chunks/${args.name}');
<ide> })
<ide> )
<ide> `))
<ide><path>server/build/plugins/dynamic-chunks-plugin.js
<ide> import { ConcatSource } from 'webpack-sources'
<ide>
<del>const isImportChunk = /^chunks[/\\].*\.js$/
<add>const isImportChunk = /^chunks[/\\]/
<ide> const matchChunkName = /^chunks[/\\](.*)$/
<ide>
<ide> class DynamicChunkTemplatePlugin {
<ide><path>server/build/webpack.js
<ide> export default async function createCompiler (dir, { buildId, dev = false, quiet
<ide> path: buildDir ? join(buildDir, '.next') : join(dir, config.distDir),
<ide> filename: '[name]',
<ide> libraryTarget: 'commonjs2',
<del> publicPath: `/_next/${buildId}/webpack/`,
<add> publicPath: `/_next/webpack/`,
<ide> strictModuleExceptionHandling: true,
<ide> devtoolModuleFilenameTemplate ({ resourcePath }) {
<ide> const hash = createHash('sha1')
<ide> export default async function createCompiler (dir, { buildId, dev = false, quiet
<ide> return `webpack:///${resourcePath}?${id}`
<ide> },
<ide> // This saves chunks with the name given via require.ensure()
<del> chunkFilename: '[name]'
<add> chunkFilename: '[name]-[chunkhash].js'
<ide> },
<ide> resolve: {
<ide> extensions: ['.js', '.jsx', '.json'],
<ide><path>server/document.js
<ide> export class Head extends Component {
<ide>
<ide> getPreloadDynamicChunks () {
<ide> const { chunks, __NEXT_DATA__ } = this.context._documentProps
<del> let { assetPrefix, buildId } = __NEXT_DATA__
<del> return chunks.map((chunk) => (
<add> let { assetPrefix } = __NEXT_DATA__
<add> return chunks.filenames.map((chunk) => (
<ide> <link
<ide> key={chunk}
<ide> rel='preload'
<del> href={`${assetPrefix}/_next/${buildId}/webpack/chunks/${chunk}`}
<add> href={`${assetPrefix}/_next/webpack/chunks/${chunk}`}
<ide> as='script'
<ide> />
<ide> ))
<ide> export class NextScript extends Component {
<ide>
<ide> getDynamicChunks () {
<ide> const { chunks, __NEXT_DATA__ } = this.context._documentProps
<del> let { assetPrefix, buildId } = __NEXT_DATA__
<add> let { assetPrefix } = __NEXT_DATA__
<ide> return (
<ide> <Fragment>
<del> {chunks.map((chunk) => (
<add> {chunks.filenames.map((chunk) => (
<ide> <script
<ide> async
<ide> key={chunk}
<ide> type='text/javascript'
<del> src={`${assetPrefix}/_next/${buildId}/webpack/chunks/${chunk}`}
<add> src={`${assetPrefix}/_next/webpack/chunks/${chunk}`}
<ide> />
<ide> ))}
<ide> </Fragment>
<ide> export class NextScript extends Component {
<ide> const { pathname, buildId, assetPrefix } = __NEXT_DATA__
<ide> const pagePathname = getPagePathname(pathname)
<ide>
<del> __NEXT_DATA__.chunks = chunks
<add> __NEXT_DATA__.chunks = chunks.names
<ide>
<ide> return <Fragment>
<ide> {staticMarkup ? null : <script nonce={this.props.nonce} dangerouslySetInnerHTML={{
<ide><path>server/export.js
<ide> export default async function (dir, options, configuration) {
<ide> if (existsSync(join(nextDir, 'chunks'))) {
<ide> log(' copying dynamic import chunks')
<ide>
<del> await mkdirp(join(outDir, '_next', buildId, 'webpack'))
<add> await mkdirp(join(outDir, '_next', 'webpack'))
<ide> await cp(
<ide> join(nextDir, 'chunks'),
<del> join(outDir, '_next', buildId, 'webpack', 'chunks')
<add> join(outDir, '_next', 'webpack', 'chunks')
<ide> )
<ide> }
<ide>
<ide><path>server/hot-reloader.js
<ide> export default class HotReloader {
<ide> ]
<ide>
<ide> let webpackDevMiddlewareConfig = {
<del> publicPath: `/_next/${this.buildId}/webpack/`,
<add> publicPath: `/_next/webpack/`,
<ide> noInfo: true,
<ide> quiet: true,
<ide> clientLogLevel: 'warning',
<ide><path>server/index.js
<ide> export default class Server {
<ide> },
<ide>
<ide> // This is to support, webpack dynamic imports in production.
<del> '/_next/:buildId/webpack/chunks/:name': async (req, res, params) => {
<del> if (!this.handleBuildId(params.buildId, res)) {
<del> return this.send404(res)
<add> '/_next/webpack/chunks/:name': async (req, res, params) => {
<add> // Cache aggressively in production
<add> if (!this.dev) {
<add> res.setHeader('Cache-Control', 'max-age=31536000, immutable')
<ide> }
<del>
<ide> const p = join(this.dir, this.dist, 'chunks', params.name)
<ide> await this.serveStatic(req, res, p)
<ide> },
<ide>
<ide> // This is to support, webpack dynamic import support with HMR
<del> '/_next/:buildId/webpack/:id': async (req, res, params) => {
<del> if (!this.handleBuildId(params.buildId, res)) {
<del> return this.send404(res)
<del> }
<del>
<add> '/_next/webpack/:id': async (req, res, params) => {
<ide> const p = join(this.dir, this.dist, 'chunks', params.id)
<ide> await this.serveStatic(req, res, p)
<ide> },
<ide><path>server/render.js
<ide> import { join } from 'path'
<del>import { existsSync } from 'fs'
<ide> import { createElement } from 'react'
<ide> import { renderToString, renderToStaticMarkup } from 'react-dom/server'
<ide> import send from 'send'
<ide> import getConfig from './config'
<ide> import resolvePath from './resolve'
<ide> import { Router } from '../lib/router'
<ide> import { loadGetInitialProps } from '../lib/utils'
<add>import { getAvailableChunks } from './utils'
<ide> import Head, { defaultHead } from '../lib/head'
<ide> import App from '../lib/app'
<ide> import ErrorDebug from '../lib/error-debug'
<ide> async function ensurePage (page, { dir, hotReloader }) {
<ide>
<ide> function loadChunks ({ dev, dir, dist, availableChunks }) {
<ide> const flushedChunks = flushChunks()
<del> const validChunks = []
<add> const response = {
<add> names: [],
<add> filenames: []
<add> }
<add>
<add> if (dev) {
<add> availableChunks = getAvailableChunks(dir, dist)
<add> }
<ide>
<ide> for (var chunk of flushedChunks) {
<del> const filename = join(dir, dist, 'chunks', chunk)
<del> const exists = dev ? existsSync(filename) : availableChunks[chunk]
<del> if (exists) {
<del> validChunks.push(chunk)
<add> const filename = availableChunks[chunk]
<add> if (filename) {
<add> response.names.push(chunk)
<add> response.filenames.push(filename)
<ide> }
<ide> }
<ide>
<del> return validChunks
<add> return response
<ide> }
<ide><path>server/utils.js
<ide> export function getAvailableChunks (dir, dist) {
<ide>
<ide> chunkFiles.forEach(filename => {
<ide> if (/\.js$/.test(filename)) {
<del> chunksMap[filename] = true
<add> const chunkName = filename.replace(/-.*/, '')
<add> chunksMap[chunkName] = filename
<ide> }
<ide> })
<ide> | 9 |
Python | Python | matcher segfaults on particular input | 782e4814f4ef4c5dead5cd633dd07b35400636b0 | <ide><path>spacy/tests/regression/test_issue587.py
<add>import spacy
<add>import spacy.matcher
<add>
<add>import pytest
<add>
<add>@pytest.mark.models
<add>def test_matcher_segfault():
<add> nlp = spacy.load('en', parser=False, entity=False)
<add> matcher = spacy.matcher.Matcher(nlp.vocab)
<add> content = u'''a b; c'''
<add> matcher.add(entity_key='1', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}]])
<add> matcher(nlp(content))
<add> matcher.add(entity_key='2', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}, {5: True}, {65: 'c'}]])
<add> matcher(nlp(content))
<add> matcher.add(entity_key='3', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}, {5: True}, {65: 'd'}]])
<add> matcher(nlp(content)) | 1 |
Python | Python | add alert for the monitored processes list | 5c3eeba0ca663a557a1b7e9e4cbb8f260cedd525 | <ide><path>glances/glances.py
<ide> def __itemexist__(self, item_type):
<ide> return i
<ide> return -1
<ide>
<del> def add(self, item_state, item_type, item_value, proc_list=[]):
<add> def add(self, item_state, item_type, item_value, proc_list=[], proc_desc=""):
<ide> """
<ide> item_state = "OK|CAREFUL|WARNING|CRITICAL"
<del> item_type = "CPU*|LOAD|MEM"
<add> item_type = "CPU*|LOAD|MEM|MON"
<ide> item_value = value
<ide> Item is defined by:
<ide> ["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM",
<ide> MAX, AVG, MIN, SUM, COUNT,
<del> [top3 process list]]
<add> [top3 process list],
<add> "Processes description"]
<ide> If item is a 'new one':
<ide> Add the new item at the beginning of the logs list
<ide> Else:
<ide> def add(self, item_state, item_type, item_value, proc_list=[]):
<ide> # Sort TOP process by io_counters (only for Linux OS)
<ide> sortby = 'io_counters'
<ide> else:
<del> # Default TOP process sort is cpu_percent (for CPU* and LOAD)
<add> # Default TOP process sort is cpu_percent
<ide> sortby = 'cpu_percent'
<ide> topprocess = sorted(proc_list, key=lambda process: process[sortby],
<ide> reverse=True)
<ide> def add(self, item_state, item_type, item_value, proc_list=[]):
<ide> # Time is stored in Epoch format
<ide> # Epoch -> DMYHMS = datetime.fromtimestamp(epoch)
<ide> item = []
<add> # START DATE
<ide> item.append(time.mktime(datetime.now().timetuple()))
<add> # END DATE
<ide> item.append(-1)
<ide> item.append(item_state) # STATE: WARNING|CRITICAL
<ide> item.append(item_type) # TYPE: CPU, LOAD, MEM...
<ide> def add(self, item_state, item_type, item_value, proc_list=[]):
<ide> item.append(item_value) # SUM
<ide> item.append(1) # COUNT
<ide> item.append(topprocess[0:3]) # TOP 3 PROCESS LIST
<add> item.append(proc_desc) # MONITORED PROCESSES DESC
<ide> self.logs_list.insert(0, item)
<ide> if self.len() > self.logs_max:
<ide> self.logs_list.pop()
<ide> def add(self, item_state, item_type, item_value, proc_list=[]):
<ide> self.logs_list[item_index][8])
<ide> # TOP PROCESS LIST
<ide> self.logs_list[item_index][9] = topprocess[0:3]
<add> # MONITORED PROCESSES DESC
<add> self.logs_list[item_index][10] = proc_desc
<ide>
<ide> return self.len()
<ide>
<ide> def displayLog(self, offset_y=0):
<ide> min(offset_y - 3, screen_y - self.log_y,
<ide> logs.len()))
<ide> logtodisplay_count = min(screen_y - self.log_y - 3, logs.len())
<del> logmsg = _("WARNING|CRITICAL logs for CPU|LOAD|MEM")
<add> logmsg = _("WARNING|CRITICAL logs")
<ide> if logtodisplay_count > 1:
<ide> logmsg += (_(" (lasts ") + str(logtodisplay_count) +
<ide> _(" entries)"))
<ide> def displayLog(self, offset_y=0):
<ide> logmsg += " {0} ({1:.1f}/{2:.1f}/{3:.1f})".format(
<ide> log[logcount][3], log[logcount][6],
<ide> log[logcount][5], log[logcount][4])
<del> # Add top process
<del> if log[logcount][9] != []:
<add> # Add the monitored process description
<add> if log[logcount][10] != "":
<add> logmsg += " - {0}".format(log[logcount][10])
<add> elif log[logcount][9] != []:
<add> # Add top processes
<ide> log_proc_name = log[logcount][9][0]['name']
<ide> logmsg += " - Top process: {0}".format(log_proc_name)
<ide> # Display the log
<ide> def displayProcess(self, processcount, processlist,
<ide> monitormsg2 = "{0}".format(cmdret)
<ide> self.term_window.addnstr(monitor_y, self.process_x + 35,
<ide> monitormsg2, screen_x - process_x - 35)
<del> # else:
<del> # monitormsg2 = "Min: {0} Current: {1} Max: {2} processes".format(
<del> # monitors.countmin(item), len(monitoredlist), monitors.countmax(item))
<del> # self.term_window.addnstr(monitor_y, self.process_x + 35,
<del> # monitormsg2, screen_x - process_x - 35)
<ide>
<add> # Generate log
<add> logs.add(self.__getMonitoredAlert(len(monitoredlist),
<add> monitors.countmin(item),
<add> monitors.countmax(item)),
<add> "MON_" + str(item + 1),
<add> len(monitoredlist),
<add> proc_list = monitoredlist,
<add> proc_desc = monitors.description(item))
<add>
<add> # Next...
<ide> item += 1
<ide>
<ide> #***************** | 1 |
Ruby | Ruby | use new migration style in habtm join table | d64e0955d04a40355e312ca4ee57b2c9a8e248cc | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def belongs_to(name, options = {})
<ide> # join table with a migration such as this:
<ide> #
<ide> # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
<del> # def self.up
<add> # def change
<ide> # create_table :developers_projects, :id => false do |t|
<ide> # t.integer :developer_id
<ide> # t.integer :project_id
<ide> # end
<ide> # end
<del> #
<del> # def self.down
<del> # drop_table :developers_projects
<del> # end
<ide> # end
<ide> #
<ide> # Adds the following methods for retrieval and query: | 1 |
Javascript | Javascript | fix bad wording in pointer events doc | 56c40baa06fc98a69e5193022310072b7a842416 | <ide><path>Libraries/Components/View/View.js
<ide> const View = React.createClass({
<ide> * - 'auto': The View can be the target of touch events.
<ide> * - 'none': The View is never the target of touch events.
<ide> * - 'box-none': The View is never the target of touch events but it's
<del> * subviews can be. It behaves like if the following classes
<add> * subviews can be. It behaves like if the view had the following classes
<ide> * in CSS:
<ide> * ```
<ide> * .box-none {
<ide> const View = React.createClass({
<ide> * }
<ide> * ```
<ide> * - 'box-only': The view can be the target of touch events but it's
<del> * subviews cannot be. It behaves like if the following classes
<add> * subviews cannot be. It behaves like if the view had the following classes
<ide> * in CSS:
<ide> * ```
<ide> * .box-only { | 1 |
Python | Python | break long line | 5345ed1fef98af2ee1253633134f6df47f3a7e04 | <ide><path>numpy/add_newdocs.py
<ide>
<ide> add_newdoc('numpy.core.multiarray','fromfile',
<ide> """fromfile(file=, dtype=float, count=-1, sep='')
<del>
<add>
<ide> Return an array of the given data type from a text or binary file.
<del>
<add>
<ide> Data written using the tofile() method can be conveniently recovered using
<ide> this function.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> file : file or string
<ide> See also
<ide> --------
<ide> loadtxt : load data from text files
<del>
<add>
<ide> Notes
<ide> -----
<ide> WARNING: This function should be used sparingly as the binary files are not
<ide> platform independent. In particular, they contain no endianess or datatype
<ide> information. Nevertheless it can be useful for reading in simply formatted
<ide> or binary data quickly.
<del>
<add>
<ide> """)
<ide>
<ide> add_newdoc('numpy.core.multiarray','frombuffer',
<ide> """frombuffer(buffer=, dtype=float, count=-1, offset=0)
<del>
<add>
<ide> Returns a 1-d array of data type dtype from buffer.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> buffer
<ide> Number of items to read. -1 means all data in the buffer.
<ide> offset : int
<ide> Number of bytes to jump from the start of the buffer before reading
<del>
<add>
<ide> Notes
<ide> -----
<ide> If the buffer has data that is not in machine byte-order, then
<ide> use a proper data type descriptor. The data will not be
<ide> byteswapped, but the array will manage it in future operations.
<del>
<add>
<ide> """)
<ide>
<ide> add_newdoc('numpy.core.multiarray','concatenate',
<ide> keys : (k,N) array or tuple of (N,) sequences
<ide> Array containing values that the returned indices should sort, or
<ide> a sequence of things that can be converted to arrays of the same shape.
<del>
<add>
<ide> axis : integer
<ide> Axis to be indirectly sorted. Default is -1 (i.e. last axis).
<ide>
<ide> out : {None, array}, optional
<ide> Array into which the result can be placed. Its type is preserved
<ide> and it must be of the right shape to hold the output.
<del>
<add>
<ide> See Also
<ide> --------
<ide> all : equivalent function
<ide> """a.any(axis=None, out=None)
<ide>
<ide> Check if any of the elements of `a` are true.
<del>
<add>
<ide> Performs a logical_or over the given axis and returns the result
<ide>
<ide> Parameters
<ide> out : {None, array}, optional
<ide> Array into which the result can be placed. Its type is preserved
<ide> and it must be of the right shape to hold the output.
<del>
<add>
<ide> See Also
<ide> --------
<ide> any : equivalent function
<ide> ============ ======= ============= ============ ========
<ide> kind speed worst case work space stable
<ide> ============ ======= ============= ============ ========
<del> 'quicksort' 1 O(n^2) 0 no
<del> 'mergesort' 2 O(n*log(n)) ~n/2 yes
<del> 'heapsort' 3 O(n*log(n)) 0 no
<add> 'quicksort' 1 O(n^2) 0 no
<add> 'mergesort' 2 O(n*log(n)) ~n/2 yes
<add> 'heapsort' 3 O(n*log(n)) 0 no
<ide> ============ ======= ============= ============ ========
<ide>
<ide> All the sort algorithms make temporary copies of the data when the
<ide> array([20, 31, 12, 3])
<ide> >>> a.choose(choices, mode='wrap')
<ide> array([20, 1, 12, 3])
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('clip',
<ide> """a.clip(a_min, a_max, out=None)
<ide>
<ide> Return an array whose values are limited to [a_min, a_max].
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> a_min
<ide> clipped_array : array
<ide> A new array whose elements are same as for a, but values
<ide> < a_min are replaced with a_min, and > a_max with a_max.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> [3]])
<ide> >>> a.compress([0,1,1])
<ide> array([2, 3])
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('conj',
<ide> """a.conj()
<ide>
<ide> Return an array with all complex-valued elements conjugated.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate',
<ide> """a.conjugate()
<ide>
<ide> Return an array with all complex-valued elements conjugated.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> If order is 'Fortran' (True) then the result has fortran order.
<ide> If order is 'Any' (None) then the result has fortran order
<ide> only if the array already is in fortran order.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('dump',
<ide> """a.dump(file)
<del>
<add>
<ide> Dump a pickle of the array to the specified file.
<ide> The array can be read back with pickle.load or numpy.load.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> file : str
<ide> A string naming the dump file.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> Returns the pickle of the array as a string.
<ide> pickle.loads or numpy.loads will convert the string back to an array.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('fill',
<ide> """a.fill(value)
<del>
<add>
<ide> Fill the array with a scalar value.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',
<ide> """a.flatten([order])
<del>
<add>
<ide> Return a 1-d array (always copy)
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> order : {'C', 'F'}
<ide> Whether to flatten in C or Fortran order.
<del>
<add>
<ide> Notes
<ide> -----
<ide> a.flatten('F') == a.T.flatten('C')
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> amax : array_like
<ide> New array holding the result.
<ide> If ``out`` was specified, ``out`` is returned.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> """a.newbyteorder(byteorder)
<ide>
<ide> Equivalent to a.view(a.dtype.newbytorder(byteorder))
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero',
<ide> """a.nonzero()
<del>
<add>
<ide> Returns a tuple of arrays, one for each dimension of a, containing
<ide> the indices of the non-zero elements in that dimension. The
<ide> corresponding non-zero values can be obtained with::
<del>
<add>
<ide> a[a.nonzero()].
<ide>
<ide> To group the indices by element, rather than dimension, use::
<del>
<add>
<ide> transpose(a.nonzero())
<ide>
<ide> instead. The result of this is always a 2d array, with a row for
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp',
<ide> """a.ptp(axis=None, out=None)
<del>
<add>
<ide> Return (maximum - minimum) along the the given dimension
<ide> (i.e. peak-to-peak value).
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> axis : {None, int}, optional
<ide> Alternative output array in which to place the result. It must
<ide> have the same shape and buffer length as the expected output
<ide> but the type will be cast if necessary.
<del>
<add>
<ide> Returns
<ide> -------
<ide> ptp : ndarray.
<ide> A new array holding the result, unless ``out`` was
<ide> specified, in which case a reference to ``out`` is returned.
<del>
<add>
<ide> Examples
<ide> --------
<ide> >>> x = np.arange(4).reshape((2,2))
<ide> array([2, 2])
<ide> >>> x.ptp(1)
<ide> array([1, 1])
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> Set a.flat[n] = values[n] for all n in indices.
<ide> If values is shorter than indices, it will repeat.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> indices : array_like
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'putmask',
<ide> """putmask(a, mask, values)
<del>
<add>
<ide> Sets a.flat[n] = values[n] for each n where mask.flat[n] is true.
<del>
<add>
<ide> If values is not the same size as `a` and `mask` then it will repeat.
<ide> This gives behavior different from a[mask] = values.
<ide>
<ide> Boolean mask array
<ide> values : {array_like}
<ide> Values to put
<add>
<ide> """)
<ide>
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat',
<ide> """a.repeat(repeats, axis=None)
<del>
<add>
<ide> Repeat elements of an array.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> a : {array_like}
<ide> -------
<ide> reshaped_array : array
<ide> A new view to the array.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('round',
<ide> """a.round(decimals=0, out=None)
<del>
<add>
<ide> Return an array rounded a to the given number of decimals.
<ide>
<ide> The real and imaginary parts of complex numbers are rounded separately. The
<ide> array([ 1, 2, 3, 11])
<ide> >>> x.round(decimals=-1)
<ide> array([ 0, 0, 0, 10])
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> -----
<ide> The array a must be 1-d and is assumed to be sorted in ascending order.
<ide> Searchsorted uses binary search to find the required insertion points.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide> sort keeps items with the same key in the same relative order. The three
<ide> available algorithms have the following properties:
<ide>
<del> =========== ======= ============= ============ =======
<add> =========== ======= ============= ============ =======
<ide> kind speed worst case work space stable
<del> =========== ======= ============= ============ =======
<del> 'quicksort' 1 O(n^2) 0 no
<del> 'mergesort' 2 O(n*log(n)) ~n/2 yes
<del> 'heapsort' 3 O(n*log(n)) 0 no
<del> =========== ======= ============= ============ =======
<add> =========== ======= ============= ============ =======
<add> 'quicksort' 1 O(n^2) 0 no
<add> 'mergesort' 2 O(n*log(n)) ~n/2 yes
<add> 'heapsort' 3 O(n*log(n)) 0 no
<add> =========== ======= ============= ============ =======
<ide>
<ide> All the sort algorithms make temporary copies of the data when the sort is
<ide> not along the last axis. Consequently, sorts along the last axis are faster
<ide> Notes
<ide> -----
<ide> The standard deviation is the square root of the average of the squared
<del> deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)).
<del> The computed standard deviation is computed by dividing by the number of
<del> elements, N-ddof. The option ddof defaults to zero, that is, a
<del> biased estimate. Note that for complex numbers std takes the absolute
<del> value before squaring, so that the result is always real and nonnegative.
<add> deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)). The
<add> computed standard deviation is computed by dividing by the number of
<add> elements, N-ddof. The option ddof defaults to zero, that is, a biased
<add> estimate. Note that for complex numbers std takes the absolute value before
<add> squaring, so that the result is always real and nonnegative.
<ide>
<ide> """))
<ide>
<ide> """a.sum(axis=None, dtype=None, out=None)
<ide>
<ide> Return the sum of the array elements over the given axis
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> axis : {None, integer}
<ide> Axis over which the sum is taken. If None is used, then the sum is
<ide> over all the array elements.
<ide> dtype : {None, dtype}, optional
<del> Determines the type of the returned array and of the accumulator
<del> where the elements are summed. If dtype has the value None and the
<del> type of a is an integer type of precision less than the default
<del> platform integer, then the default platform integer precision is
<del> used. Otherwise, the dtype is the same as that of a.
<add> Determines the type of the returned array and of the accumulator where
<add> the elements are summed. If dtype has the value None and the type of a
<add> is an integer type of precision less than the default platform integer,
<add> then the default platform integer precision is used. Otherwise, the
<add> dtype is the same as that of a.
<ide> out : {None, array}, optional
<del> Array into which the sum can be placed. Its type is preserved and
<del> it must be of the right shape to hold the output.
<add> Array into which the sum can be placed. Its type is preserved and it
<add> must be of the right shape to hold the output.
<ide>
<ide> Returns
<ide> -------
<ide> sum_along_axis : {array, scalar}, see dtype parameter above.
<del> Returns an array whose shape is the same as a with the specified
<del> axis removed. Returns a 0d array when a is 1d or axis=None.
<del> Returns a reference to the specified output array if specified.
<add> Returns an array whose shape is the same as a with the specified axis
<add> removed. Returns a 0d array when a is 1d or axis=None. Returns a
<add> reference to the specified output array if specified.
<ide>
<ide> See Also
<ide> --------
<ide> See Also
<ide> --------
<ide> take : equivalent function
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> This is a convenience function for quick storage of array data.
<ide> Information on endianess and precision is lost, so this method is not a
<del> good choice for files intended to archive data or transport data
<del> between machines with different endianess. Some of these problems can
<del> be overcome by outputting the data as text files at the expense of
<del> speed and file size.
<add> good choice for files intended to archive data or transport data between
<add> machines with different endianess. Some of these problems can be overcome
<add> by outputting the data as text files at the expense of speed and file size.
<ide>
<ide> Parameters
<ide> ----------
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist',
<ide> """a.tolist()
<del>
<add>
<ide> Return the array as nested lists.
<ide>
<ide> Copy the data portion of the array to a hierarchical Python list and return
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring',
<ide> """a.tostring(order='C')
<del>
<add>
<ide> Construct a Python string containing the raw data bytes in the array.
<del>
<add>
<ide> Parameters
<ide> ----------
<ide> order : {'C', 'F', None}
<ide> Order of the data for multidimensional arrays:
<ide> C, Fortran, or the same as for the original array.
<del>
<add>
<ide> """))
<ide>
<ide>
<ide>
<ide> Return the sum along diagonals of the array.
<ide>
<del> If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the
<del> collection of elements of the form a[i,i+offset]. If a has more than two
<del> dimensions, then the axes specified by axis1 and axis2 are used to determine
<del> the 2-d subarray whose trace is returned. The shape of the resulting
<del> array can be determined by removing axis1 and axis2 and appending an index
<del> to the right equal to the size of the resulting diagonals.
<add> If a is 2-d, returns the sum along the diagonal of self with the given
<add> offset, i.e., the collection of elements of the form a[i,i+offset]. If a
<add> has more than two dimensions, then the axes specified by axis1 and axis2
<add> are used to determine the 2-d subarray whose trace is returned. The shape
<add> of the resulting array can be determined by removing axis1 and axis2 and
<add> appending an index to the right equal to the size of the resulting
<add> diagonals.
<ide>
<ide> Parameters
<ide> ----------
<ide> """))
<ide>
<ide> add_newdoc('numpy.core.umath','geterrobj',
<del> """geterrobj()
<add> """geterrobj()
<ide>
<del> Used internally by `geterr`.
<add> Used internally by `geterr`.
<ide>
<del> Returns
<del> -------
<del> errobj : list
<del> Internal numpy buffer size, error mask, error callback function.
<add> Returns
<add> -------
<add> errobj : list
<add> Internal numpy buffer size, error mask, error callback function.
<ide>
<del> """)
<add> """)
<ide>
<ide> add_newdoc('numpy.core.umath','seterrobj',
<del> """seterrobj()
<add> """seterrobj()
<ide>
<del> Used internally by `seterr`.
<add> Used internally by `seterr`.
<ide>
<del> Parameters
<del> ----------
<del> errobj : list
<del> [buffer_size, error_mask, callback_func]
<add> Parameters
<add> ----------
<add> errobj : list
<add> [buffer_size, error_mask, callback_func]
<ide>
<del> See Also
<del> --------
<del> seterrcall
<add> See Also
<add> --------
<add> seterrcall
<ide>
<del> """)
<add> """)
<ide>
<del>add_newdoc("numpy.core","ufunc","""Optimized functions make it possible to implement arithmetic with arrays efficiently
<add>add_newdoc("numpy.core","ufunc",
<add> """Functions that operate element by element on whole arrays.
<ide>
<del>Unary ufuncs:
<del>=============
<add> Unary ufuncs:
<add> =============
<ide>
<del>op(X, out=None)
<del>Apply op to X elementwise
<add> op(X, out=None)
<add> Apply op to X elementwise
<ide>
<del>Parameters
<del>----------
<del>X : array-like
<del>out : array-like
<del> An array to store the output. Must be the same shape as X.
<add> Parameters
<add> ----------
<add> X : array-like
<add> out : array-like
<add> An array to store the output. Must be the same shape as X.
<ide>
<del>Returns
<del>-------
<del>r : array-like
<del> r will have the same shape as X; if out is provided, r will be
<del> equal to out.
<add> Returns
<add> -------
<add> r : array-like
<add> r will have the same shape as X; if out is provided, r will be
<add> equal to out.
<ide>
<del>Binary ufuncs:
<del>==============
<add> Binary ufuncs:
<add> ==============
<ide>
<del>op(X, Y, out=None)
<del>Apply op to X and Y elementwise. May "broadcast" to make
<del>the shapes of X and Y congruent.
<add> op(X, Y, out=None)
<add> Apply op to X and Y elementwise. May "broadcast" to make
<add> the shapes of X and Y congruent.
<ide>
<del>The broadcasting rules are:
<del>* Dimensions of length 1 may be prepended to either array
<del>* Arrays may be repeated along dimensions of length 1
<add> The broadcasting rules are:
<add> * Dimensions of length 1 may be prepended to either array
<add> * Arrays may be repeated along dimensions of length 1
<ide>
<del>Parameters
<del>----------
<del>X : array-like
<del>Y : array-like
<del>out : array-like
<del> An array to store the output. Must be the same shape as the
<del> output would have.
<add> Parameters
<add> ----------
<add> X : array-like
<add> Y : array-like
<add> out : array-like
<add> An array to store the output. Must be the same shape as the
<add> output would have.
<ide>
<del>Returns
<del>-------
<del>r : array-like
<del> The return value; if out is provided, r will be equal to out.
<del>""")
<del>add_newdoc("numpy.core","ufunc",
<del> [("reduce","""reduce(array,axis=0,dtype=None,out=None)
<del>reduce applies the operator to all elements of the array producing
<del>a single result.
<del>
<del>For a one-dimensional array, reduce produces results equivalent to:
<del>r = op.identity
<del>for i in xrange(len(A)):
<del> r = op(r,A[i])
<del>return r
<del>
<del>For example, add.reduce() is equivalent to sum().
<del>
<del>Parameters:
<del>-----------
<del>
<del>array : array-like
<del> The array to act on.
<del>axis : integer
<del> The axis along which to apply the reduction.
<del>dtype : data type or None
<del> The type used to represent the intermediate results. Defaults
<del> to the data type of the output array if this is provided, or
<del> the data type of the input array if no output array is provided.
<del>out : array-like or None
<del> A location into which the result is stored. If not provided a
<del> freshly-allocated array is returned.
<del>
<del>Returns:
<del>--------
<add> Returns
<add> -------
<add> r : array-like
<add> The return value; if out is provided, r will be equal to out.
<ide>
<del>r : array
<del> The reduced values. If out was supplied, r is equal to out.
<add> """)
<ide>
<del>Example:
<del>--------
<del>>>> np.multiply.reduce([2,3,5])
<del>30
<ide>
<add>add_newdoc("numpy.core","ufunc",("reduce",
<add> """reduce(array,axis=0,dtype=None,out=None)
<ide>
<del>"""),
<del> ("accumulate","""accumulate(array,axis=None,dtype=None,out=None)
<del>accumulate applies the operator to all elements of the array producing
<del>cumulative results.
<del>
<del>For a one-dimensional array, accumulate produces results equivalent to:
<del>r = np.empty(len(A))
<del>t = op.identity
<del>for i in xrange(len(A)):
<del> t = op(t,A[i])
<del> r[i] = t
<del>return r
<del>
<del>For example, add.accumulate() is equivalent to cumsum().
<del>
<del>Parameters:
<del>-----------
<del>
<del>array : array-like
<del> The array to act on.
<del>axis : integer
<del> The axis along which to apply the accumulation.
<del>dtype : data type or None
<del> The type used to represent the intermediate results. Defaults
<del> to the data type of the output array if this is provided, or
<del> the data type of the input array if no output array is provided.
<del>out : array-like or None
<del> A location into which the result is stored. If not provided a
<del> freshly-allocated array is returned.
<del>
<del>Returns:
<del>--------
<add> Reduce applies the operator to all elements of the array producing
<add> a single result.
<ide>
<del>r : array
<del> The accumulated values. If out was supplied, r is equal to out.
<add> For a one-dimensional array, reduce produces results equivalent to:
<add> r = op.identity
<add> for i in xrange(len(A)):
<add> r = op(r,A[i])
<add> return r
<ide>
<del>Example:
<del>--------
<del>>>> np.multiply.accumulate([2,3,5])
<del>array([2,6,30])
<add> For example, add.reduce() is equivalent to sum().
<ide>
<del>"""),
<del> ("reduceat","""reduceat(self,array,indices,axis=None,dtype=None,out=None)
<del>reduceat performs a reduce over an axis using the indices as a guide
<del>
<del>op.reduceat(array,indices) computes
<del>op.reduce(array[indices[i]:indices[i+1]])
<del>for i=0..end with an implicit indices[i+1]=len(array)
<del>assumed when i=end-1
<del>
<del>if indices[i+1] <= indices[i]+1
<del>then the result is array[indices[i]] for that value
<del>
<del>op.accumulate(array) is the same as
<del>op.reduceat(array,indices)[::2]
<del>where indices is range(len(array)-1) with a zero placed
<del>in every other sample:
<del>indices = zeros(len(array)*2-1)
<del>indices[1::2] = range(1,len(array))
<del>
<del>output shape is based on the size of indices
<del>
<del>Parameters:
<del>-----------
<del>
<del>array : array-like
<del> The array to act on.
<del>indices : array-like
<del> Indices specifying ranges to reduce.
<del>axis : integer
<del> The axis along which to apply the reduceat.
<del>dtype : data type or None
<del> The type used to represent the intermediate results. Defaults
<del> to the data type of the output array if this is provided, or
<del> the data type of the input array if no output array is provided.
<del>out : array-like or None
<del> A location into which the result is stored. If not provided a
<del> freshly-allocated array is returned.
<del>
<del>Returns:
<del>--------
<add> Parameters:
<add> -----------
<ide>
<del>r : array
<del> The reduced values. If out was supplied, r is equal to out.
<add> array : array-like
<add> The array to act on.
<add> axis : integer
<add> The axis along which to apply the reduction.
<add> dtype : data type or None
<add> The type used to represent the intermediate results. Defaults
<add> to the data type of the output array if this is provided, or
<add> the data type of the input array if no output array is provided.
<add> out : array-like or None
<add> A location into which the result is stored. If not provided a
<add> freshly-allocated array is returned.
<add>
<add> Returns:
<add> --------
<ide>
<del>Example:
<del>--------
<del>To take the running sum of four successive values:
<del>>>> np.multiply.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
<del>array([ 6, 10, 14, 18])
<add> r : array
<add> The reduced values. If out was supplied, r is equal to out.
<ide>
<del>"""),
<del> ("outer","""outer(A,B)
<del>Compute the result of applying op to all pairs (a,b)
<add> Example:
<add> --------
<add> >>> np.multiply.reduce([2,3,5])
<add> 30
<add>
<add> """))
<ide>
<del>op.outer(A,B) is equivalent to
<del>op(A[:,:,...,:,newaxis,...,newaxis]*B[newaxis,...,newaxis,:,...,:])
<del>where A has B.ndim new axes appended and B has A.ndim new axes prepended.
<add>add_newdoc("numpy.core","ufunc",("accumulate",
<add> """accumulate(array,axis=None,dtype=None,out=None)
<ide>
<del>For A and B one-dimensional, this is equivalent to
<del>r = empty(len(A),len(B))
<del>for i in xrange(len(A)):
<del> for j in xrange(len(B)):
<del> r[i,j] = A[i]*B[j]
<del>If A and B are higher-dimensional, the result has dimension A.ndim+B.ndim
<add> Accumulate applies the operator to all elements of the array producing
<add> cumulative results.
<ide>
<del>Parameters:
<del>-----------
<add> For a one-dimensional array, accumulate produces results equivalent to:
<add> r = np.empty(len(A))
<add> t = op.identity
<add> for i in xrange(len(A)):
<add> t = op(t,A[i])
<add> r[i] = t
<add> return r
<ide>
<del>A : array-like
<del>B : array-like
<add> For example, add.accumulate() is equivalent to cumsum().
<ide>
<del>Returns:
<del>--------
<add> Parameters:
<add> -----------
<ide>
<del>r : array
<del>Example:
<del>--------
<del>>>> np.multiply.outer([1,2,3],[4,5,6])
<del>array([[ 4, 5, 6],
<del> [ 8, 10, 12],
<del> [12, 15, 18]])
<add> array : array-like
<add> The array to act on.
<add> axis : integer
<add> The axis along which to apply the accumulation.
<add> dtype : data type or None
<add> The type used to represent the intermediate results. Defaults
<add> to the data type of the output array if this is provided, or
<add> the data type of the input array if no output array is provided.
<add> out : array-like or None
<add> A location into which the result is stored. If not provided a
<add> freshly-allocated array is returned.
<add>
<add> Returns:
<add> --------
<add>
<add> r : array
<add> The accumulated values. If out was supplied, r is equal to out.
<add>
<add> Example:
<add> --------
<add> >>> np.multiply.accumulate([2,3,5])
<add> array([2,6,30])
<add>
<add> """))
<add>
<add>add_newdoc("numpy.core","ufunc",("reduceat",
<add> """reduceat(self,array,indices,axis=None,dtype=None,out=None)
<add>
<add> Reduceat performs a reduce over an axis using the indices as a guide
<add>
<add> op.reduceat(array,indices) computes
<add> op.reduce(array[indices[i]:indices[i+1]])
<add> for i=0..end with an implicit indices[i+1]=len(array)
<add> assumed when i=end-1
<add>
<add> if indices[i+1] <= indices[i]+1
<add> then the result is array[indices[i]] for that value
<add>
<add> op.accumulate(array) is the same as
<add> op.reduceat(array,indices)[::2]
<add> where indices is range(len(array)-1) with a zero placed
<add> in every other sample:
<add> indices = zeros(len(array)*2-1)
<add> indices[1::2] = range(1,len(array))
<add>
<add> output shape is based on the size of indices
<add>
<add> Parameters:
<add> -----------
<add>
<add> array : array-like
<add> The array to act on.
<add> indices : array-like
<add> Indices specifying ranges to reduce.
<add> axis : integer
<add> The axis along which to apply the reduceat.
<add> dtype : data type or None
<add> The type used to represent the intermediate results. Defaults
<add> to the data type of the output array if this is provided, or
<add> the data type of the input array if no output array is provided.
<add> out : array-like or None
<add> A location into which the result is stored. If not provided a
<add> freshly-allocated array is returned.
<add>
<add> Returns:
<add> --------
<add>
<add> r : array
<add> The reduced values. If out was supplied, r is equal to out.
<add>
<add> Example:
<add> --------
<add> To take the running sum of four successive values:
<add> >>> np.multiply.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
<add> array([ 6, 10, 14, 18])
<add>
<add> """))
<add>
<add>add_newdoc("numpy.core","ufunc",("outer",
<add> """outer(A,B)
<add>
<add> Compute the result of applying op to all pairs (a,b)
<add>
<add> op.outer(A,B) is equivalent to
<add> op(A[:,:,...,:,newaxis,...,newaxis]*B[newaxis,...,newaxis,:,...,:])
<add> where A has B.ndim new axes appended and B has A.ndim new axes prepended.
<add>
<add> For A and B one-dimensional, this is equivalent to
<add> r = empty(len(A),len(B))
<add> for i in xrange(len(A)):
<add> for j in xrange(len(B)):
<add> r[i,j] = A[i]*B[j]
<add> If A and B are higher-dimensional, the result has dimension A.ndim+B.ndim
<add>
<add> Parameters:
<add> -----------
<add>
<add> A : array-like
<add> B : array-like
<add>
<add> Returns:
<add> --------
<add>
<add> r : array
<add> Example:
<add> --------
<add> >>> np.multiply.outer([1,2,3],[4,5,6])
<add> array([[ 4, 5, 6],
<add> [ 8, 10, 12],
<add> [12, 15, 18]])
<add>
<add> """))
<ide>
<del>""")]) | 1 |
Ruby | Ruby | add documentation to messageverifier | 9fd4fbd1fb74f1eafed456875e39164ae0f6d7c8 | <ide><path>activesupport/lib/active_support/message_verifier.rb
<ide> def initialize(secret, options = {})
<ide> @serializer = options[:serializer] || Marshal
<ide> end
<ide>
<del> # FIXME: Document this method
<add> # Checks if a signed message could have been generated by signing an object
<add> # with the +MessageVerifier+'s secret.
<add> #
<add> # verifier = ActiveSupport::MessageVerifier.new 's3Krit'
<add> # signed_message = verifier.generate 'a private message'
<add> # verifier.valid_message?(signed_message) # => true
<add> #
<add> # tampered_message = signed_message.chop # editing the message invalidates the signature
<add> # verifier.valid_message?(tampered_message) # => false
<ide> def valid_message?(signed_message)
<ide> return if signed_message.blank?
<ide>
<ide> data, digest = signed_message.split("--")
<ide> data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))
<ide> end
<ide>
<del> # FIXME: Document this method
<add> # Decodes the signed message using the +MessageVerifier+'s secret.
<add> #
<add> # verifier = ActiveSupport::MessageVerifier.new 's3Krit'
<add> #
<add> # signed_message = verifier.generate 'a private message'
<add> # verifier.verified(signed_message) #=> 'a private message'
<add> #
<add> # Returns +nil+ if the message was not signed with the same secret.
<add> #
<add> # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit'
<add> # other_verifier.verified(signed_message) #=> nil
<add> #
<add> # Returns +nil+ if the message is not Base64-encoded.
<add> #
<add> # invalid_message = "f--46a0120593880c733a53b6dad75b42ddc1c8996d"
<add> # verifier.verified(invalid_message) #=> nil
<add> #
<add> # Raises any error raised while decoding the signed message.
<add> #
<add> # incompatible_message = "test--dad7b06c94abba8d46a15fafaef56c327665d5ff"
<add> # verifier.verified(incompatible_message) #=> TypeError: incompatible marshal file format
<add> #
<ide> def verified(signed_message)
<ide> if valid_message?(signed_message)
<ide> begin
<ide> def verified(signed_message)
<ide> end
<ide> end
<ide>
<del> # FIXME: Document this method
<add> # Decodes the signed message using the +MessageVerifier+'s secret.
<add> #
<add> # verifier = ActiveSupport::MessageVerifier.new 's3Krit'
<add> # signed_message = verifier.generate 'a private message'
<add> #
<add> # verifier.verify(signed_message) #=> 'a private message'
<add> #
<add> # Raises +InvalidSignature+ if the message was not signed with the same
<add> # secret or was not Base64-encoded.
<add> #
<add> # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit'
<add> # other_verifier.verified(signed_message) #=> ActiveSupport::MessageVerifier::InvalidSignature
<ide> def verify(signed_message)
<ide> verified(signed_message) || raise(InvalidSignature)
<ide> end
<ide>
<del> # FIXME: Document this method
<add> # Generates a signed message for the provided value.
<add> #
<add> # The message is signed with the +MessageVerifier+'s secret. Without knowing
<add> # the secret, the original value cannot be extracted from the message.
<add> #
<add> # verifier = ActiveSupport::MessageVerifier.new 's3Krit'
<add> # verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772"
<ide> def generate(value)
<ide> data = encode(@serializer.dump(value))
<ide> "#{data}--#{generate_digest(data)}" | 1 |
Mixed | Ruby | fix typo of duplicated `the` [ci skip] | 7217179d1e03ab3d6ece4f3aa19fe29af2a496da | <ide><path>activerecord/lib/active_record/database_configurations.rb
<ide> def initialize(configurations = {})
<ide> # configs for all environments.
<ide> # <tt>spec_name:</tt> The specification name (ie primary, animals, etc.). Defaults
<ide> # to +nil+.
<del> # <tt>include_replicas:</tt> Determines whether to include replicas in the
<add> # <tt>include_replicas:</tt> Determines whether to include replicas in
<ide> # the returned list. Most of the time we're only iterating over the write
<ide> # connection (i.e. migrations don't need to run for the write and read connection).
<ide> # Defaults to +false+.
<ide><path>guides/source/i18n.md
<ide> For several reasons the Simple backend shipped with Active Support only does the
<ide>
<ide> That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs, by passing a backend instance to the `I18n.backend=` setter.
<ide>
<del>For example, you can replace the Simple backend with the the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends.
<add>For example, you can replace the Simple backend with the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends.
<ide>
<ide> With the Chain backend, you could use the Active Record backend and fall back to the (default) Simple backend:
<ide> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.