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
add link to latest cdn versions
e69a66fdcd02fe33a95ab0cb65ee7e8dd4b860d6
<ide><path>guide/english/css/css-frameworks/css-framework-foundation/index.md <ide> Here is a simple HTML template which includes the latest compiled and minified C <ide> </html> <ide> ``` <ide> <del>This example makes use of a CDN that loads the default settings. If you'd like to customize the grid layout, change the colors or add and remove components you can do so on the Foundation [download](http://foundation.zurb.com/sites/download/) page. <add>This example makes use of a CDN that loads the default settings. (You can always find the latest versions at [cdnjs.com](https://cdnjs.com/libraries/foundation)) If you'd like to customize the grid layout, change the colors or add and remove components you can do so on the Foundation [download](http://foundation.zurb.com/sites/download/) page. <ide> <ide> #### Learning Resources <ide>
1
Javascript
Javascript
fix the spellings
08892fc0c488a4205f2880acda250af4a922aa51
<ide><path>lib/_stream_duplex.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> // a duplex stream is just a stream that is both readable and writable. <del>// Since JS doesn't have multiple prototypal inheritance, this class <del>// prototypally inherits from Readable, and then parasitically from <add>// Since JS doesn't have multiple prototype inheritance, this class <add>// prototypically inherits from Readable, and then parasitically from <ide> // Writable. <ide> <ide> 'use strict';
1
Ruby
Ruby
remove deprecated method "table#primary_key"
ec083687a96af1f35f9fb9e75611cc4bf4f5bf81
<ide><path>lib/arel/table.rb <ide> def initialize name, engine = Table.engine <ide> @columns = nil <ide> @aliases = [] <ide> @table_alias = nil <del> @primary_key = nil <ide> <ide> if Hash === engine <ide> @engine = engine[:engine] || Table.engine <ide> def initialize name, engine = Table.engine <ide> end <ide> end <ide> <del> def primary_key <del> if $VERBOSE <del> warn <<-eowarn <del>primary_key (#{caller.first}) is deprecated and will be removed in Arel 4.0.0 <del> eowarn <del> end <del> @primary_key ||= begin <del> primary_key_name = @engine.connection.primary_key(name) <del> # some tables might be without primary key <del> primary_key_name && self[primary_key_name] <del> end <del> end <del> <ide> def alias name = "#{self.name}_2" <ide> Nodes::TableAlias.new(self, name).tap do |node| <ide> @aliases << node <ide><path>lib/arel/visitors/mssql.rb <ide> module Visitors <ide> class MSSQL < Arel::Visitors::ToSql <ide> RowNumber = Struct.new :children <ide> <add> def initialize(*) <add> @primary_keys = {} <add> super <add> end <add> <ide> private <ide> <ide> # `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate <ide> def select_count? x <ide> end <ide> <ide> # FIXME raise exception of there is no pk? <del> # FIXME!! Table.primary_key will be deprecated. What is the replacement?? <ide> def find_left_table_pk o <del> return o.primary_key if o.instance_of? Arel::Table <del> find_left_table_pk o.left if o.kind_of? Arel::Nodes::Join <add> if o.kind_of?(Arel::Nodes::Join) <add> find_left_table_pk(o.left) <add> elsif o.instance_of?(Arel::Table) <add> find_primary_key(o) <add> end <add> end <add> <add> def find_primary_key(o) <add> @primary_keys[o.name] ||= begin <add> primary_key_name = @connection.primary_key(o.name) <add> # some tables might be without primary key <add> primary_key_name && o[primary_key_name] <add> end <ide> end <ide> end <ide> end <ide><path>test/visitors/test_mssql.rb <ide> def compile node <ide> sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY \"users\".\"id\") as _row_num FROM \"users\") as _t WHERE _row_num BETWEEN 1 AND 10" <ide> end <ide> <add> it 'caches the PK lookup for order' do <add> connection = MiniTest::Mock.new <add> connection.expect(:primary_key, ["id"], ["users"]) <add> <add> # We don't care how many times these methods are called <add> def connection.quote_table_name(*); ""; end <add> def connection.quote_column_name(*); ""; end <add> <add> @visitor = MSSQL.new(connection) <add> stmt = Nodes::SelectStatement.new <add> stmt.cores.first.from = @table <add> stmt.limit = Nodes::Limit.new(10) <add> <add> compile(stmt) <add> compile(stmt) <add> <add> connection.verify <add> end <add> <ide> it 'should go over query ORDER BY if .order()' do <ide> stmt = Nodes::SelectStatement.new <ide> stmt.limit = Nodes::Limit.new(10)
3
Text
Text
remove legacy `-j` test.py option from building.md
85a77b0cbf7913697bbfae56d17aa9b25894f10e
<ide><path>BUILDING.md <ide> You can execute the entire suite of tests for a given subsystem <ide> by providing the name of a subsystem: <ide> <ide> ```text <del>$ tools/test.py -J child-process <add>$ tools/test.py child-process <ide> ``` <ide> <ide> You can also execute the tests in a tests directory (such as `test/message`): <ide> <ide> ```text <del>$ tools/test.py -J test/message <add>$ tools/test.py test/message <ide> ``` <ide> <ide> If you want to check the other options, please refer to the help by using
1
Ruby
Ruby
fix streaming downloads from s3/azure storage
86938c495e282e6a61c16a9e1d77582e22c0a4fc
<ide><path>activestorage/lib/active_storage/service/azure_storage_service.rb <ide> def upload(key, io, checksum: nil) <ide> end <ide> end <ide> <del> def download(key) <add> def download(key, &block) <ide> if block_given? <ide> instrument :streaming_download, key do <ide> stream(key, &block) <ide> def format_expiry(expires_in) <ide> end <ide> <ide> # Reads the object for the given key in chunks, yielding each to the block. <del> def stream(key, options = {}, &block) <add> def stream(key) <ide> blob = blob_for(key) <ide> <ide> chunk_size = 5.megabytes <ide> offset = 0 <ide> <ide> while offset < blob.properties[:content_length] <del> _, io = blobs.get_blob(container, key, start_range: offset, end_range: offset + chunk_size - 1) <del> yield io <add> _, chunk = blobs.get_blob(container, key, start_range: offset, end_range: offset + chunk_size - 1) <add> yield chunk.force_encoding(Encoding::BINARY) <ide> offset += chunk_size <ide> end <ide> end <ide><path>activestorage/lib/active_storage/service/s3_service.rb <ide> def upload(key, io, checksum: nil) <ide> end <ide> end <ide> <del> def download(key) <add> def download(key, &block) <ide> if block_given? <ide> instrument :streaming_download, key do <ide> stream(key, &block) <ide> def object_for(key) <ide> end <ide> <ide> # Reads the object for the given key in chunks, yielding each to the block. <del> def stream(key, options = {}, &block) <add> def stream(key, &block) <ide> object = object_for(key) <ide> <ide> chunk_size = 5.megabytes <ide> offset = 0 <ide> <ide> while offset < object.content_length <del> yield object.read(options.merge(range: "bytes=#{offset}-#{offset + chunk_size - 1}")) <add> yield object.get(range: "bytes=#{offset}-#{offset + chunk_size - 1}").body.read.force_encoding(Encoding::BINARY) <ide> offset += chunk_size <ide> end <ide> end <ide><path>activestorage/test/service/shared_service_tests.rb <ide> module ActiveStorage::Service::SharedServiceTests <ide> assert_equal FIXTURE_DATA, @service.download(FIXTURE_KEY) <ide> end <ide> <add> test "downloading in chunks" do <add> chunks = [] <add> <add> @service.download(FIXTURE_KEY) do |chunk| <add> chunks << chunk <add> end <add> <add> assert_equal [ FIXTURE_DATA ], chunks <add> end <add> <ide> test "existing" do <ide> assert @service.exist?(FIXTURE_KEY) <ide> assert_not @service.exist?(FIXTURE_KEY + "nonsense")
3
Ruby
Ruby
add api docs for run_load_hooks
6a71188f9ce8f6a353fb3ce40dfadc5c1acb5260
<ide><path>activesupport/lib/active_support/lazy_load_hooks.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveSupport <del> # lazy_load_hooks allows Rails to lazily load a lot of components and thus <add> # LazyLoadHooks allows Rails to lazily load a lot of components and thus <ide> # making the app boot faster. Because of this feature now there is no need to <ide> # require <tt>ActiveRecord::Base</tt> at boot time purely to apply <ide> # configuration. Instead a hook is registered that applies configuration once <ide> # <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is <ide> # used as example but this feature can be applied elsewhere too. <ide> # <del> # Here is an example where +on_load+ method is called to register a hook. <add> # Here is an example where on_load method is called to register a hook. <ide> # <ide> # initializer 'active_record.initialize_timezone' do <ide> # ActiveSupport.on_load(:active_record) do <ide> module ActiveSupport <ide> # end <ide> # <ide> # When the entirety of +ActiveRecord::Base+ has been <del> # evaluated then +run_load_hooks+ is invoked. The very last line of <add> # evaluated then run_load_hooks is invoked. The very last line of <ide> # +ActiveRecord::Base+ is: <ide> # <ide> # ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) <add> # <add> # run_load_hooks will then execute all the hooks that were registered <add> # with the on_load method. In the case of the above example, it will <add> # execute the block of code that is in the +initializer+. <ide> module LazyLoadHooks <ide> def self.extended(base) # :nodoc: <ide> base.class_eval do <ide> def on_load(name, options = {}, &block) <ide> @load_hooks[name] << [block, options] <ide> end <ide> <add> # Executes all blocks registered to +name+ via on_load, using +base+ as the <add> # evaluation context. <add> # <add> # ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) <add> # <add> # In the case of the above example, it will execute all hooks registered <add> # for +:active_record+ within the class +ActiveRecord::Base+. <ide> def run_load_hooks(name, base = Object) <ide> @loaded[name] << base <ide> @load_hooks[name].each do |hook, options|
1
Ruby
Ruby
remove any resource logic from respond_to
7a4a679dbada2e1fcfc28db8c47dd32e03afc1af
<ide><path>actionpack/lib/action_controller/base/mime_responds.rb <ide> def clear_respond_to <ide> # Be sure to check respond_with and respond_to documentation for more examples. <ide> # <ide> def respond_to(*mimes, &block) <del> options = mimes.extract_options! <ide> raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given? <ide> <del> resource = options.delete(:with) <ide> responder = Responder.new <del> <ide> mimes = collect_mimes_from_class_level if mimes.empty? <ide> mimes.each { |mime| responder.send(mime) } <ide> block.call(responder) if block_given? <ide> <ide> if format = request.negotiate_mime(responder.order) <del> respond_to_block_or_template_or_resource(format, resource, <del> options, &responder.response_for(format)) <add> self.formats = [format.to_sym] <add> <add> if response = responder.response_for(format) <add> response.call <add> else <add> default_render <add> end <ide> else <ide> head :not_acceptable <ide> end <ide> def respond_to(*mimes, &block) <ide> # end <ide> # <ide> def respond_with(resource, options={}, &block) <del> respond_to(options.merge!(:with => resource), &block) <del> end <del> <del> protected <del> <del> def respond_to_block_or_template_or_resource(format, resource, options) <del> self.formats = [format.to_sym] <del> return yield if block_given? <del> <ide> begin <del> default_render <add> respond_to(&block) <ide> rescue ActionView::MissingTemplate => e <del> if resource && resource.respond_to?(:"to_#{format.to_sym}") <del> render options.merge(format.to_sym => resource) <add> format = self.formats.first <add> <add> if resource.respond_to?(:"to_#{format}") <add> render options.merge(format => resource) <ide> else <ide> raise e <ide> end <ide> end <ide> end <ide> <add> protected <add> <ide> # Collect mimes declared in the class method respond_to valid for the <ide> # current action. <ide> #
1
Text
Text
add playsimple games to "who uses apache airflow?"
8986e7582c746f4f4f0f38308f196f292e5f3c22
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [Pernod-Ricard](https://www.pernod-ricard.com/) [[@romain-nio](https://github.com/romain-nio)] <ide> 1. [Plaid](https://www.plaid.com/) [[@plaid](https://github.com/plaid), [@AustinBGibbons](https://github.com/AustinBGibbons) & [@jeeyoungk](https://github.com/jeeyoungk)] <ide> 1. [Playbuzz](https://www.playbuzz.com/) [[@clintonboys](https://github.com/clintonboys) & [@dbn](https://github.com/dbn)] <add>1. [Playsimple Games](https://playsimple.in/) [[@joshi95](https://github.com/joshi95)] <ide> 1. [PMC](https://pmc.com/) [[@andrewm4894](https://github.com/andrewm4894)] <ide> 1. [Polidea](https://www.polidea.com/) [[@potiuk](https://github.com/potiuk), [@mschickensoup](https://github.com/mschickensoup), [@mik-laj](https://github.com/mik-laj), [@turbaszek](https://github.com/turbaszek), [@michalslowikowski00](https://github.com/michalslowikowski00), [@olchas](https://github.com/olchas)], [@debek](https://github.com/debek) <ide> 1. [Poshmark](https://www.poshmark.com)
1
PHP
PHP
add coverage for comma in email alias
d97cf79545b6fedf84de84a3f9f26f9e31a073d1
<ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testAddresses() { <ide> $this->CakeEmail->replyTo('[email protected]', 'ReplyTo CakePHP'); <ide> $this->CakeEmail->readReceipt('[email protected]', 'ReadReceipt CakePHP'); <ide> $this->CakeEmail->returnPath('[email protected]', 'ReturnPath CakePHP'); <del> $this->CakeEmail->to('[email protected]', 'To CakePHP'); <add> $this->CakeEmail->to('[email protected]', 'To, CakePHP'); <ide> $this->CakeEmail->cc('[email protected]', 'Cc CakePHP'); <ide> $this->CakeEmail->bcc('[email protected]', 'Bcc CakePHP'); <ide> $this->CakeEmail->addTo('[email protected]', 'To2 CakePHP'); <ide> public function testAddresses() { <ide> $this->assertSame($this->CakeEmail->replyTo(), array('[email protected]' => 'ReplyTo CakePHP')); <ide> $this->assertSame($this->CakeEmail->readReceipt(), array('[email protected]' => 'ReadReceipt CakePHP')); <ide> $this->assertSame($this->CakeEmail->returnPath(), array('[email protected]' => 'ReturnPath CakePHP')); <del> $this->assertSame($this->CakeEmail->to(), array('[email protected]' => 'To CakePHP', '[email protected]' => 'To2 CakePHP')); <add> $this->assertSame($this->CakeEmail->to(), array('[email protected]' => 'To, CakePHP', '[email protected]' => 'To2 CakePHP')); <ide> $this->assertSame($this->CakeEmail->cc(), array('[email protected]' => 'Cc CakePHP', '[email protected]' => 'Cc2 CakePHP')); <ide> $this->assertSame($this->CakeEmail->bcc(), array('[email protected]' => 'Bcc CakePHP', '[email protected]' => 'Bcc2 CakePHP')); <ide> <ide> public function testAddresses() { <ide> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <[email protected]>'); <ide> $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP <[email protected]>'); <ide> $this->assertSame($headers['Return-Path'], 'ReturnPath CakePHP <[email protected]>'); <del> $this->assertSame($headers['To'], 'To CakePHP <[email protected]>, To2 CakePHP <[email protected]>'); <add> $this->assertSame($headers['To'], '"To, CakePHP" <[email protected]>, To2 CakePHP <[email protected]>'); <ide> $this->assertSame($headers['Cc'], 'Cc CakePHP <[email protected]>, Cc2 CakePHP <[email protected]>'); <ide> $this->assertSame($headers['Bcc'], 'Bcc CakePHP <[email protected]>, Bcc2 CakePHP <[email protected]>'); <ide> }
1
Text
Text
add an example
14a20147c66d5535fcbc28e7ca0e3033600796e9
<ide><path>docs/upgrading/upgrading-your-package.md <ide> class CommandPaletteView extends SelectListView <ide> @panel?.hide() <ide> ``` <ide> <del>See the [SelectListView docs][SelectListView] for all the options. <add>See the [SelectListView docs][SelectListView] for all the options. And check out the [conversion of CommandPaletteView][selectlistview-example] as a real-world example. <ide> <ide> ## Specs <ide> <ide> TODO: come up with patterns for converting away from using `workspaceView` and ` <ide> [texteditorview]:https://github.com/atom/atom-space-pen-views#texteditorview <ide> [scrollview]:https://github.com/atom/atom-space-pen-views#scrollview <ide> [selectlistview]:https://github.com/atom/atom-space-pen-views#selectlistview <add>[selectlistview-example]:https://github.com/atom/command-palette/pull/19/files
1
Javascript
Javascript
follow gltfloader api for parse()
87245cb81f80266dd66df4c4e41df1501f8d4d0a
<ide><path>examples/js/loaders/LDrawLoader.js <ide> THREE.LDrawLoader = ( function () { <ide> <ide> }, <ide> <del> parse: function ( text, onParsed ) { <add> parse: function ( text, path, onLoad ) { <ide> <ide> // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter <ide> <del> this.processObject( text, onProcessed, null, "" ); <add> this.processObject( text, onLoad, null, path ); <ide> <ide> }, <ide>
1
Python
Python
fix bug in platform detection
c81c7fa511502337f97b5190ab96910b31b68c54
<ide><path>numpy/random/setup.py <ide> def generate_libraries(ext, build_dir): <ide> elif not is_msvc: <ide> # Some bit generators require c99 <ide> EXTRA_COMPILE_ARGS += ['-std=c99'] <del> INTEL_LIKE = any([val in k.lower() for k in platform.uname() <del> for val in ('x86', 'i686', 'i386', 'amd64')]) <add> INTEL_LIKE = any(arch in platform.machine() <add> for arch in ('x86', 'i686', 'i386', 'amd64')) <ide> if INTEL_LIKE: <ide> # Assumes GCC or GCC-like compiler <ide> EXTRA_COMPILE_ARGS += ['-msse2']
1
Python
Python
raise error if passed a serializer instance
7a0416c50bfd663b5690c563d7448f2a10d414d3
<ide><path>rest_framework/response.py <ide> from django.utils import six <ide> from django.utils.six.moves.http_client import responses <ide> <add>from rest_framework.serializers import Serializer <add> <ide> <ide> class Response(SimpleTemplateResponse): <ide> """ <ide> def __init__(self, data=None, status=None, <ide> For example being set automatically by the `APIView`. <ide> """ <ide> super(Response, self).__init__(None, status=status) <add> <add> if isinstance(data, Serializer): <add> msg = ( <add> 'You passed a Serializer instance as data, but ' <add> 'probably meant to pass serialized `.data` or ' <add> '`.error`. representation.' <add> ) <add> raise AssertionError(msg) <add> <ide> self.data = data <ide> self.template_name = template_name <ide> self.exception = exception
1
Ruby
Ruby
generalize file recognition
ea593cf61cf376ffb44f7c825c8734c79cff6850
<ide><path>Library/Homebrew/patches.rb <add>require 'stringio' <add> <ide> class Patches <ide> include Enumerable <ide> <ide> def initialize patch_p, filename, url <ide> @compression = nil <ide> @url = nil <ide> <del> if url.kind_of? File # true when DATA is passed <add> if url.kind_of? IO or url.kind_of? StringIO <add> # File-like objects. Most common when DATA is passed. <ide> write_data url <ide> elsif looks_like_url(url) <ide> @url = url # Save URL to mark this as an external patch
1
Python
Python
make dev data optional
53cf2f1c0ed1adb5b14c23ebc05142e4b50dac70
<ide><path>spacy/cli/train.py <ide> def train(language, output_dir, train_data, dev_data, n_iter, tagger, parser, ner): <ide> output_path = Path(output_dir) <ide> train_path = Path(train_data) <del> dev_path = Path(dev_data) <add> dev_path = Path(dev_data) if dev_data else None <ide> check_dirs(output_path, data_path, dev_path) <ide> <ide> lang = util.get_lang_class(language) <ide> def train(language, output_dir, train_data, dev_data, n_iter, tagger, parser, ne <ide> parser_cfg['features'] = lang.Defaults.parser_features <ide> entity_cfg['features'] = lang.Defaults.entity_features <ide> gold_train = list(read_gold_json(train_path)) <del> gold_dev = list(read_gold_json(dev_path)) <add> gold_dev = list(read_gold_json(dev_path)) if dev_path else None <ide> <ide> train_model(lang, gold_train, gold_dev, output_path, tagger_cfg, parser_cfg, <ide> entity_cfg, n_iter) <del> scorer = evaluate(lang, list(read_gold_json(dev_loc)), output_path) <del> print_results(scorer) <add> if gold_dev: <add> scorer = evaluate(lang, gold_dev, output_path) <add> print_results(scorer) <ide> <ide> <ide> def train_config(config): <ide> def train_model(Language, train_data, dev_data, output_path, tagger_cfg, parser_ <ide> for itn, epoch in enumerate(trainer.epochs(n_iter, augment_data=None)): <ide> for doc, gold in epoch: <ide> trainer.update(doc, gold) <del> dev_scores = trainer.evaluate(dev_data) <add> dev_scores = trainer.evaluate(dev_data) if dev_data else [] <ide> print_progress(itn, trainer.nlp.parser.model.nr_weight, <ide> trainer.nlp.parser.model.nr_active_feat, <ide> **dev_scores.scores) <ide> def evaluate(Language, gold_tuples, output_path): <ide> def check_dirs(input_path, train_path, dev_path): <ide> if not output_path.exists(): <ide> util.sys_exit(output_path.as_posix(), title="Output directory not found") <del> if not train_path.exists() and train_path.is_file(): <add> if not train_path.exists() or not train_path.is_file(): <ide> util.sys_exit(train_path.as_posix(), title="Training data not found") <add> if dev_path and not dev_path.exists(): <add> util.sys_exit(dev_path.as_posix(), title="Development data not found") <ide> <ide> <ide> def print_progress(itn, nr_weight, nr_active_feat, **scores):
1
Go
Go
use request factory for registry ping
55f0ca94e57fc8ec26a79061d04ddd3aeaecb94b
<ide><path>registry/endpoint.go <ide> import ( <ide> <ide> log "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/registry/v2" <add> "github.com/docker/docker/utils" <ide> ) <ide> <ide> // for mocking in unit tests <ide> func (e *Endpoint) Path(path string) string { <ide> <ide> func (e *Endpoint) Ping() (RegistryInfo, error) { <ide> // The ping logic to use is determined by the registry endpoint version. <add> factory := HTTPRequestFactory(nil) <ide> switch e.Version { <ide> case APIVersion1: <del> return e.pingV1() <add> return e.pingV1(factory) <ide> case APIVersion2: <del> return e.pingV2() <add> return e.pingV2(factory) <ide> } <ide> <ide> // APIVersionUnknown <ide> // We should try v2 first... <ide> e.Version = APIVersion2 <del> regInfo, errV2 := e.pingV2() <add> regInfo, errV2 := e.pingV2(factory) <ide> if errV2 == nil { <ide> return regInfo, nil <ide> } <ide> <ide> // ... then fallback to v1. <ide> e.Version = APIVersion1 <del> regInfo, errV1 := e.pingV1() <add> regInfo, errV1 := e.pingV1(factory) <ide> if errV1 == nil { <ide> return regInfo, nil <ide> } <ide> func (e *Endpoint) Ping() (RegistryInfo, error) { <ide> return RegistryInfo{}, fmt.Errorf("unable to ping registry endpoint %s\nv2 ping attempt failed with error: %s\n v1 ping attempt failed with error: %s", e, errV2, errV1) <ide> } <ide> <del>func (e *Endpoint) pingV1() (RegistryInfo, error) { <add>func (e *Endpoint) pingV1(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { <ide> log.Debugf("attempting v1 ping for registry endpoint %s", e) <ide> <ide> if e.String() == IndexServerAddress() { <ide> func (e *Endpoint) pingV1() (RegistryInfo, error) { <ide> return RegistryInfo{Standalone: false}, nil <ide> } <ide> <del> req, err := http.NewRequest("GET", e.Path("_ping"), nil) <add> req, err := factory.NewRequest("GET", e.Path("_ping"), nil) <ide> if err != nil { <ide> return RegistryInfo{Standalone: false}, err <ide> } <ide> func (e *Endpoint) pingV1() (RegistryInfo, error) { <ide> return info, nil <ide> } <ide> <del>func (e *Endpoint) pingV2() (RegistryInfo, error) { <add>func (e *Endpoint) pingV2(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { <ide> log.Debugf("attempting v2 ping for registry endpoint %s", e) <ide> <del> req, err := http.NewRequest("GET", e.Path(""), nil) <add> req, err := factory.NewRequest("GET", e.Path(""), nil) <ide> if err != nil { <ide> return RegistryInfo{}, err <ide> }
1
Go
Go
ignore sigurg on all platforms
05f520dd3cf6730ca53910ada5fc24791ab2ead0
<ide><path>pkg/signal/signal.go <ide> import ( <ide> ) <ide> <ide> // CatchAll catches all signals and relays them to the specified channel. <del>// On Linux, SIGURG is not handled, as it's used by the Go runtime to support <add>// SIGURG is not handled, as it's used by the Go runtime to support <ide> // preemptable system calls. <ide> func CatchAll(sigc chan os.Signal) { <ide> var handledSigs []os.Signal <del> for _, s := range SignalMap { <del> if isRuntimeSig(s) { <del> // Do not handle SIGURG on Linux, as in go1.14+, the go runtime issues <add> for n, s := range SignalMap { <add> if n == "URG" { <add> // Do not handle SIGURG, as in go1.14+, the go runtime issues <ide> // SIGURG as an interrupt to support preemptable system calls on Linux. <ide> continue <ide> } <ide><path>pkg/signal/signal_darwin.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> <ide> import ( <del> "os" <ide> "syscall" <ide> ) <ide> <ide> var SignalMap = map[string]syscall.Signal{ <ide> "XCPU": syscall.SIGXCPU, <ide> "XFSZ": syscall.SIGXFSZ, <ide> } <del> <del>func isRuntimeSig(_ os.Signal) bool { <del> return false <del>} <ide><path>pkg/signal/signal_freebsd.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> <ide> import ( <del> "os" <ide> "syscall" <ide> ) <ide> <ide> var SignalMap = map[string]syscall.Signal{ <ide> "XCPU": syscall.SIGXCPU, <ide> "XFSZ": syscall.SIGXFSZ, <ide> } <del> <del>func isRuntimeSig(_ os.Signal) bool { <del> return false <del>} <ide><path>pkg/signal/signal_linux.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> <ide> import ( <del> "os" <ide> "syscall" <ide> <ide> "golang.org/x/sys/unix" <ide> var SignalMap = map[string]syscall.Signal{ <ide> "RTMAX-1": sigrtmax - 1, <ide> "RTMAX": sigrtmax, <ide> } <del> <del>func isRuntimeSig(s os.Signal) bool { <del> return s == unix.SIGURG <del>} <ide><path>pkg/signal/signal_linux_mipsx.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> <ide> import ( <del> "os" <ide> "syscall" <ide> <ide> "golang.org/x/sys/unix" <ide> var SignalMap = map[string]syscall.Signal{ <ide> "RTMAX-1": sigrtmax - 1, <ide> "RTMAX": sigrtmax, <ide> } <del> <del>func isRuntimeSig(s os.Signal) bool { <del> return s == unix.SIGURG <del>} <ide><path>pkg/signal/signal_windows.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> <ide> import ( <del> "os" <ide> "syscall" <ide> ) <ide> <ide> var SignalMap = map[string]syscall.Signal{ <ide> "KILL": syscall.SIGKILL, <ide> "TERM": syscall.SIGTERM, <ide> } <del> <del>func isRuntimeSig(_ os.Signal) bool { <del> return false <del>}
6
PHP
PHP
pass the table instance into createtablesql
7aea6200ac05b0bf949ec094a4947086ffbfa3a1
<ide><path>lib/Cake/Database/Schema/MysqlSchema.php <ide> public function extraSchemaColumns() { <ide> /** <ide> * Generate the SQL to create a table. <ide> * <del> * @param string $table The name of the table. <add> * @param Table $table Table instance <ide> * @param array $columns The columns to go inside the table. <ide> * @param array $constraints The constraints for the table. <ide> * @param array $indexes The indexes for the table. <ide> * @return array A complete CREATE TABLE statement(s) <ide> */ <ide> public function createTableSql($table, $columns, $constraints, $indexes) { <ide> $content = implode(",\n", array_merge($columns, $constraints, $indexes)); <del> return [sprintf("CREATE TABLE `%s` (\n%s\n);", $table, $content)]; <add> return [sprintf("CREATE TABLE `%s` (\n%s\n)", $table->name(), $content)]; <ide> } <ide> <ide> /** <ide><path>lib/Cake/Database/Schema/SqliteSchema.php <ide> public function indexSql(Table $table, $name) { <ide> /** <ide> * Generate the SQL to create a table. <ide> * <del> * @param string $table The name of the table. <add> * @param Table $table Table instance <ide> * @param array $columns The columns to go inside the table. <ide> * @param array $constraints The constraints for the table. <ide> * @param array $indexes The indexes for the table. <ide> public function indexSql(Table $table, $name) { <ide> public function createTableSql($table, $columns, $constraints, $indexes) { <ide> $lines = array_merge($columns, $constraints); <ide> $content = implode(",\n", array_filter($lines)); <del> $table = sprintf("CREATE TABLE \"%s\" (\n%s\n);", $table, $content); <add> $table = sprintf("CREATE TABLE \"%s\" (\n%s\n)", $table->name(), $content); <ide> $out = [$table]; <ide> foreach ($indexes as $index) { <del> $out[] = $index . ";"; <add> $out[] = $index; <ide> } <ide> return $out; <ide> } <ide><path>lib/Cake/Database/Schema/Table.php <ide> public function constraint($name) { <ide> */ <ide> public function createTableSql(Connection $connection) { <ide> $dialect = $connection->driver()->schemaDialect(); <del> $lines = $constraints = $indexes = []; <add> $columns = $constraints = $indexes = []; <ide> foreach (array_keys($this->_columns) as $name) { <del> $lines[] = $dialect->columnSql($this, $name); <add> $columns[] = $dialect->columnSql($this, $name); <ide> } <ide> foreach (array_keys($this->_constraints) as $name) { <ide> $constraints[] = $dialect->constraintSql($this, $name); <ide> } <ide> foreach (array_keys($this->_indexes) as $name) { <ide> $indexes[] = $dialect->indexSql($this, $name); <ide> } <del> return $dialect->createTableSql($this->_table, $lines, $constraints, $indexes); <add> return $dialect->createTableSql($this, $columns, $constraints, $indexes); <ide> } <ide> <ide> } <ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testCreateTableSql() { <ide> `body` TEXT, <ide> `created` DATETIME, <ide> PRIMARY KEY (`id`) <del>); <add>) <ide> SQL; <ide> $result = $table->createTableSql($connection); <ide> $this->assertCount(1, $result); <ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testCreateTableSql() { <ide> "title" VARCHAR NOT NULL, <ide> "body" TEXT, <ide> "created" DATETIME <del>); <add>) <ide> SQL; <ide> $result = $table->createTableSql($connection); <ide> $this->assertCount(2, $result); <ide> $this->assertEquals($expected, $result[0]); <ide> $this->assertEquals( <del> 'CREATE INDEX "title_idx" ON "articles" ("title");', <add> 'CREATE INDEX "title_idx" ON "articles" ("title")', <ide> $result[1] <ide> ); <ide> }
5
Python
Python
add norwegian lemmatizer and tag_map
b9b3a40c78b28c5222e3d6b25da915d8dcddd438
<ide><path>spacy/lang/nb/__init__.py <ide> <ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS <ide> from ..norm_exceptions import BASE_NORMS <add>from .lemmatizer import LOOKUP <add>from .tag_map import TAG_MAP <ide> from ...language import Language <ide> from ...attrs import LANG, NORM <ide> from ...util import update_exc, add_lookups <ide> class NorwegianDefaults(Language.Defaults): <ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS) <ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) <ide> stop_words = STOP_WORDS <add> tag_map = TAG_MAP <add> lemma_lookup = LOOKUP <ide> <ide> <ide> class Norwegian(Language): <ide><path>spacy/lang/nb/lemmatizer.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>LOOKUP = { <add>'a':'a', <add>'aabakken':'aabakken', <add>'aabakkens':'aabakkens', <add>'aarbakke':'aarbakke', <add>'aarum':'aarum', <add>'aase':'aase', <add>'ab':'ab', <add>'abitanti':'abitanti', <add>'abitazione':'abitazione', <add>'ablegøyer':'ablegøyer', <add>'absolutt':'absolutt', <add>'absorberes':'absorberes', <add>'ad':'ad', <add>'adgang':'adgang', <add>'adgangen':'adgangen', <add>'adkomst':'adkomst', <add>'adkomstdokument':'adkomstdokument', <add>'adkomstdokumenter':'adkomstdokumenter', <add>'adkomsten':'adkomsten', <add>'adlyde':'adlyde', <add>'adlyder':'adlyder', <add>'adm':'adm', <add>'administrasjon':'administrasjon', <add>'administrasjonen':'administrasjonen', <add>'administrasjonsdepartementet':'administrasjonsdepartementet', <add>'administrasjonskostnadene':'administrasjonskostnadene', <add>'administrativ':'administrativ', <add>'administrative':'administrative', <add>'administrativt':'administrativt', <add>'administrere':'administrere', <add>'administrerende':'administrerende', <add>'administreres':'administreres', <add>'administrert':'administrert', <add>'adopsjon':'adopsjon', <add>'adopsjonspenger':'adopsjonspenger', <add>'adresse':'adresse', <add>'adresser':'adresser', <add>'adskillelse':'adskillelse', <add>'adskilt':'adskilt', <add>'advare':'advare', <add>'advarselen':'advarselen', <add>'advart':'advart', <add>'advokat':'advokat', <add>'advokatar':'advokatar', <add>'advokatfirmaet':'advokatfirmaet', <add>'advokatfullmektig':'advokatfullmektig', <add>'agder':'agder', <add>'agenter':'agenter', <add>'agenturer':'agenturer', <add>'aggregeres':'aggregeres', <add>'aggregert':'aggregert', <add>'agn':'agn', <add>'agnar':'agnar', <add>'agreement':'agreement', <add>'ajourføring':'ajourføring', <add>'akademikerne':'akademikerne', <add>'akademikernes':'akademikernes', <add>'ake':'ake', <add>'akershus':'akershus', <add>'akkord':'akkord', <add>'akkumulerte':'akkumulerte', <add>'akkurat':'akkurat', <add>'aksept':'aksept', <add>'akseptabel':'akseptabel', <add>'akseptabelt':'akseptabelt', <add>'akseptable':'akseptable', <add>'aksepterast':'aksepterast', <add>'akseptere':'akseptere', <add>'aksepteres':'aksepteres', <add>'akseptert':'akseptert', <add>'aksjane':'aksjane', <add>'aksjar':'aksjar', <add>'aksje':'aksje', <add>'aksjeandel':'aksjeandel', <add>'aksjeavkastning':'aksjeavkastning', <add>'aksjebrev':'aksjebrev', <add>'aksjebustader':'aksjebustader', <add>'aksjeeigar':'aksjeeigar', <add>'aksjeeigarane':'aksjeeigarane', <add>'aksjeeigarar':'aksjeeigarar', <add>'aksjeeigaravtale':'aksjeeigaravtale', <add>'aksjeeigaren':'aksjeeigaren', <add>'aksjegevinster':'aksjegevinster', <add>'aksjeinnskot':'aksjeinnskot', <add>'aksjekapital':'aksjekapital', <add>'aksjekapitalen':'aksjekapitalen', <add>'aksjelov':'aksjelov', <add>'aksjelova':'aksjelova', <add>'aksjeloven':'aksjeloven', <add>'aksjelovens':'aksjelovens', <add>'aksjelovgjeving':'aksjelovgjeving', <add>'aksjelovgjevinga':'aksjelovgjevinga', <add>'aksjer':'aksjer', <add>'aksjerettslig':'aksjerettslig', <add>'aksjeselskap':'aksjeselskap', <add>'aksjeselskaper':'aksjeselskaper', <add>'aksjeselskapet':'aksjeselskapet', <add>'aksjeselskapsformen':'aksjeselskapsformen', <add>'aksjeselskapsrettslege':'aksjeselskapsrettslege', <add>'aksjonær':'aksjonær', <add>'aksjonæroppgaver':'aksjonæroppgaver', <add>'aktersetet':'aktersetet', <add>'aktes':'aktes', <add>'aktiv':'aktiv', <add>'aktiva':'aktiva', <add>'aktivaklasser':'aktivaklasser', <add>'aktivasammensetning':'aktivasammensetning', <add>'aktive':'aktive', <add>'aktivitet':'aktivitet', <add>'aktivitetane':'aktivitetane', <add>'aktivitetar':'aktivitetar', <add>'aktiviteten':'aktiviteten', <add>'aktivitetene':'aktivitetene', <add>'aktiviteter':'aktiviteter', <add>'aktivitetsøkning':'aktivitetsøkning', <add>'aktivt':'aktivt', <add>'aktlaust':'aktlaust', <add>'aktløyse':'aktløyse', <add>'aktsemd':'aktsemd', <add>'aktsemdplikta':'aktsemdplikta', <add>'aktualisere':'aktualisere', <add>'aktuar':'aktuar', <add>'aktuell':'aktuell', <add>'aktuelle':'aktuelle', <add>'aktuelt':'aktuelt', <add>'aktør':'aktør', <add>'aktørane':'aktørane', <add>'aktørar':'aktørar', <add>'aktørene':'aktørene', <add>'aktørenes':'aktørenes', <add>'aktørens':'aktørens', <add>'aktører':'aktører', <add>'aktørers':'aktørers', <add>'aktørgruppe':'aktørgruppe', <add>'aku':'aku', <add>'alarmsignalet':'alarmsignalet', <add>'aldeles':'aldeles', <add>'alder':'alder', <add>'alderdom':'alderdom', <add>'alderdommen':'alderdommen', <add>'alderen':'alderen', <add>'alderkilde':'alderkilde', <add>'alderpensjonen':'alderpensjonen', <add>'alderpensjonskapital':'alderpensjonskapital', <add>'alders':'alders', <add>'aldersdifferanse':'aldersdifferanse', <add>'aldersforskjellen':'aldersforskjellen', <add>'aldersgrense':'aldersgrense', <add>'aldersgrensen':'aldersgrensen', <add>'aldersgrensene':'aldersgrensene', <add>'aldersgrupper':'aldersgrupper', <add>'alderspensjon':'alderspensjon', <add>'alderspensjonen':'alderspensjonen', <add>'alderspensjoner':'alderspensjoner', <add>'alderspensjonist':'alderspensjonist', <add>'alderspensjonistene':'alderspensjonistene', <add>'alderspensjonister':'alderspensjonister', <add>'alderspensjonsforsikring':'alderspensjonsforsikring', <add>'alderspensjonsforsikringen':'alderspensjonsforsikringen', <add>} <ide><path>spacy/lang/nb/punctuation.py <add># coding: utf8 <add>"""Punctuation stolen from Danish""" <add>from __future__ import unicode_literals <add> <add>from ..char_classes import LIST_ELLIPSES, LIST_ICONS <add>from ..char_classes import QUOTES, ALPHA, ALPHA_LOWER, ALPHA_UPPER <add>from ..punctuation import TOKENIZER_SUFFIXES <add> <add> <add>_quotes = QUOTES.replace("'", '') <add> <add>_infixes = (LIST_ELLIPSES + LIST_ICONS + <add> [r'(?<=[{}])\.(?=[{}])'.format(ALPHA_LOWER, ALPHA_UPPER), <add> r'(?<=[{a}])[,!?](?=[{a}])'.format(a=ALPHA), <add> r'(?<=[{a}"])[:<>=](?=[{a}])'.format(a=ALPHA), <add> r'(?<=[{a}]),(?=[{a}])'.format(a=ALPHA), <add> r'(?<=[{a}])([{q}\)\]\(\[])(?=[\{a}])'.format(a=ALPHA, q=_quotes), <add> r'(?<=[{a}])--(?=[{a}])'.format(a=ALPHA)]) <add> <add>_suffixes = [suffix for suffix in TOKENIZER_SUFFIXES if suffix not in ["'s", "'S", "’s", "’S", r"\'"]] <add>_suffixes += [r"(?<=[^sSxXzZ])\'"] <add> <add> <add>TOKENIZER_INFIXES = _infixes <add>TOKENIZER_SUFFIXES = _suffixes <ide><path>spacy/lang/nb/tag_map.py <add># coding: utf8 <add>"""Based on Garman tag map, converted using <add>https://pdfs.semanticscholar.org/87b9/24e2134f6782acc59ab567f6bf87cb5e5d9f.pdf""" <add>from __future__ import unicode_literals <add> <add>from ...symbols import POS, PUNCT, ADJ, CONJ, CCONJ, SCONJ, SYM, NUM, DET, ADV, ADP, X, VERB <add>from ...symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX <add> <add> <add>TAG_MAP = { <add> "$(": {POS: PUNCT, "PunctType": "PUNCT"}, <add> "$)": {POS: PUNCT, "PunctType": "PUNCT"}, <add> # <parentes-slutt> PUNCT <add> # <parentes-beg> PUNCT <add> "$,": {POS: PUNCT, "PunctType": "PUNCT"}, <add> "$.": {POS: PUNCT, "PunctType": "PUNCT"}, <add> "$\"": {POS: PUNCT, "PunctType": "PUNCT"}, <add> "$-": {POS: PUNCT, "PunctType": "PUNCT"}, <add> <add> 'NOUN': {POS: NOUN}, <add> 'PROPN': {POS: PROPN}, <add> 'VERB': {POS: VERB}, <add> 'PUNCT': {POS: PUNCT}, <add> 'ADJ': {POS: ADJ}, <add> 'ADP': {POS: ADP}, <add> 'PART': {POS: PART}, <add> 'DET': {POS: DET}, <add> 'AUX': {POS: AUX}, <add> 'PRON': {POS: PRON}, <add> 'CCONJ': {POS: CCONJ}, <add> 'NUM': {POS: NUM}, <add> 'ADV': {POS: ADV}, <add> 'SCONJ': {POS: SCONJ}, <add> 'SYM': {POS: SYM}, <add> 'X': {POS: X}, <add> 'INTJ': {POS: INTJ}, <add> <add> # <anf> PUNCT <add> # 'adj': {POS: ADJ}, <add> # 'adv': {POS: ADV}, <add> # 'clb': {POS: PUNCT}, # SYM <add> # 'det': {POS: DET}, # NUM <add> # 'konj': {POS: CONJ}, <add> # 'interj': {POS: INTJ}, <add> # 'inf-merke': {POS: PART}, <add> # 'prep': {POS: ADP}, <add> # # 'prep': {POS: ADV}, <add> # 'pron': {POS: PRON}, <add> # 'sbu': {POS: SCONJ}, # <add> # 'subst': {POS: NOUN}, #, PROPN <add> # 'symb': {POS: SYM}, # <add> # 'ukjent': {POS: X}, # <add> # 'verb': {POS: AUX}, #, VERB <add> <add>}
4
Python
Python
fix the default master flag
c865727c09d7a1098c1949f6c640e75ba6b4d0ff
<ide><path>research/ptn/eval_rotator.py <ide> flags.DEFINE_integer('save_summaries_secs', 15, '') <ide> flags.DEFINE_integer('eval_interval_secs', 60 * 5, '') <ide> # Scheduling <del>flags.DEFINE_string('master', 'local', '') <add>flags.DEFINE_string('master', '', '') <ide> <ide> FLAGS = flags.FLAGS <ide>
1
Python
Python
give useful repr to _lazyxcomaccess class
1911c9211009499e8351b44feb58ca5efb56b090
<ide><path>airflow/models/taskinstance.py <ide> ) <ide> from urllib.parse import quote <ide> <add>import attr <ide> import dill <ide> import jinja2 <ide> import pendulum <ide> def __next__(self): <ide> return XCom.deserialize_value(next(self._it)) <ide> <ide> <add>@attr.define <ide> class _LazyXComAccess(collections.abc.Sequence): <ide> """Wrapper to lazily pull XCom with a sequence-like interface. <ide> <ide> class _LazyXComAccess(collections.abc.Sequence): <ide> for every function call with ``with_session()``. <ide> """ <ide> <del> def __init__(self, query: Query): <del> self._q = query <del> self._len = None <add> dag_id: str <add> run_id: str <add> task_id: str <add> _query: Query = attr.ib(repr=False) <add> _len: Optional[int] = attr.ib(init=False, repr=False, default=None) <add> <add> @classmethod <add> def build_from_single_xcom(cls, first: "XCom", query: Query) -> "_LazyXComAccess": <add> return cls( <add> dag_id=first.dag_id, <add> run_id=first.run_id, <add> task_id=first.task_id, <add> query=query.with_entities(XCom.value) <add> .filter( <add> XCom.run_id == first.run_id, <add> XCom.task_id == first.task_id, <add> XCom.dag_id == first.dag_id, <add> XCom.map_index >= 0, <add> ) <add> .order_by(None) <add> .order_by(XCom.map_index.asc()), <add> ) <ide> <ide> def __len__(self): <ide> if self._len is None: <ide> def __getitem__(self, key): <ide> @contextlib.contextmanager <ide> def _get_bound_query(self) -> Generator[Query, None, None]: <ide> # Do we have a valid session already? <del> if self._q.session and self._q.session.is_active: <del> yield self._q <add> if self._query.session and self._query.session.is_active: <add> yield self._query <ide> return <ide> <ide> session = settings.Session() <ide> try: <del> yield self._q.with_session(session) <add> yield self._query.with_session(session) <ide> finally: <ide> session.close() <ide> <ide> def xcom_pull( <ide> <ide> # We are only pulling one single task. <ide> if (task_ids is None or isinstance(task_ids, str)) and not isinstance(map_indexes, Iterable): <del> first = query.with_entities(XCom.run_id, XCom.task_id, XCom.map_index, XCom.value).first() <add> first = query.with_entities( <add> XCom.run_id, XCom.task_id, XCom.dag_id, XCom.map_index, XCom.value <add> ).first() <ide> if first is None: # No matching XCom at all. <ide> return default <ide> if map_indexes is not None or first.map_index < 0: <ide> return XCom.deserialize_value(first) <ide> <del> # We're pulling one specific mapped task. Add additional filters to <del> # make sure all XComs come from one task and run (for task_ids=None <del> # and include_prior_dates=True), and re-order by map index (reset <del> # needed because XCom.get_many() orders by XCom timestamp). <del> return _LazyXComAccess( <del> query.with_entities(XCom.value) <del> .filter(XCom.run_id == first.run_id, XCom.task_id == first.task_id, XCom.map_index >= 0) <del> .order_by(None) <del> .order_by(XCom.map_index.asc()) <del> ) <add> return _LazyXComAccess.build_from_single_xcom(first, query) <ide> <ide> # At this point either task_ids or map_indexes is explicitly multi-value. <ide> <ide><path>tests/models/test_taskinstance.py <ide> def test_ti_xcom_pull_on_mapped_operator_return_lazy_iterable(mock_deserialize_v <ide> joined = ti_2.xcom_pull("task_1", session=session) <ide> assert mock_deserialize_value.call_count == 0 <ide> <add> assert repr(joined) == "_LazyXComAccess(dag_id='test_xcom', run_id='test', task_id='task_1')" <add> <ide> # Only when we go through the iterable does deserialization happen. <ide> it = iter(joined) <ide> assert next(it) == "a"
2
Text
Text
add v3.4.7 to changelog.md
60a538c01e141569531c63673a6f9bbdad780a49
<ide><path>CHANGELOG.md <ide> - [#16978](https://github.com/emberjs/ember.js/pull/16978) [BUGFIX] Properly teardown alias <ide> - [#16877](https://github.com/emberjs/ember.js/pull/16877) [CLEANUP] Allow routes to be named "array" and "object" <ide> <add>### v3.4.7 (December 7, 2018) <add> <add>- #17271 [BUGFIX] Update `backburner.js` to 2.4.2. <add> <ide> ### v3.4.6 (October 29, 2018) <ide> <ide> - [#17115](https://github.com/emberjs/ember.js/pull/17115) [BUGFIX] Ensure `{{input` continues to pass the event to the actions that it fires.
1
Python
Python
fix lint issues in the official models
5ddd7e55c9ab6ae10a1459afc6309a2a417398d9
<ide><path>official/mnist/convert_to_records.py <ide> def main(unused_argv): <ide> <ide> if __name__ == '__main__': <ide> tf.logging.set_verbosity(tf.logging.INFO) <del> FLAGS = parser.parse_args() <del> tf.app.run() <add> FLAGS, unparsed = parser.parse_known_args() <add> tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) <ide><path>official/mnist/mnist.py <ide> <ide> import argparse <ide> import os <add>import sys <ide> <del>import numpy as np <ide> import tensorflow as tf <ide> <ide> parser = argparse.ArgumentParser() <ide> def input_fn(mode, batch_size=1): <ide> """A simple input_fn using the contrib.data input pipeline.""" <ide> <del> def parser(serialized_example): <add> def example_parser(serialized_example): <ide> """Parses a single tf.Example into image and label tensors.""" <ide> features = tf.parse_single_example( <ide> serialized_example, <ide> def parser(serialized_example): <ide> assert mode == tf.estimator.ModeKeys.EVAL, 'invalid mode' <ide> tfrecords_file = os.path.join(FLAGS.data_dir, 'test.tfrecords') <ide> <del> assert tf.gfile.Exists(tfrecords_file), ('Run convert_to_records.py first to ' <del> 'convert the MNIST data to TFRecord file format.') <add> assert tf.gfile.Exists(tfrecords_file), ( <add> 'Run convert_to_records.py first to convert the MNIST data to TFRecord ' <add> 'file format.') <ide> <ide> dataset = tf.contrib.data.TFRecordDataset([tfrecords_file]) <ide> <ide> # For training, repeat the dataset forever <ide> if mode == tf.estimator.ModeKeys.TRAIN: <ide> dataset = dataset.repeat() <ide> <del> # Map the parser over dataset, and batch results by up to batch_size <del> dataset = dataset.map(parser, num_threads=1, output_buffer_size=batch_size) <add> # Map example_parser over dataset, and batch results by up to batch_size <add> dataset = dataset.map( <add> example_parser, num_threads=1, output_buffer_size=batch_size) <ide> dataset = dataset.batch(batch_size) <ide> images, labels = dataset.make_one_shot_iterator().get_next() <ide> <ide> def main(unused_argv): <ide> <ide> if __name__ == '__main__': <ide> tf.logging.set_verbosity(tf.logging.INFO) <del> FLAGS = parser.parse_args() <del> tf.app.run() <add> FLAGS, unparsed = parser.parse_known_args() <add> tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) <ide><path>official/mnist/mnist_test.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del>import numpy as np <ide> import tensorflow as tf <ide> <ide> import mnist <ide><path>official/resnet/cifar10_download_and_extract.py <ide> def main(unused_argv): <ide> <ide> if not os.path.exists(filepath): <ide> def _progress(count, block_size, total_size): <del> sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, <del> 100.0 * count * block_size / total_size)) <add> sys.stdout.write('\r>> Downloading %s %.1f%%' % ( <add> filename, 100.0 * count * block_size / total_size)) <ide> sys.stdout.flush() <ide> <ide> filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress) <ide><path>official/resnet/cifar10_main.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> # ============================================================================== <add>"""Runs a ResNet model on the CIFAR-10 dataset.""" <ide> <ide> from __future__ import absolute_import <ide> from __future__ import division <ide> from __future__ import print_function <ide> <ide> import argparse <ide> import os <del>import sys <ide> <del>import numpy as np <ide> import tensorflow as tf <ide> <ide> import resnet_model <ide> def record_dataset(filenames): <ide> return tf.contrib.data.FixedLengthRecordDataset(filenames, record_bytes) <ide> <ide> <del>def filenames(mode): <add>def get_filenames(mode): <ide> """Returns a list of filenames based on 'mode'.""" <ide> data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin') <ide> <del> assert os.path.exists(data_dir), ('Run cifar10_download_and_extract.py first ' <del> 'to download and extract the CIFAR-10 data.') <add> assert os.path.exists(data_dir), ( <add> 'Run cifar10_download_and_extract.py first to download and extract the ' <add> 'CIFAR-10 data.') <ide> <ide> if mode == tf.estimator.ModeKeys.TRAIN: <ide> return [ <ide> def input_fn(mode, batch_size): <ide> """Input_fn using the contrib.data input pipeline for CIFAR-10 dataset. <ide> <ide> Args: <del> mode: Standard names for model modes (tf.estimators.ModeKeys). <add> mode: Standard names for model modes from tf.estimator.ModeKeys. <ide> batch_size: The number of samples per batch of input requested. <add> <add> Returns: <add> A tuple of images and labels. <ide> """ <del> dataset = record_dataset(filenames(mode)) <add> dataset = record_dataset(get_filenames(mode)) <ide> <ide> # For training repeat forever. <ide> if mode == tf.estimator.ModeKeys.TRAIN: <ide> def cifar10_model_fn(features, labels, mode): <ide> else: <ide> train_op = None <ide> <del> accuracy= tf.metrics.accuracy( <add> accuracy = tf.metrics.accuracy( <ide> tf.argmax(labels, axis=1), predictions['classes']) <ide> metrics = {'accuracy': accuracy} <ide> <ide> def main(unused_argv): <ide> cifar_classifier = tf.estimator.Estimator( <ide> model_fn=cifar10_model_fn, model_dir=FLAGS.model_dir) <ide> <del> for cycle in range(FLAGS.train_steps // FLAGS.steps_per_eval): <add> for _ in range(FLAGS.train_steps // FLAGS.steps_per_eval): <ide> tensors_to_log = { <ide> 'learning_rate': 'learning_rate', <ide> 'cross_entropy': 'cross_entropy', <ide><path>official/resnet/cifar10_test.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del>import os <del>import sys <del>from tempfile import mkdtemp <ide> from tempfile import mkstemp <ide> <ide> import numpy as np <ide> def test_dataset_input_fn(self): <ide> fake_data = bytearray() <ide> fake_data.append(7) <ide> for i in xrange(3): <del> for j in xrange(1024): <add> for _ in xrange(1024): <ide> fake_data.append(i) <ide> <ide> _, filename = mkstemp(dir=self.get_temp_dir()) <del> file = open(filename, 'wb') <del> file.write(fake_data) <del> file.close() <add> data_file = open(filename, 'wb') <add> data_file.write(fake_data) <add> data_file.close() <ide> <ide> fake_dataset = cifar10_main.record_dataset(filename) <ide> fake_dataset = fake_dataset.map(cifar10_main.dataset_parser) <ide><path>official/resnet/imagenet_main.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> # ============================================================================== <add>"""Runs a ResNet model on the ImageNet dataset.""" <ide> <ide> from __future__ import absolute_import <ide> from __future__ import division <ide> def input_fn(is_training): <ide> <ide> <ide> def resnet_model_fn(features, labels, mode): <del> """ Our model_fn for ResNet to be used with our Estimator.""" <add> """Our model_fn for ResNet to be used with our Estimator.""" <ide> tf.summary.image('images', features, max_outputs=6) <ide> <ide> logits = network( <ide> def main(unused_argv): <ide> resnet_classifier = tf.estimator.Estimator( <ide> model_fn=resnet_model_fn, model_dir=FLAGS.model_dir) <ide> <del> for cycle in range(FLAGS.train_steps // FLAGS.steps_per_eval): <add> for _ in range(FLAGS.train_steps // FLAGS.steps_per_eval): <ide> tensors_to_log = { <ide> 'learning_rate': 'learning_rate', <ide> 'cross_entropy': 'cross_entropy', <ide><path>official/resnet/imagenet_test.py <ide> class BaseTest(tf.test.TestCase): <ide> def tensor_shapes_helper(self, resnet_size, with_gpu=False): <ide> """Checks the tensor shapes after each phase of the ResNet model.""" <ide> def reshape(shape): <del> """Returns the expected dimensions depending on if gpu is being used. <del> <del> If a GPU is used for the test, the shape is returned (already in NCHW <del> form). When GPU is not used, the shape is converted to NHWC. <del> """ <add> """Returns the expected dimensions depending on if a GPU is being used.""" <add> # If a GPU is used for the test, the shape is returned (already in NCHW <add> # form). When GPU is not used, the shape is converted to NHWC. <ide> if with_gpu: <ide> return shape <ide> return shape[0], shape[2], shape[3], shape[1] <ide><path>official/resnet/resnet_model.py <ide> <ide> def batch_norm_relu(inputs, is_training, data_format): <ide> """Performs a batch normalization followed by a ReLU.""" <del> # We set fused=True for a significant performance boost. <del> # See https://www.tensorflow.org/performance/performance_guide#common_fused_ops <add> # We set fused=True for a significant performance boost. See <add> # https://www.tensorflow.org/performance/performance_guide#common_fused_ops <ide> inputs = tf.layers.batch_normalization( <ide> inputs=inputs, axis=1 if data_format == 'channels_first' else 3, <ide> momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True, <ide> def fixed_padding(inputs, kernel_size, data_format): <ide> <ide> <ide> def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): <del> """Strided 2-D convolution with explicit padding. <del> <del> The padding is consistent and is based only on `kernel_size`, not on the <del> dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). <del> """ <add> """Strided 2-D convolution with explicit padding.""" <add> # The padding is consistent and is based only on `kernel_size`, not on the <add> # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). <ide> if strides > 1: <ide> inputs = fixed_padding(inputs, kernel_size, data_format) <ide> <ide> def projection_shortcut(inputs): <ide> inputs = block_fn(inputs, filters, is_training, projection_shortcut, strides, <ide> data_format) <ide> <del> for i in range(1, blocks): <add> for _ in range(1, blocks): <ide> inputs = block_fn(inputs, filters, is_training, None, 1, data_format) <ide> <ide> return tf.identity(inputs, name) <ide> def cifar10_resnet_v2_generator(resnet_size, num_classes, data_format=None): <ide> Returns: <ide> The model function that takes in `inputs` and `is_training` and <ide> returns the output tensor of the ResNet model. <add> <add> Raises: <add> ValueError: If `resnet_size` is invalid. <ide> """ <ide> if resnet_size % 6 != 2: <ide> raise ValueError('resnet_size must be 6n + 2:', resnet_size) <ide> <ide> num_blocks = (resnet_size - 2) // 6 <ide> <ide> if data_format is None: <del> data_format = 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last' <add> data_format = ( <add> 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last') <ide> <ide> def model(inputs, is_training): <add> """Constructs the ResNet model given the inputs.""" <ide> if data_format == 'channels_first': <ide> # Convert from channels_last (NHWC) to channels_first (NCHW). This <del> # provides a large performance boost on GPU. <del> # See https://www.tensorflow.org/performance/performance_guide#data_formats <add> # provides a large performance boost on GPU. See <add> # https://www.tensorflow.org/performance/performance_guide#data_formats <ide> inputs = tf.transpose(inputs, [0, 3, 1, 2]) <ide> <ide> inputs = conv2d_fixed_padding( <ide> def imagenet_resnet_v2_generator(block_fn, layers, num_classes, <ide> returns the output tensor of the ResNet model. <ide> """ <ide> if data_format is None: <del> data_format = 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last' <add> data_format = ( <add> 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last') <ide> <ide> def model(inputs, is_training): <add> """Constructs the ResNet model given the inputs.""" <ide> if data_format == 'channels_first': <ide> # Convert from channels_last (NHWC) to channels_first (NCHW). This <ide> # provides a large performance boost on GPU.
9
Javascript
Javascript
add fsstarttime for single runs
fbcc470bcf6a2fcf7494f6f720638d06a5166ea2
<ide><path>lib/node/NodeEnvironmentPlugin.js <ide> class NodeEnvironmentPlugin { <ide> ); <ide> compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { <ide> if (compiler.inputFileSystem === inputFileSystem) { <add> compiler.fsStartTime = Date.now(); <ide> inputFileSystem.purge(); <ide> } <ide> }); <ide><path>test/configCases/asset-modules/file-url/webpack.config.js <ide> const fs = require("fs"); <ide> const path = require("path"); <ide> const { pathToFileURL } = require("url"); <del>const file = path.resolve( <del> "./test/configCases/asset-modules/file-url", <del> "./temp/index.js" <del>); <add>const dir = path.resolve(__dirname, "temp"); <add>const file = path.resolve(dir, "index.js"); <ide> <del>fs.mkdirSync("./test/configCases/asset-modules/file-url/temp", { <add>fs.mkdirSync(dir, { <ide> recursive: true <ide> }); <ide> fs.writeFileSync( <ide> import v2 from ${JSON.stringify( <ide> export const val1 = v1; <ide> export const val2 = v2;` <ide> ); <add>fs.utimesSync(file, new Date(Date.now() - 10000), new Date(Date.now() - 10000)); <ide> <ide> /** @type {import("../../../../").Configuration} */ <ide> module.exports = {
2
Text
Text
fix ulimit command form
98e5a8efcc390d2b5de18049e3227db7a257c232
<ide><path>docs/reference/commandline/run.md <ide> available in the default container, you can set these using the `--ulimit` flag. <ide> `--ulimit` is specified with a soft and hard limit as such: <ide> `<type>=<soft limit>[:<hard limit>]`, for example: <ide> <del> $ docker run --ulimit nofile=1024:1024 --rm debian ulimit -n <add> $ docker run --ulimit nofile=1024:1024 --rm debian sh -c "ulimit -n" <ide> 1024 <ide> <ide> > **Note:**
1
Ruby
Ruby
improve autosave documentation [ci skip]
ad050486ee237db3f3bed6af0ae7e3640bb41e92
<ide><path>activerecord/lib/active_record/autosave_association.rb <ide> module ActiveRecord <ide> # post.save # => saves both post and comment <ide> # <ide> # post = Post.create(title: 'ruby rocks') <del> # post.comments.create(body: 'hello world') <del> # post.save # => saves both post and comment <add> # comment = post.comments.create(body: 'hello world') <add> # comment.body = 'hi everyone' <add> # post.save # => saves post, but not comment <ide> # <ide> # When <tt>:autosave</tt> is true all children are saved, no matter whether they <ide> # are new records or not: <ide> module ActiveRecord <ide> # end <ide> # <ide> # post = Post.create(title: 'ruby rocks') <del> # post.comments.create(body: 'hello world') <del> # post.comments[0].body = 'hi everyone' <add> # comment = post.comments.create(body: 'hello world') <add> # comment.body = 'hi everyone' <ide> # post.comments.build(body: "good morning.") <del> # post.title += "!" <del> # post.save # => saves both post and comments. <add> # post.save # => saves post and both comments. <ide> # <ide> # Destroying one of the associated models as part of the parent's save action <ide> # is as simple as marking it for destruction:
1
Java
Java
initialize rootview size to the display size
588320831f1ecc6e26f344cc08f137b364da7ffc
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> import android.os.Build; <ide> import android.os.Bundle; <ide> import android.util.AttributeSet; <add>import android.util.DisplayMetrics; <ide> import android.view.DisplayCutout; <ide> import android.view.KeyEvent; <ide> import android.view.MotionEvent; <ide> public void startReactApplication( <ide> // if in this experiment, we initialize the root earlier in startReactApplication <ide> // instead of waiting for the initial measure <ide> if (ReactFeatureFlags.enableEagerRootViewAttachment) { <add> if (!mWasMeasured) { <add> // Ideally, those values will be used by default, but we only update them here to scope <add> // this change to `enableEagerRootViewAttachment` experiment. <add> setSurfaceConstraintsToScreenSize(); <add> } <ide> attachToReactInstanceManager(); <ide> } <ide> } finally { <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> <add> private void setSurfaceConstraintsToScreenSize() { <add> DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); <add> mWidthMeasureSpec = <add> MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, MeasureSpec.AT_MOST); <add> mHeightMeasureSpec = <add> MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, MeasureSpec.AT_MOST); <add> } <add> <ide> @Override <ide> public int getWidthMeasureSpec() { <ide> return mWidthMeasureSpec;
1
PHP
PHP
add route callable test
6641ac81c635afc34111dc74e20319e62198f542
<ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testBasicDispatchingOfRoutes() <ide> $router = $this->getRouter(); <ide> $router->get('foo/bar/åαф', function() { return 'hello'; }); <ide> $this->assertEquals('hello', $router->dispatch(Request::create('foo/bar/%C3%A5%CE%B1%D1%84', 'GET'))->getContent()); <add> <add> $router = $this->getRouter(); <add> $router->get('foo/bar', ['boom' => 'auth', function() { return 'closure'; }]); <add> $this->assertEquals('closure', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); <ide> } <ide> <ide>
1
Javascript
Javascript
add back chart.ticks.formatters
33c7d941f7caa5363f68ac2135a66d7c2328e196
<ide><path>src/chart.js <ide> Chart.Element = require('./core/core.element'); <ide> Chart.elements = require('./elements/index'); <ide> Chart.Interaction = require('./core/core.interaction'); <ide> Chart.platform = require('./platforms/platform'); <add>Chart.Ticks = require('./core/core.ticks'); <ide> <ide> require('./core/core.plugin')(Chart); <ide> require('./core/core.animation')(Chart); <ide><path>src/core/core.ticks.js <ide> var helpers = require('../helpers/index'); <ide> * @namespace Chart.Ticks <ide> */ <ide> module.exports = { <del> /** <del> * Namespace to hold generators for different types of ticks <del> * @namespace Chart.Ticks.generators <del> */ <del> generators: { <del> /** <del> * Interface for the options provided to the numeric tick generator <del> * @interface INumericTickGenerationOptions <del> */ <del> /** <del> * The maximum number of ticks to display <del> * @name INumericTickGenerationOptions#maxTicks <del> * @type Number <del> */ <del> /** <del> * The distance between each tick. <del> * @name INumericTickGenerationOptions#stepSize <del> * @type Number <del> * @optional <del> */ <del> /** <del> * Forced minimum for the ticks. If not specified, the minimum of the data range is used to calculate the tick minimum <del> * @name INumericTickGenerationOptions#min <del> * @type Number <del> * @optional <del> */ <del> /** <del> * The maximum value of the ticks. If not specified, the maximum of the data range is used to calculate the tick maximum <del> * @name INumericTickGenerationOptions#max <del> * @type Number <del> * @optional <del> */ <del> <del> /** <del> * Generate a set of linear ticks <del> * @method Chart.Ticks.generators.linear <del> * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks <del> * @param dataRange {IRange} the range of the data <del> * @returns {Array<Number>} array of tick values <del> */ <del> linear: function(generationOptions, dataRange) { <del> var ticks = []; <del> // To get a "nice" value for the tick spacing, we will use the appropriately named <del> // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks <del> // for details. <del> <del> var spacing; <del> if (generationOptions.stepSize && generationOptions.stepSize > 0) { <del> spacing = generationOptions.stepSize; <del> } else { <del> var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); <del> spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); <del> } <del> var niceMin = Math.floor(dataRange.min / spacing) * spacing; <del> var niceMax = Math.ceil(dataRange.max / spacing) * spacing; <del> <del> // If min, max and stepSize is set and they make an evenly spaced scale use it. <del> if (generationOptions.min && generationOptions.max && generationOptions.stepSize) { <del> // If very close to our whole number, use it. <del> if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) { <del> niceMin = generationOptions.min; <del> niceMax = generationOptions.max; <del> } <del> } <del> <del> var numSpaces = (niceMax - niceMin) / spacing; <del> // If very close to our rounded value, use it. <del> if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { <del> numSpaces = Math.round(numSpaces); <del> } else { <del> numSpaces = Math.ceil(numSpaces); <del> } <del> <del> var precision = 1; <del> if (spacing < 1) { <del> precision = Math.pow(10, spacing.toString().length - 2); <del> niceMin = Math.round(niceMin * precision) / precision; <del> niceMax = Math.round(niceMax * precision) / precision; <del> } <del> ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); <del> for (var j = 1; j < numSpaces; ++j) { <del> ticks.push(Math.round((niceMin + j * spacing) * precision) / precision); <del> } <del> ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); <del> <del> return ticks; <del> }, <del> <del> /** <del> * Generate a set of logarithmic ticks <del> * @method Chart.Ticks.generators.logarithmic <del> * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks <del> * @param dataRange {IRange} the range of the data <del> * @returns {Array<Number>} array of tick values <del> */ <del> logarithmic: function(generationOptions, dataRange) { <del> var ticks = []; <del> var valueOrDefault = helpers.valueOrDefault; <del> <del> // Figure out what the max number of ticks we can support it is based on the size of <del> // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 <del> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <del> // the graph <del> var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min)))); <del> <del> var endExp = Math.floor(helpers.log10(dataRange.max)); <del> var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); <del> var exp, significand; <del> <del> if (tickVal === 0) { <del> exp = Math.floor(helpers.log10(dataRange.minNotZero)); <del> significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp)); <del> <del> ticks.push(tickVal); <del> tickVal = significand * Math.pow(10, exp); <del> } else { <del> exp = Math.floor(helpers.log10(tickVal)); <del> significand = Math.floor(tickVal / Math.pow(10, exp)); <del> } <del> var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; <del> <del> do { <del> ticks.push(tickVal); <del> <del> ++significand; <del> if (significand === 10) { <del> significand = 1; <del> ++exp; <del> precision = exp >= 0 ? 1 : precision; <del> } <del> <del> tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; <del> } while (exp < endExp || (exp === endExp && significand < endSignificand)); <del> <del> var lastTick = valueOrDefault(generationOptions.max, tickVal); <del> ticks.push(lastTick); <del> <del> return ticks; <del> } <del> }, <del> <ide> /** <ide> * Namespace to hold formatters for different types of ticks <ide> * @namespace Chart.Ticks.formatters <ide><path>src/scales/scale.linearbase.js <ide> 'use strict'; <ide> <ide> var helpers = require('../helpers/index'); <del>var Ticks = require('../core/core.ticks'); <add> <add>/** <add> * Generate a set of linear ticks <add> * @param generationOptions the options used to generate the ticks <add> * @param dataRange the range of the data <add> * @returns {Array<Number>} array of tick values <add> */ <add>function generateTicks(generationOptions, dataRange) { <add> var ticks = []; <add> // To get a "nice" value for the tick spacing, we will use the appropriately named <add> // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks <add> // for details. <add> <add> var spacing; <add> if (generationOptions.stepSize && generationOptions.stepSize > 0) { <add> spacing = generationOptions.stepSize; <add> } else { <add> var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); <add> spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); <add> } <add> var niceMin = Math.floor(dataRange.min / spacing) * spacing; <add> var niceMax = Math.ceil(dataRange.max / spacing) * spacing; <add> <add> // If min, max and stepSize is set and they make an evenly spaced scale use it. <add> if (generationOptions.min && generationOptions.max && generationOptions.stepSize) { <add> // If very close to our whole number, use it. <add> if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) { <add> niceMin = generationOptions.min; <add> niceMax = generationOptions.max; <add> } <add> } <add> <add> var numSpaces = (niceMax - niceMin) / spacing; <add> // If very close to our rounded value, use it. <add> if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { <add> numSpaces = Math.round(numSpaces); <add> } else { <add> numSpaces = Math.ceil(numSpaces); <add> } <add> <add> var precision = 1; <add> if (spacing < 1) { <add> precision = Math.pow(10, spacing.toString().length - 2); <add> niceMin = Math.round(niceMin * precision) / precision; <add> niceMax = Math.round(niceMax * precision) / precision; <add> } <add> ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); <add> for (var j = 1; j < numSpaces; ++j) { <add> ticks.push(Math.round((niceMin + j * spacing) * precision) / precision); <add> } <add> ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); <add> <add> return ticks; <add>} <add> <ide> <ide> module.exports = function(Chart) { <ide> <ide> module.exports = function(Chart) { <ide> max: tickOpts.max, <ide> stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize) <ide> }; <del> var ticks = me.ticks = Ticks.generators.linear(numericGeneratorOptions, me); <add> var ticks = me.ticks = generateTicks(numericGeneratorOptions, me); <ide> <ide> me.handleDirectionalChanges(); <ide> <ide><path>src/scales/scale.logarithmic.js <ide> var helpers = require('../helpers/index'); <ide> var Ticks = require('../core/core.ticks'); <ide> <add>/** <add> * Generate a set of logarithmic ticks <add> * @param generationOptions the options used to generate the ticks <add> * @param dataRange the range of the data <add> * @returns {Array<Number>} array of tick values <add> */ <add>function generateTicks(generationOptions, dataRange) { <add> var ticks = []; <add> var valueOrDefault = helpers.valueOrDefault; <add> <add> // Figure out what the max number of ticks we can support it is based on the size of <add> // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 <add> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <add> // the graph <add> var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min)))); <add> <add> var endExp = Math.floor(helpers.log10(dataRange.max)); <add> var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); <add> var exp, significand; <add> <add> if (tickVal === 0) { <add> exp = Math.floor(helpers.log10(dataRange.minNotZero)); <add> significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp)); <add> <add> ticks.push(tickVal); <add> tickVal = significand * Math.pow(10, exp); <add> } else { <add> exp = Math.floor(helpers.log10(tickVal)); <add> significand = Math.floor(tickVal / Math.pow(10, exp)); <add> } <add> var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; <add> <add> do { <add> ticks.push(tickVal); <add> <add> ++significand; <add> if (significand === 10) { <add> significand = 1; <add> ++exp; <add> precision = exp >= 0 ? 1 : precision; <add> } <add> <add> tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; <add> } while (exp < endExp || (exp === endExp && significand < endSignificand)); <add> <add> var lastTick = valueOrDefault(generationOptions.max, tickVal); <add> ticks.push(lastTick); <add> <add> return ticks; <add>} <add> <add> <ide> module.exports = function(Chart) { <ide> <ide> var defaultConfig = { <ide> module.exports = function(Chart) { <ide> min: tickOpts.min, <ide> max: tickOpts.max <ide> }; <del> var ticks = me.ticks = Ticks.generators.logarithmic(generationOptions, me); <add> var ticks = me.ticks = generateTicks(generationOptions, me); <ide> <ide> // At this point, we need to update our max and min given the tick values since we have expanded the <ide> // range of the scale <ide><path>test/specs/core.ticks.tests.js <ide> describe('Test tick generators', function() { <add> // formatters are used as default config values so users want to be able to reference them <add> it('Should expose formatters api', function() { <add> expect(typeof Chart.Ticks).toBeDefined(); <add> expect(typeof Chart.Ticks.formatters).toBeDefined(); <add> expect(typeof Chart.Ticks.formatters.values).toBe('function'); <add> expect(typeof Chart.Ticks.formatters.linear).toBe('function'); <add> expect(typeof Chart.Ticks.formatters.logarithmic).toBe('function'); <add> }); <add> <ide> it('Should generate linear spaced ticks with correct precision', function() { <ide> var chart = window.acquireChart({ <ide> type: 'line',
5
Javascript
Javascript
add try-catch for gltfbinaryextension
2138f8154660b5dc760d598cd01bdf37786f88e5
<ide><path>examples/js/loaders/GLTFLoader.js <ide> THREE.GLTFLoader = ( function () { <ide> <ide> if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { <ide> <del> extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); <add> try { <add> <add> extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); <add> <add> } catch ( error ) { <add> <add> onError( error ); <add> return; <add> <add> } <add> <ide> content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; <ide> <ide> } else {
1
Python
Python
add stone unit of measuring weight
dc6e77338c9cac607e58c06b178a232643f3e87d
<ide><path>conversions/weight_conversion.py <ide> <ide> __author__ = "Anubhav Solanki" <ide> __license__ = "MIT" <del>__version__ = "1.0.0" <add>__version__ = "1.1.0" <ide> __maintainer__ = "Anubhav Solanki" <ide> __email__ = "[email protected]" <ide> <ide> -> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce <ide> -> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat <ide> -> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) <add>-> Wikipedia reference: https://en.wikipedia.org/wiki/Stone_(unit) <ide> """ <ide> <ide> KILOGRAM_CHART: dict[str, float] = { <ide> "long-ton": 0.0009842073, <ide> "short-ton": 0.0011023122, <ide> "pound": 2.2046244202, <add> "stone": 0.1574731728, <ide> "ounce": 35.273990723, <ide> "carrat": 5000, <ide> "atomic-mass-unit": 6.022136652e26, <ide> "long-ton": 1016.04608, <ide> "short-ton": 907.184, <ide> "pound": 0.453592, <add> "stone": 6.35029, <ide> "ounce": 0.0283495, <ide> "carrat": 0.0002, <ide> "atomic-mass-unit": 1.660540199e-27, <ide> def weight_conversion(from_type: str, to_type: str, value: float) -> float: <ide> "long-ton" : 0.0009842073, <ide> "short-ton" : 0.0011023122, <ide> "pound" : 2.2046244202, <add> "stone": 0.1574731728, <ide> "ounce" : 35.273990723, <ide> "carrat" : 5000, <ide> "atomic-mass-unit" : 6.022136652E+26 <ide> def weight_conversion(from_type: str, to_type: str, value: float) -> float: <ide> 0.0011023122 <ide> >>> weight_conversion("kilogram","pound",4) <ide> 8.8184976808 <add> >>> weight_conversion("kilogram","stone",5) <add> 0.7873658640000001 <ide> >>> weight_conversion("kilogram","ounce",4) <ide> 141.095962892 <ide> >>> weight_conversion("kilogram","carrat",3) <ide> def weight_conversion(from_type: str, to_type: str, value: float) -> float: <ide> 3.3069366000000003e-06 <ide> >>> weight_conversion("gram","pound",3) <ide> 0.0066138732606 <add> >>> weight_conversion("gram","stone",4) <add> 0.0006298926912000001 <ide> >>> weight_conversion("gram","ounce",1) <ide> 0.035273990723 <ide> >>> weight_conversion("gram","carrat",2) <ide> def weight_conversion(from_type: str, to_type: str, value: float) -> float: <ide> 2267.96 <ide> >>> weight_conversion("pound","atomic-mass-unit",4) <ide> 1.0926372033015936e+27 <add> >>> weight_conversion("stone","kilogram",5) <add> 31.751450000000002 <add> >>> weight_conversion("stone","gram",2) <add> 12700.58 <add> >>> weight_conversion("stone","milligram",3) <add> 19050870.0 <add> >>> weight_conversion("stone","metric-ton",3) <add> 0.01905087 <add> >>> weight_conversion("stone","long-ton",3) <add> 0.018750005325351003 <add> >>> weight_conversion("stone","short-ton",3) <add> 0.021000006421614002 <add> >>> weight_conversion("stone","pound",2) <add> 28.00000881870372 <add> >>> weight_conversion("stone","ounce",1) <add> 224.00007054835967 <add> >>> weight_conversion("stone","carrat",2) <add> 63502.9 <ide> >>> weight_conversion("ounce","kilogram",3) <ide> 0.0850485 <ide> >>> weight_conversion("ounce","gram",3)
1
PHP
PHP
correct the option key
0536e058f9aa6e52509f0085fbc30b6697b10a9b
<ide><path>lib/Cake/Network/CakeResponse.php <ide> class CakeResponse { <ide> * <ide> * @param array $options list of parameters to setup the response. Possible values are: <ide> * - body: the response text that should be sent to the client <del> * - codes: additional allowable response codes <add> * - statusCodes: additional allowable response codes <ide> * - status: the HTTP status code to respond with <ide> * - type: a complete mime-type string or an extension mapped in this class <ide> * - charset: the charset for the response body
1
PHP
PHP
fix container docblock
d4de66f78e30519cf5f03e177efc8fb25c2e26bd
<ide><path>src/Illuminate/Container/Container.php <ide> public function makeWith($abstract, array $parameters = []) <ide> * @param string $abstract <ide> * @param array $parameters <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Container\BindingResolutionException <ide> */ <ide> public function make($abstract, array $parameters = []) <ide> { <ide> public function get($id) <ide> * @param string $abstract <ide> * @param array $parameters <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Container\BindingResolutionException <ide> */ <ide> protected function resolve($abstract, $parameters = []) <ide> { <ide> public function build($concrete) <ide> * <ide> * @param array $dependencies <ide> * @return array <add> * <add> * @throws \Illuminate\Contracts\Container\BindingResolutionException <ide> */ <ide> protected function resolveDependencies(array $dependencies) <ide> {
1
Text
Text
update the result of generate command [skip ci]
923a0027902ba3829d08bb5350050ef71f7c0420
<ide><path>guides/source/engines.md <ide> create app/views/blorgh/articles/new.html.erb <ide> create app/views/blorgh/articles/_form.html.erb <ide> invoke test_unit <ide> create test/controllers/blorgh/articles_controller_test.rb <add>create test/system/blorgh/articles_test.rb <ide> invoke helper <ide> create app/helpers/blorgh/articles_helper.rb <del>invoke test_unit <del>create test/application_system_test_case.rb <del>create test/system/articles_test.rb <add>invoke test_unit <ide> invoke assets <del>invoke js <del>create app/assets/javascripts/blorgh/articles.js <ide> invoke css <ide> create app/assets/stylesheets/blorgh/articles.css <ide> invoke css <ide> be isolated from those routes that are within the application. The <ide> Next, the `scaffold_controller` generator is invoked, generating a controller <ide> called `Blorgh::ArticlesController` (at <ide> `app/controllers/blorgh/articles_controller.rb`) and its related views at <del>`app/views/blorgh/articles`. This generator also generates a test for the <del>controller (`test/controllers/blorgh/articles_controller_test.rb`) and a helper <del>(`app/helpers/blorgh/articles_helper.rb`). <add>`app/views/blorgh/articles`. This generator also generates tests for the <add>controller (`test/controllers/blorgh/articles_controller_test.rb` and `test/system/blorgh/articles_test.rb`) and a helper (`app/helpers/blorgh/articles_helper.rb`). <ide> <ide> Everything this generator has created is neatly namespaced. The controller's <ide> class is defined within the `Blorgh` module: <ide> end <ide> This helps prevent conflicts with any other engine or application that may have <ide> an article resource as well. <ide> <del>Finally, the assets for this resource are generated in two files: <del>`app/assets/javascripts/blorgh/articles.js` and <del>`app/assets/stylesheets/blorgh/articles.css`. You'll see how to use these a little <del>later. <add>Finally, the assets for this resource are generated in one file: `app/assets/stylesheets/blorgh/articles.css`. You'll see how to use these a little later. <ide> <ide> You can see what the engine has so far by running `rails db:migrate` at the root <ide> of our engine to run the migration generated by the scaffold generator, and then <ide> invoke test_unit <ide> create test/controllers/blorgh/comments_controller_test.rb <ide> invoke helper <ide> create app/helpers/blorgh/comments_helper.rb <add>invoke test_unit <ide> invoke assets <del>invoke js <del>create app/assets/javascripts/blorgh/comments.js <ide> invoke css <ide> create app/assets/stylesheets/blorgh/comments.css <ide> ```
1
Text
Text
fix odd indentation [ci skip]
c02d9e5a3db4c7dc91c742536ec3cf665acb62fc
<ide><path>guides/source/getting_started.md <ide> active_record_migrations.html). <ide> We also have to permit the `:status` key as part of the strong parameter, in `app/controllers/articles_controller.rb`: <ide> <ide> ```ruby <del>private <add> private <ide> def article_params <ide> params.require(:comment).permit(:commenter, :body, :status) <ide> end <ide> private <ide> and in `app/controllers/comments_controller.rb`: <ide> <ide> ```ruby <del>private <add> private <ide> def comment_params <ide> params.require(:comment).permit(:commenter, :body, :status) <ide> end
1
Javascript
Javascript
use common.mustcall in test-http-malformed-request
f6b2839bc396df2591952bc16cfe8c543c077f25
<ide><path>test/parallel/test-http-malformed-request.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>require('../common'); <del>const assert = require('assert'); <add>const common = require('../common'); <ide> const net = require('net'); <ide> const http = require('http'); <ide> const url = require('url'); <ide> <ide> // Make sure no exceptions are thrown when receiving malformed HTTP <ide> // requests. <del> <del>let nrequests_completed = 0; <del>const nrequests_expected = 1; <del> <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer(common.mustCall((req, res) => { <ide> console.log(`req: ${JSON.stringify(url.parse(req.url))}`); <ide> <ide> res.writeHead(200, { 'Content-Type': 'text/plain' }); <ide> res.write('Hello World'); <ide> res.end(); <ide> <del> if (++nrequests_completed === nrequests_expected) server.close(); <del>}); <add> server.close(); <add>})); <ide> server.listen(0); <ide> <ide> server.on('listening', function() { <ide> server.on('listening', function() { <ide> c.end(); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.strictEqual(nrequests_expected, nrequests_completed); <del>});
1
Java
Java
fix regression in determinetransactionmanager
961574bd17b2fe30f171646f54667b5895f0dcbf
<ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java <ide> protected void clearTransactionManagerCache() { <ide> * Determine the specific transaction manager to use for the given transaction. <ide> */ <ide> protected PlatformTransactionManager determineTransactionManager(TransactionAttribute txAttr) { <del> if (this.beanFactory != null) { <del> String qualifier = txAttr != null ? txAttr.getQualifier() : null; <del> if (StringUtils.hasText(qualifier)) { <del> return determineQualifiedTransactionManager(qualifier); <del> } <del> else if (StringUtils.hasText(this.transactionManagerBeanName)) { <del> return determineQualifiedTransactionManager(this.transactionManagerBeanName); <del> } <del> else if (txAttr != null) { // Do not lookup default bean name if no tx attributes are set <del> PlatformTransactionManager defaultTransactionManager = getTransactionManager(); <del> if (defaultTransactionManager == null) { <del> defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class); <del> this.transactionManagerCache.putIfAbsent( <del> DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager); <del> } <del> return defaultTransactionManager; <add> // Do not attempt to lookup tx manager if no tx attributes are set <add> if (txAttr == null || this.beanFactory == null) { <add> return getTransactionManager(); <add> } <add> String qualifier = (txAttr.getQualifier() != null ? <add> txAttr.getQualifier() : this.transactionManagerBeanName); <add> if (StringUtils.hasText(qualifier)) { <add> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier); <add> if (txManager == null) { <add> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType( <add> this.beanFactory, PlatformTransactionManager.class, qualifier); <add> this.transactionManagerCache.putIfAbsent(qualifier, txManager); <ide> } <add> return txManager; <ide> } <del> return getTransactionManager(); <del> } <del> <del> private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) { <del> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier); <del> if (txManager == null) { <del> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType( <del> this.beanFactory, PlatformTransactionManager.class, qualifier); <del> this.transactionManagerCache.putIfAbsent(qualifier, txManager); <add> else { <add> PlatformTransactionManager defaultTransactionManager = getTransactionManager(); <add> if (defaultTransactionManager == null) { <add> defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class); <add> this.transactionManagerCache.putIfAbsent( <add> DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager); <add> } <add> return defaultTransactionManager; <ide> } <del> return txManager; <ide> } <ide> <ide> /**
1
Text
Text
remove outdated readme
1044b124a56e023e69b0ad82931019aacb0aff93
<ide><path>README-zh-CN.md <del>[![Next.js](https://assets.zeit.co/image/upload/v1538361091/repositories/next-js/next-js.png)](https://nextjs.org) <del> <del><p align="center"> <del> <a aria-label="ZEIT logo" href="https://github.com/zeit"> <del> <img src="https://img.shields.io/badge/MADE%20BY%20ZEIT-000000.svg?style=for-the-badge&logo=ZEIT&labelColor=000000&logoWidth=20"> <del> </a> <del> <a aria-label="NPM version" href="https://www.npmjs.com/package/next"> <del> <img alt="" src="https://img.shields.io/npm/v/next.svg?style=for-the-badge&labelColor=000000"> <del> </a> <del> <a aria-label="License" href="https://github.com/zeit/next.js/blob/canary/license.md"> <del> <img alt="" src= <del> "https://img.shields.io/npm/l/next.svg?style=for-the-badge&labelColor=000000"> <del> </a> <del> <a aria-label="join us in spectrum" href="https://spectrum.chat/next-js"> <del> <img alt="" src="https://img.shields.io/badge/Join%20the%20community-blueviolet.svg?style=for-the-badge&logo=Next.js&labelColor=000000&logoWidth=20"> <del> </a> <del></p> <del> <del>Next.js 是一个轻量级的 React 服务端渲染应用框架。 <del> <del>**可访问 [nextjs.org/learn](https://nextjs.org/learn) 开始学习 Next.js.** <del> <del>[README in English](https://github.com/zeit/next.js) <del> <del>--- <del> <del><!-- START doctoc generated TOC please keep comment here to allow auto update --> <del><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <del><!-- https://github.com/thlorenz/doctoc --> <del> <del>- [怎么使用](#how-to-use) <del> - [安装](#setup) <del> - [代码自动分割](#automatic-code-splitting) <del> - [CSS](#css) <del> - [支持嵌入样式](#built-in-css-support) <del> - [内嵌样式](#css-in-js) <del> - [使用 CSS / Sass / Less / Stylus files](#importing-css--sass--less--stylus-files) <del> - [静态文件服务(如图像)](#static-file-serving-eg-images) <del> - [`<head>`](#populating-head) <del> - [获取数据以及组件生命周期](#fetching-data-and-component-lifecycle) <del> - [路由](#routing) <del> - [`<Link>` 用法](#with-link) <del> - [URL 对象](#with-url-object) <del> - [替换路由](#replace-instead-of-push-url) <del> - [组件支持点击事件`onClick`](#using-a-component-that-supports-onclick) <del> - [暴露`href`给子元素](#forcing-the-link-to-expose-href-to-its-child) <del> - [禁止滚动到页面顶部](#disabling-the-scroll-changes-to-top-on-page) <del> - [命令式](#imperatively) <del> - [拦截器 `popstate`](#intercepting-popstate) <del> - [URL 对象用法](#with-url-object-1) <del> - [路由事件](#router-events) <del> - [浅层路由](#shallow-routing) <del> - [高阶组件](#using-a-higher-order-component) <del> - [预加载页面](#prefetching-pages) <del> - [`<Link>`用法](#with-link-1) <del> - [命令式 prefetch 写法](#imperatively-1) <del> - [自定义服务端路由](#custom-server-and-routing) <del> - [禁止文件路由](#disabling-file-system-routing) <del> - [动态前缀](#dynamic-assetprefix) <del> - [动态导入](#dynamic-import) <del> - [1. 基础支持 (同样支持 SSR)](#1-basic-usage-also-does-ssr) <del> - [2. 自定义加载组件](#2-with-custom-loading-component) <del> - [3. 禁止使用 SSR](#3-with-no-ssr) <del> - [4. 同时加载多个模块](#4-with-multiple-modules-at-once) <del> - [自定义 `<App>`](#custom-app) <del> - [自定义 `<Document>`](#custom-document) <del> - [自定义错误处理](#custom-error-handling) <del> - [渲染内置错误页面](#reusing-the-built-in-error-page) <del> - [自定义配置](#custom-configuration) <del> - [设置自定义构建目录](#setting-a-custom-build-directory) <del> - [禁止 etag 生成](#disabling-etag-generation) <del> - [配置 onDemandEntries](#configuring-the-ondemandentries) <del> - [配置页面后缀名解析扩展](#configuring-extensions-looked-for-when-resolving-pages-in-pages) <del> - [配置构建 ID](#configuring-the-build-id) <del> - [自定义 webpack 配置](#customizing-webpack-config) <del> - [自定义 babel 配置](#customizing-babel-config) <del> - [暴露配置到服务端和客户端](#exposing-configuration-to-the-server--client-side) <del> - [启动服务选择 hostname](#starting-the-server-on-alternative-hostname) <del> - [CDN 支持前缀](#cdn-support-with-asset-prefix) <del>- [项目部署](#production-deployment) <del>- [浏览器支持](#browser-support) <del>- [导出静态页面](#static-html-export) <del> - [使用](#usage) <del> - [限制](#limitation) <del>- [多 zone](#multi-zones) <del> - [怎么定义一个 zone](#how-to-define-a-zone) <del> - [怎么合并他们](#how-to-merge-them) <del>- [技巧](#recipes) <del>- [FAQ](#faq) <del>- [贡献](#contributing) <del>- [作者](#authors) <del> <del><!-- END doctoc generated TOC please keep comment here to allow auto update --> <del> <del><a id="how-to-use" style="display: none"></a> <del> <del>## 怎么使用 <del> <del><a id="setup" style="display: none"></a> <del> <del>### 安装 <del> <del>在项目文件夹中运行: <del> <del>```bash <del>npm install --save next react react-dom <del>``` <del> <del>将下面脚本添加到 package.json 中: <del> <del>```json <del>{ <del> "scripts": { <del> "dev": "next", <del> "build": "next build", <del> "start": "next start" <del> } <del>} <del>``` <del> <del>下面, 文件系统是主要的 API. 每个`.js` 文件将变成一个路由,自动处理和渲染。 <del> <del>新建 `./pages/index.js` 到你的项目中: <del> <del>```jsx <del>export default () => <div>Welcome to next.js!</div> <del>``` <del> <del>运行 `npm run dev` 命令并打开 `http://localhost:3000`。 要使用其他端口,你可以运行 `npm run dev -- -p <your port here>`. <del> <del>到目前为止,我们做到: <del> <del>- 自动打包编译 (使用 webpack 和 babel) <del>- 热加载 <del>- 以 `./pages`作为服务的渲染和索引 <del>- 静态文件服务. `./public/` 映射到 `/` (可以 [创建一个静态目录](#static-file-serving-eg-images) 在你的项目中) <del> <del>这里有个简单的案例,可以下载看看 [sample app - nextgram](https://github.com/zeit/nextgram) <del> <del><a id="automatic-code-splitting" style="display: none"></a> <del> <del>### 代码自动分割 <del> <del>每个页面只会导入`import`中绑定以及被用到的代码. 这意味着页面不会加载不必要的代码 <del> <del>```jsx <del>import cowsay from 'cowsay-browser' <del> <del>export default () => <pre>{cowsay.say({ text: 'hi there!' })}</pre> <del>``` <del> <del><a id="css" style="display: none"></a> <del> <del>### CSS <del> <del><a id="built-in-css-support" style="display: none"></a> <del> <del>#### 支持嵌入样式 <del> <del><p><details> <del> <summary><b>案例</b></summary> <del> <ul><li><a href="https://github.com/zeit/next.js/tree/canary/examples/basic-css">Basic css</a></li></ul> <del></details></p> <del> <del>我们绑定 [styled-jsx](https://github.com/zeit/styled-jsx) 来生成独立作用域的 CSS. 目标是支持 "shadow CSS",但是 [不支持独立模块作用域的 JS](https://github.com/w3c/webcomponents/issues/71). <del> <del>```jsx <del>export default () => ( <del> <div> <del> Hello world <del> <p>scoped!</p> <del> <style jsx>{` <del> p { <del> color: blue; <del> } <del> div { <del> background: red; <del> } <del> @media (max-width: 600px) { <del> div { <del> background: blue; <del> } <del> } <del> `}</style> <del> <style global jsx>{` <del> body { <del> background: black; <del> } <del> `}</style> <del> </div> <del>) <del>``` <del> <del>想查看更多案例可以点击 [styled-jsx documentation](https://www.npmjs.com/package/styled-jsx). <del> <del><a id="css-in-js" style="display: none"></a> <del> <del>#### 内嵌样式 <del> <del><p><details> <del> <summary> <del> <b>Examples</b> <del> </summary> <del> <ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-glamorous">Glamorous</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul> <del></details></p> <del> <del>有些情况可以使用 CSS 内嵌 JS 写法。如下所示: <del> <del>```jsx <del>export default () => <p style={{ color: 'red' }}>hi there</p> <del>``` <del> <del>更复杂的内嵌样式解决方案,特别是服务端渲染时的样式更改。我们可以通过包裹自定义 Document,来添加样式,案例如下:[custom `<Document>`](#user-content-custom-document) <del> <del><a id="importing-css--sass--less--stylus-files" style="display: none"></a> <del> <del>#### 使用 CSS / Sass / Less / Stylus files <del> <del>支持用`.css`, `.scss`, `.less` or `.styl`,需要配置默认文件 next.config.js,具体可查看下面链接 <del> <del>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css) <del>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) <del>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less) <del>- [@zeit/next-stylus](https://github.com/zeit/next-plugins/tree/master/packages/next-stylus) <del> <del><a id="static-file-serving-eg-images" style="display: none"></a> <del> <del>### 静态文件服务(如图像) <del> <del>在根目录下新建文件夹叫`public`。代码可以通过`/`来引入相关的静态资源。 <del> <del>```jsx <del>export default () => <img src="/my-image.png" alt="my image" /> <del>``` <del> <del>_注意:不要自定义静态文件夹的名字,只能叫`public` ,因为只有这个名字 Next.js 才会把它当作静态资源。_ <del> <del><a id="populating-head" style="display: none"></a> <del> <del>### 生成`<head>` <del> <del>`<head>` <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/head-elements">Head elements</a></li> <del> <li><a href="./examples/layout-component">Layout component</a></li> <del> </ul> <del></details></p> <del> <del>我们设置一个内置组件来装载`<head>`到页面中。 <del> <del>```jsx <del>import Head from 'next/head' <del> <del>export default () => ( <del> <div> <del> <Head> <del> <title>My page title</title> <del> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <del> </Head> <del> <p>Hello world!</p> <del> </div> <del>) <del>``` <del> <del>我们定义`key`属性来避免重复的`<head>`标签,保证`<head>`只渲染一次,如下所示: <del> <del>```jsx <del>import Head from 'next/head' <del>export default () => ( <del> <div> <del> <Head> <del> <title>My page title</title> <del> <meta <del> name="viewport" <del> content="initial-scale=1.0, width=device-width" <del> key="viewport" <del> /> <del> </Head> <del> <Head> <del> <meta <del> name="viewport" <del> content="initial-scale=1.2, width=device-width" <del> key="viewport" <del> /> <del> </Head> <del> <p>Hello world!</p> <del> </div> <del>) <del>``` <del> <del>只有第二个`<meta name="viewport" />`才被渲染。 <del> <del>_注意:在卸载组件时,`<head>`的内容将被清除。请确保每个页面都在其`<head>`定义了所需要的内容,而不是假设其他页面已经加过了_ <del> <del><a id="fetching-data-and-component-lifecycle" style="display: none"></a> <del> <del>### 获取数据以及组件生命周期 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/data-fetch">Data fetch</a></li></ul> <del></details></p> <del> <del>当你需要状态,生命周期钩子或初始数据填充时,你可以导出`React.Component`(而不是上面的无状态函数),如下所示: <del> <del>```jsx <del>import React from 'react' <del> <del>export default class extends React.Component { <del> static async getInitialProps({ req }) { <del> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <del> return { userAgent } <del> } <del> <del> render() { <del> return <div>Hello World {this.props.userAgent}</div> <del> } <del>} <del>``` <del> <del>请注意,当页面渲染时加载数据,我们使用了一个异步静态方法`getInitialProps`。它能异步获取 JS 普通对象,并绑定在`props`上。 <del> <del>当服务渲染时,`getInitialProps`将会把数据序列化,就像`JSON.stringify`。所以确保`getInitialProps`返回的是一个普通 JS 对象,而不是`Date`, `Map` 或 `Set`类型。 <del> <del>当页面初次加载时,`getInitialProps`只会在服务端执行一次。`getInitialProps`只有在路由切换的时候(如`Link`组件跳转或路由自定义跳转)时,客户端的才会被执行。 <del> <del>当页面初始化加载时,`getInitialProps`仅在服务端上执行。只有当路由跳转(`Link`组件跳转或 API 方法跳转)时,客户端才会执行`getInitialProps`。 <del> <del>注意:`getInitialProps`将不能在子组件中使用。只能在`pages`页面中使用。 <del> <del><br/> <del> <del>> 只有服务端用到的模块放在`getInitialProps`里,请确保正确的导入了它们,可参考[import them properly](https://arunoda.me/blog/ssr-and-server-only-modules)。 <del>> 否则会拖慢你的应用速度。 <del> <del><br/> <del> <del>你也可以给无状态组件定义`getInitialProps`: <del> <del>```jsx <del>const Page = ({ stars }) => <div>Next stars: {stars}</div> <del> <del>Page.getInitialProps = async ({ req }) => { <del> const res = await fetch('https://api.github.com/repos/zeit/next.js') <del> const json = await res.json() <del> return { stars: json.stargazers_count } <del>} <del> <del>export default Page <del>``` <del> <del>`getInitialProps`入参对象的属性如下: <del> <del>- `pathname` - URL 的 path 部分 <del>- `query` - URL 的 query 部分,并被解析成对象 <del>- `asPath` - 显示在浏览器中的实际路径(包含查询部分),为`String`类型 <del>- `req` - HTTP 请求对象 (仅限服务器端) <del>- `res` - HTTP 返回对象 (仅限服务器端) <del>- `jsonPageRes` - 获取响应对象(仅限客户端) <del>- `err` - 渲染过程中的任何错误 <del> <del><a id="routing" style="display: none"></a> <del> <del>### 路由 <del> <del>Next.js 不会随应用程序中每个可能的路由一起发布路由清单,因此当前页面不知道客户端上的任何其他页面。出于可扩展性考虑,所有后续路由都会惰性加载。 <del> <del><a id="with-link" style="display: none"></a> <del> <del>#### `<Link>`用法 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/hello-world">Hello World</a></li> <del> </ul> <del></details></p> <del> <del>可以用 `<Link>` 组件实现客户端的路由切换。 <del> <del>**基本例子** <del> <del>参考下面的两个页面: <del> <del>```jsx <del>// pages/index.js <del>import Link from 'next/link' <del> <del>function Home() { <del> return ( <del> <div> <del> Click{' '} <del> <Link href="/about"> <del> <a>here</a> <del> </Link>{' '} <del> to read more <del> </div> <del> ) <del>} <del> <del>export default Home <del>``` <del> <del>```jsx <del>// pages/about.js <del>function About() { <del> return <p>Welcome to About!</p> <del>} <del> <del>export default About <del>``` <del> <del>**自定义路由 (使用 URL 中的 props)** <del> <del>`<Link>` 组件有两个主要属性: <del> <del>- `href`: `pages`目录内的路径+查询字符串. <del>- `as`: 将在浏览器 URL 栏中呈现的路径. <del> <del>例子: <del> <del>1. 假设你有个这样的路由 `/post/:slug`. <del> <del>2. 你可以创建文件 `pages/post.js` <del> <del>```jsx <del>class Post extends React.Component { <del> static async getInitialProps({ query }) { <del> console.log('SLUG', query.slug) <del> return {} <del> } <del> render() { <del> return <h1>My blog post</h1> <del> } <del>} <del> <del>export default Post <del>``` <del> <del>3. 将路由添加到 `express` (或者其他服务端) 的 `server.js` 文件 (这仅适用于 SSR). 这将解析`/post/:slug`到`pages/post.js`并在 getInitialProps 中提供`slug`作为查询的一部分。 <del> <del>```jsx <del>server.get('/post/:slug', (req, res) => { <del> return app.render(req, res, '/post', { slug: req.params.slug }) <del>}) <del>``` <del> <del>4. 对于客户端路由,使用 `next/link`: <del> <del>```jsx <del><Link href="/post?slug=something" as="/post/something"> <del>``` <del> <del>_注意:可以使用[`<Link prefetch>`](#prefetching-pages)使链接和预加载在后台同时进行,来达到页面的最佳性能。_ <del> <del>客户端路由行为与浏览器很相似: <del> <del>1. 获取组件 <del>2. 如果组件定义了`getInitialProps`,则获取数据。如果有错误情况将会渲染 `_error.js`。 <del>3. 1 和 2 都完成了,`pushState`执行,新组件被渲染。 <del> <del>如果需要注入`pathname`, `query` 或 `asPath`到你组件中,你可以使用[withRouter](#using-a-higher-order-component)。 <del> <del><a id="with-url-object" style="display: none"></a> <del> <del>##### URL 对象 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/with-url-object-routing">With URL Object Routing</a></li> <del> </ul> <del></details></p> <del> <del>组件`<Link>`接收 URL 对象,而且它会自动格式化生成 URL 字符串 <del> <del>```jsx <del>// pages/index.js <del>import Link from 'next/link' <del> <del>export default () => ( <del> <div> <del> Click{' '} <del> <Link href={{ pathname: '/about', query: { name: 'Zeit' } }}> <del> <a>here</a> <del> </Link>{' '} <del> to read more <del> </div> <del>) <del>``` <del> <del>将生成 URL 字符串`/about?name=Zeit`,你可以使用任何在[Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects)定义过的属性。 <del> <del><a id="replace-instead-of-push-url" style="display: none"></a> <del> <del>##### 替换路由 <del> <del>`<Link>`组件默认将新 url 推入路由栈中。你可以使用`replace`属性来防止添加新输入。 <del> <del>```jsx <del>// pages/index.js <del>import Link from 'next/link' <del> <del>export default () => ( <del> <div> <del> Click{' '} <del> <Link href="/about" replace> <del> <a>here</a> <del> </Link>{' '} <del> to read more <del> </div> <del>) <del>``` <del> <del><a id="using-a-component-that-supports-onclick" style="display: none"></a> <del> <del>##### 组件支持点击事件 `onClick` <del> <del>`<Link>`支持每个组件所支持的`onClick`事件。如果你不提供`<a>`标签,只会处理`onClick`事件而`href`将不起作用。 <del> <del>```jsx <del>// pages/index.js <del>import Link from 'next/link' <del> <del>export default () => ( <del> <div> <del> Click{' '} <del> <Link href="/about"> <del> <img src="/static/image.png" alt="image" /> <del> </Link> <del> </div> <del>) <del>``` <del> <del><a id="forcing-the-link-to-expose-href-to-its-child" style="display: none"></a> <del> <del>##### 暴露 `href` 给子元素 <del> <del>如子元素是一个没有 href 属性的`<a>`标签,我们将会指定它以免用户重复操作。然而有些时候,我们需要里面有`<a>`标签,但是`Link`组件不会被识别成*超链接*,结果不能将`href`传递给子元素。在这种场景下,你可以定义一个`Link`组件中的布尔属性`passHref`,强制将`href`传递给子元素。 <del> <del>**注意**: 使用`a`之外的标签而且没有通过`passHref`的链接可能会使导航看上去正确,但是当搜索引擎爬行检测时,将不会识别成链接(由于缺乏 href 属性),这会对你网站的 SEO 产生负面影响。 <del> <del>```jsx <del>import Link from 'next/link' <del>import Unexpected_A from 'third-library' <del> <del>export default ({ href, name }) => ( <del> <Link href={href} passHref> <del> <Unexpected_A>{name}</Unexpected_A> <del> </Link> <del>) <del>``` <del> <del><a id="disabling-the-scroll-changes-to-top-on-page" style="display: none"></a> <del> <del>##### 禁止滚动到页面顶部 <del> <del>`<Link>`的默认行为就是滚到页面顶部。当有 hash 定义时(#),页面将会滚动到对应的 id 上,就像`<a>`标签一样。为了预防滚动到顶部,可以给`<Link>`加 <del>`scroll={false}`属性: <del> <del>```jsx <del><Link scroll={false} href="/?counter=10"><a>Disables scrolling</a></Link> <del><Link href="/?counter=10"><a>Changes with scrolling to top</a></Link> <del>``` <del> <del><a id="imperatively" style="display: none"></a> <del> <del>#### 命令式 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/using-router">Basic routing</a></li> <del> <li><a href="./examples/with-loading">With a page loading indicator</a></li> <del> </ul> <del></details></p> <del> <del>你也可以用`next/router`实现客户端路由切换 <del> <del>```jsx <del>import Router from 'next/router' <del> <del>export default () => ( <del> <div> <del> Click <span onClick={() => Router.push('/about')}>here</span> to read more <del> </div> <del>) <del>``` <del> <del><a id="intercepting-popstate" style="display: none"></a> <del> <del>#### 拦截器 `popstate` <del> <del>有些情况(比如使用[custom router](#custom-server-and-routing)),你可能想监听[`popstate`](https://developer.mozilla.org/en-US/docs/Web/Events/popstate),在路由跳转前做一些动作。 <del>比如,你可以操作 request 或强制 SSR 刷新 <del> <del>```jsx <del>import Router from 'next/router' <del> <del>Router.beforePopState(({ url, as, options }) => { <del> // I only want to allow these two routes! <del> if (as !== '/' || as !== '/other') { <del> // Have SSR render bad routes as a 404. <del> window.location.href = as <del> return false <del> } <del> <del> return true <del>}) <del>``` <del> <del>如果你在`beforePopState`中返回 false,`Router`将不会执行`popstate`事件。 <del>例如[Disabling File-System Routing](#disabling-file-system-routing)。 <del> <del>以上`Router`对象的 API 如下: <del> <del>- `route` - 当前路由,为`String`类型 <del>- `pathname` - 不包含查询内容的当前路径,为`String`类型 <del>- `query` - 查询内容,被解析成`Object`类型. 默认为`{}` <del>- `asPath` - 展现在浏览器上的实际路径,包含查询内容,为`String`类型 <del>- `push(url, as=url)` - 用给定的 url 调用`pushState` <del>- `replace(url, as=url)` - 用给定的 url 调用`replaceState` <del>- `beforePopState(cb=function)` - 在路由器处理事件之前拦截. <del> <del>`push` 和 `replace` 函数的第二个参数`as`,是为了装饰 URL 作用。如果你在服务器端设置了自定义路由将会起作用。 <del> <del><a id="with-url-object-1" style="display: none"></a> <del> <del>##### URL 对象用法 <del> <del>`push` 或 `replace`可接收的 URL 对象(`<Link>`组件的 URL 对象一样)来生成 URL。 <del> <del>```jsx <del>import Router from 'next/router' <del> <del>const handler = () => <del> Router.push({ <del> pathname: '/about', <del> query: { name: 'Zeit' }, <del> }) <del> <del>export default () => ( <del> <div> <del> Click <span onClick={handler}>here</span> to read more <del> </div> <del>) <del>``` <del> <del>也可以像`<Link>`组件一样添加额外的参数。 <del> <del><a id="router-events" style="display: none"></a> <del> <del>##### 路由事件 <del> <del>你可以监听路由相关事件。 <del>下面是支持的事件列表: <del> <del>- `routeChangeStart(url)` - 路由开始切换时触发 <del>- `routeChangeComplete(url)` - 完成路由切换时触发 <del>- `routeChangeError(err, url)` - 路由切换报错时触发 <del>- `beforeHistoryChange(url)` - 浏览器 history 模式开始切换时触发 <del>- `hashChangeStart(url)` - 开始切换 hash 值但是没有切换页面路由时触发 <del>- `hashChangeComplete(url)` - 完成切换 hash 值但是没有切换页面路由时触发 <del> <del>> 这里的`url`是指显示在浏览器中的 url。如果你用了`Router.push(url, as)`(或类似的方法),那浏览器中的 url 将会显示 as 的值。 <del> <del>下面是如何正确使用路由事件`routeChangeStart`的例子: <del> <del>```js <del>const handleRouteChange = url => { <del> console.log('App is changing to: ', url) <del>} <del> <del>Router.events.on('routeChangeStart', handleRouteChange) <del>``` <del> <del>如果你不想再监听该事件,你可以用`off`事件去取消监听: <del> <del>```js <del>Router.events.off('routeChangeStart', handleRouteChange) <del>``` <del> <del>如果路由加载被取消(比如快速连续双击链接),`routeChangeError`将触发。传递 err,并且属性 cancelled 的值为 true。 <del> <del>```js <del>Router.events.on('routeChangeError', (err, url) => { <del> if (err.cancelled) { <del> console.log(`Route to ${url} was cancelled!`) <del> } <del>}) <del>``` <del> <del><a id="shallow-routing" style="display: none"></a> <del> <del>##### 浅层路由 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/with-shallow-routing">Shallow Routing</a></li> <del> </ul> <del></details></p> <del> <del>浅层路由允许你改变 URL 但是不执行`getInitialProps`生命周期。你可以加载相同页面的 URL,得到更新后的路由属性`pathname`和`query`,并不失去 state 状态。 <del> <del>你可以给`Router.push` 或 `Router.replace`方法加`shallow: true`参数。如下面的例子所示: <del> <del>```js <del>// Current URL is "/" <del>const href = '/?counter=10' <del>const as = href <del>Router.push(href, as, { shallow: true }) <del>``` <del> <del>现在 URL 更新为`/?counter=10`。在组件里查看`this.props.router.query`你将会看到更新的 URL。 <del> <del>你可以在[`componentdidupdate`](https://facebook.github.io/react/docs/react-component.html#componentdidupdate)钩子函数中监听 URL 的变化。 <del> <del>```js <del>componentDidUpdate(prevProps) { <del> const { pathname, query } = this.props.router <del> // verify props have changed to avoid an infinite loop <del> if (query.id !== prevProps.router.query.id) { <del> // fetch data based on the new query <del> } <del>} <del>``` <del> <del>> 注意: <del>> <del>> 浅层路由只作用于相同 URL 的参数改变,比如我们假定有个其他路由`about`,而你向下面代码样运行: <del>> <del>> ```js <del>> Router.push('/?counter=10', '/about?counter=10', { shallow: true }) <del>> ``` <del>> <del>> 那么这将会出现新页面,即使我们加了浅层路由,但是它还是会卸载当前页,会加载新的页面并触发新页面的`getInitialProps`。 <del> <del><a id="using-a-higher-order-component" style="display: none"></a> <del> <del>#### 高阶组件 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/using-with-router">Using the `withRouter` utility</a></li> <del> </ul> <del></details></p> <del> <del>如果你想应用里每个组件都处理路由对象,你可以使用`withRouter`高阶组件。下面是如何使用它: <del> <del>```jsx <del>import { withRouter } from 'next/router' <del> <del>const ActiveLink = ({ children, router, href }) => { <del> const style = { <del> marginRight: 10, <del> color: router.pathname === href ? 'red' : 'black', <del> } <del> <del> const handleClick = e => { <del> e.preventDefault() <del> router.push(href) <del> } <del> <del> return ( <del> <a href={href} onClick={handleClick} style={style}> <del> {children} <del> </a> <del> ) <del>} <del> <del>export default withRouter(ActiveLink) <del>``` <del> <del>上面路由对象的 API 可以参考[`next/router`](#imperatively). <del> <del><a id="prefetching-pages" style="display: none"></a> <del> <del>### 预加载页面 <del> <del>⚠️ 只有生产环境才有此功能 ⚠️ <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-prefetching">Prefetching</a></li></ul> <del></details></p> <del> <del>Next.js 有允许你预加载页面的 API。 <del> <del>用 Next.js 服务端渲染你的页面,可以达到所有你应用里所有未来会跳转的路径即时响应,有效的应用 Next.js,可以通过预加载应用程序的功能,最大程度的初始化网站性能。[查看更多](https://zeit.co/blog/next#anticipation-is-the-key-to-performance). <del> <del>> Next.js 的预加载功能只预加载 JS 代码。当页面渲染时,你可能需要等待数据请求。 <del> <del><a id="with-link-1" style="display: none"></a> <del> <del>#### `<Link>`用法 <del> <del>你可以给<Link>添加 `prefetch` 属性,Next.js 将会在后台预加载这些页面。 <del> <del>```jsx <del>import Link from 'next/link' <del> <del>// example header component <del>export default () => ( <del> <nav> <del> <ul> <del> <li> <del> <Link prefetch href="/"> <del> <a>Home</a> <del> </Link> <del> </li> <del> <li> <del> <Link prefetch href="/about"> <del> <a>About</a> <del> </Link> <del> </li> <del> <li> <del> <Link prefetch href="/contact"> <del> <a>Contact</a> <del> </Link> <del> </li> <del> </ul> <del> </nav> <del>) <del>``` <del> <del><a id="imperatively-1" style="display: none"></a> <del> <del>#### 命令式 prefetch 写法 <del> <del>大多数预加载是通过<Link />处理的,但是我们还提供了命令式 API 用于更复杂的场景。 <del> <del>```jsx <del>import { withRouter } from 'next/router' <del> <del>export default withRouter(({ router }) => ( <del> <div> <del> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}> <del> A route transition will happen after 100ms <del> </a> <del> {// but we can prefetch it! <del> router.prefetch('/dynamic')} <del> </div> <del>)) <del>``` <del> <del>路由实例只允许在应用程序的客户端。以防服务端渲染发生错误,建议 prefetch 事件写在`componentDidMount()`生命周期里。 <del> <del>```jsx <del>import React from 'react' <del>import { withRouter } from 'next/router' <del> <del>class MyLink extends React.Component { <del> componentDidMount() { <del> const { router } = this.props <del> router.prefetch('/dynamic') <del> } <del> <del> render() { <del> const { router } = this.props <del> return ( <del> <div> <del> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}> <del> A route transition will happen after 100ms <del> </a> <del> </div> <del> ) <del> } <del>} <del> <del>export default withRouter(MyLink) <del>``` <del> <del><a id="custom-server-and-routing" style="display: none"></a> <del> <del>### 自定义服务端路由 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/custom-server">Basic custom server</a></li> <del> <li><a href="./examples/custom-server-express">Express integration</a></li> <del> <li><a href="./examples/custom-server-hapi">Hapi integration</a></li> <del> <li><a href="./examples/custom-server-koa">Koa integration</a></li> <del> <li><a href="./examples/parameterized-routing">Parameterized routing</a></li> <del> <li><a href="./examples/ssr-caching">SSR caching</a></li> <del> </ul> <del></details></p> <del> <del>一般你使用`next start`命令来启动 next 服务,你还可以编写代码来自定义路由,如使用路由正则等。 <del> <del>当使用自定义服务文件,如下面例子所示叫 server.js 时,确保你更新了 package.json 中的脚本。 <del> <del>```json <del>{ <del> "scripts": { <del> "dev": "node server.js", <del> "build": "next build", <del> "start": "NODE_ENV=production node server.js" <del> } <del>} <del>``` <del> <del>下面这个例子使 `/a` 路由解析为`./pages/b`,以及`/b` 路由解析为`./pages/a`; <del> <del>```js <del>// This file doesn't go through babel or webpack transformation. <del>// Make sure the syntax and sources this file requires are compatible with the current node version you are running <del>// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel <del>const { createServer } = require('http') <del>const { parse } = require('url') <del>const next = require('next') <del> <del>const dev = process.env.NODE_ENV !== 'production' <del>const app = next({ dev }) <del>const handle = app.getRequestHandler() <del> <del>app.prepare().then(() => { <del> createServer((req, res) => { <del> // Be sure to pass `true` as the second argument to `url.parse`. <del> // This tells it to parse the query portion of the URL. <del> const parsedUrl = parse(req.url, true) <del> const { pathname, query } = parsedUrl <del> <del> if (pathname === '/a') { <del> app.render(req, res, '/b', query) <del> } else if (pathname === '/b') { <del> app.render(req, res, '/a', query) <del> } else { <del> handle(req, res, parsedUrl) <del> } <del> }).listen(3000, err => { <del> if (err) throw err <del> console.log('> Ready on http://localhost:3000') <del> }) <del>}) <del>``` <del> <del>`next`的 API 如下所示 <del> <del>- `next(opts: object)` <del> <del>opts 的属性如下: <del> <del>- `dev` (`boolean`) 判断 Next.js 应用是否在开发环境 - 默认`false` <del>- `dir` (`string`) Next 项目路径 - 默认`'.'` <del>- `quiet` (`boolean`) 是否隐藏包含服务端消息在内的错误信息 - 默认`false` <del>- `conf` (`object`) 与`next.config.js`的对象相同 - 默认`{}` <del> <del>生产环境的话,可以更改 package.json 里的`start`脚本为`NODE_ENV=production node server.js`。 <del> <del><a id="disabling-file-system-routing" style="display: none"></a> <del> <del>#### 禁止文件路由 <del> <del>默认情况,`Next`将会把`/pages`下的所有文件匹配路由(如`/pages/some-file.js` 渲染为 `site.com/some-file`) <del> <del>如果你的项目使用自定义路由,那么有可能不同的路由会得到相同的内容,可以优化 SEO 和用户体验。 <del> <del>禁止路由链接到`/pages`下的文件,只需设置`next.config.js`文件如下所示: <del> <del>```js <del>// next.config.js <del>module.exports = { <del> useFileSystemPublicRoutes: false, <del>} <del>``` <del> <del>注意`useFileSystemPublicRoutes`只禁止服务端的文件路由;但是客户端的还是禁止不了。 <del> <del>你如果想配置客户端路由不能跳转文件路由,可以参考[Intercepting `popstate`](#intercepting-popstate)。 <del> <del><a id="dynamic-assetprefix" style="display: none"></a> <del> <del>#### 动态前缀 <del> <del>有时你需要设置动态前缀,可以在请求时设置`assetPrefix`改变前缀。 <del> <del>使用方法如下: <del> <del>```js <del>const next = require('next') <del>const micro = require('micro') <del> <del>const dev = process.env.NODE_ENV !== 'production' <del>const app = next({ dev }) <del>const handleNextRequests = app.getRequestHandler() <del> <del>app.prepare().then(() => { <del> const server = micro((req, res) => { <del> // Add assetPrefix support based on the hostname <del> if (req.headers.host === 'my-app.com') { <del> app.setAssetPrefix('http://cdn.com/myapp') <del> } else { <del> app.setAssetPrefix('') <del> } <del> <del> handleNextRequests(req, res) <del> }) <del> <del> server.listen(port, err => { <del> if (err) { <del> throw err <del> } <del> <del> console.log(`> Ready on http://localhost:${port}`) <del> }) <del>}) <del>``` <del> <del><a id="dynamic-import" style="display: none"></a> <del> <del>### 动态导入 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="./examples/with-dynamic-import">With Dynamic Import</a></li> <del> </ul> <del></details></p> <del> <del>ext.js 支持 JavaScript 的 TC39 提议[dynamic import proposal](https://github.com/tc39/proposal-dynamic-import)。你可以动态导入 JavaScript 模块(如 React 组件)。 <del> <del>动态导入相当于把代码分成各个块管理。Next.js 服务端动态导入功能,你可以做很多炫酷事情。 <del> <del>下面介绍一些动态导入方式: <del> <del><a id="1-basic-usage-also-does-ssr" style="display: none"></a> <del> <del>#### 1. 基础用法 (也就是 SSR) <del> <del>```jsx <del>import dynamic from 'next/dynamic' <del> <del>const DynamicComponent = dynamic(import('../components/hello')) <del> <del>export default () => ( <del> <div> <del> <Header /> <del> <DynamicComponent /> <del> <p>HOME PAGE is here!</p> <del> </div> <del>) <del>``` <del> <del><a id="2-with-custom-loading-componen" style="display: none"></a> <del> <del>#### 2. 自定义加载组件 <del> <del>```jsx <del>import dynamic from 'next/dynamic' <del> <del>const DynamicComponentWithCustomLoading = dynamic( <del> import('../components/hello2'), <del> { <del> loading: () => <p>...</p>, <del> } <del>) <del> <del>export default () => ( <del> <div> <del> <Header /> <del> <DynamicComponentWithCustomLoading /> <del> <p>HOME PAGE is here!</p> <del> </div> <del>) <del>``` <del> <del><a id="3-with-no-ssr" style="display: none"></a> <del> <del>#### 3. 禁止使用 SSR <del> <del>```jsx <del>import dynamic from 'next/dynamic' <del> <del>const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), { <del> ssr: false, <del>}) <del> <del>export default () => ( <del> <div> <del> <Header /> <del> <DynamicComponentWithNoSSR /> <del> <p>HOME PAGE is here!</p> <del> </div> <del>) <del>``` <del> <del><a id="4-with-multiple-modules-at-once" style="display: none"></a> <del> <del>#### 4. 同时加载多个模块 <del> <del>```jsx <del>import dynamic from 'next/dynamic' <del> <del>const HelloBundle = dynamic({ <del> modules: () => { <del> const components = { <del> Hello1: import('../components/hello1'), <del> Hello2: import('../components/hello2'), <del> } <del> <del> return components <del> }, <del> render: (props, { Hello1, Hello2 }) => ( <del> <div> <del> <h1>{props.title}</h1> <del> <Hello1 /> <del> <Hello2 /> <del> </div> <del> ), <del>}) <del> <del>export default () => <HelloBundle title="Dynamic Bundle" /> <del>``` <del> <del><a id="custom-app" style="display: none"></a> <del> <del>### 自定义 `<App>` <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-app-layout">Using `_app.js` for layout</a></li></ul> <del> <ul><li><a href="./examples/with-componentdidcatch">Using `_app.js` to override `componentDidCatch`</a></li></ul> <del></details></p> <del> <del>组件来初始化页面。你可以重写它来控制页面初始化,如下面的事: <del> <del>- 当页面变化时保持页面布局 <del>- 当路由变化时保持页面状态 <del>- 使用`componentDidCatch`自定义处理错误 <del>- 注入额外数据到页面里 (如 GraphQL 查询) <del> <del>重写的话,新建`./pages/_app.js`文件,重写 App 模块如下所示: <del> <del>```js <del>import App, { Container } from 'next/app' <del>import React from 'react' <del> <del>export default class MyApp extends App { <del> static async getInitialProps({ Component, router, ctx }) { <del> let pageProps = {} <del> <del> if (Component.getInitialProps) { <del> pageProps = await Component.getInitialProps(ctx) <del> } <del> <del> return { pageProps } <del> } <del> <del> render() { <del> const { Component, pageProps } = this.props <del> return ( <del> <Container> <del> <Component {...pageProps} /> <del> </Container> <del> ) <del> } <del>} <del>``` <del> <del><a id="custom-document" style="display: none"></a> <del> <del>### 自定义 `<Document>` <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-styled-components">Styled components custom document</a></li></ul> <del> <ul><li><a href="./examples/with-amp">Google AMP</a></li></ul> <del></details></p> <del> <del>- 在服务端呈现 <del>- 初始化服务端时添加文档标记元素 <del>- 通常实现服务端渲染会使用一些 css-in-js 库,如[styled-components](./examples/with-styled-components), [glamorous](./examples/with-glamorous) 或 [emotion](with-emotion)。[styled-jsx](https://github.com/zeit/styled-jsx)是 Next.js 自带默认使用的 css-in-js 库 <del> <del>`Next.js`会自动定义文档标记,比如,你从来不需要添加`<html>`, `<body>`等。如果想自定义文档标记,你可以新建`./pages/_document.js`,然后扩展`Document`类: <del> <del>```jsx <del>// _document is only rendered on the server side and not on the client side <del>// Event handlers like onClick can't be added to this file <del> <del>// ./pages/_document.js <del>import Document, { Head, Main, NextScript } from 'next/document' <del> <del>export default class MyDocument extends Document { <del> static async getInitialProps(ctx) { <del> const initialProps = await Document.getInitialProps(ctx) <del> return { ...initialProps } <del> } <del> <del> render() { <del> return ( <del> <html> <del> <Head> <del> <style>{`body { margin: 0 } /* custom! */`}</style> <del> </Head> <del> <body className="custom_class"> <del> <Main /> <del> <NextScript /> <del> </body> <del> </html> <del> ) <del> } <del>} <del>``` <del> <del>钩子[`getInitialProps`](#fetching-data-and-component-lifecycle)接收到的参数`ctx`对象都是一样的 <del> <del>- 回调函数`renderPage`是会执行 React 渲染逻辑的函数(同步),这种做法有助于此函数支持一些类似于 Aphrodite 的 renderStatic 等一些服务器端渲染容器。 <del> <del>**注意:`<Main />`外的 React 组件将不会渲染到浏览器中,所以那添加应用逻辑代码。如果你页面需要公共组件(菜单或工具栏),可以参照上面说的`App`组件代替。** <del> <del><a id="custom-error-handling" style="display: none"></a> <del> <del>#### 自定义 `renderPage` <del> <del>🚧 应该注意的是,您应该定制“renderPage”的唯一原因是使用 css-in-js 库,需要将应用程序包装起来以正确使用服务端渲染。 🚧 <del> <del>- 它将一个选项对象作为参数进行进一步的自定义: <del> <del>```js <del>import Document from 'next/document' <del> <del>class MyDocument extends Document { <del> static async getInitialProps(ctx) { <del> const originalRenderPage = ctx.renderPage <del> <del> ctx.renderPage = () => <del> originalRenderPage({ <del> // useful for wrapping the whole react tree <del> enhanceApp: App => App, <del> // useful for wrapping in a per-page basis <del> enhanceComponent: Component => Component, <del> }) <del> <del> // Run the parent `getInitialProps` using `ctx` that now includes our custom `renderPage` <del> const initialProps = await Document.getInitialProps(ctx) <del> <del> return initialProps <del> } <del>} <del> <del>export default MyDocument <del>``` <del> <del>### 自定义错误处理 <del> <del>404 和 500 错误客户端和服务端都会通过`error.js`组件处理。如果你想改写它,则新建`_error.js`在文件夹中: <del> <del>⚠️ 该`pages/_error.js`组件仅用于生产。在开发过程中,您会收到调用堆栈错误,以了解错误源自何处。 ⚠️ <del> <del>```jsx <del>import React from 'react' <del> <del>export default class Error extends React.Component { <del> static getInitialProps({ res, err }) { <del> const statusCode = res ? res.statusCode : err ? err.statusCode : null <del> return { statusCode } <del> } <del> <del> render() { <del> return ( <del> <p> <del> {this.props.statusCode <del> ? `An error ${this.props.statusCode} occurred on server` <del> : 'An error occurred on client'} <del> </p> <del> ) <del> } <del>} <del>``` <del> <del><a id="reusing-the-built-in-error-page" style="display: none"></a> <del> <del>### 渲染内置错误页面 <del> <del>如果你想渲染内置错误页面,你可以使用`next/error`: <del> <del>```jsx <del>import React from 'react' <del>import Error from 'next/error' <del>import fetch from 'isomorphic-unfetch' <del> <del>export default class Page extends React.Component { <del> static async getInitialProps() { <del> const res = await fetch('https://api.github.com/repos/zeit/next.js') <del> const statusCode = res.statusCode > 200 ? res.statusCode : false <del> const json = await res.json() <del> <del> return { statusCode, stars: json.stargazers_count } <del> } <del> <del> render() { <del> if (this.props.statusCode) { <del> return <Error statusCode={this.props.statusCode} /> <del> } <del> <del> return <div>Next stars: {this.props.stars}</div> <del> } <del>} <del>``` <del> <del>> 如果你自定义了个错误页面,你可以引入自己的错误页面来代替`next/error` <del> <del><a id="custom-configuration" style="display: none"></a> <del> <del>### 自定义配置 <del> <del>如果你想自定义 Next.js 的高级配置,可以在根目录下新建`next.config.js`文件(与`pages/` 和 `package.json`一起) <del> <del>注意:`next.config.js`是一个 Node.js 模块,不是一个 JSON 文件,可以用于 Next 启动服务已经构建阶段,但是不作用于浏览器端。 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> /* config options here */ <del>} <del>``` <del> <del>或使用一个函数: <del> <del>```js <del>module.exports = (phase, { defaultConfig }) => { <del> // <del> // https://github.com/zeit/ <del> return { <del> /* config options here */ <del> } <del>} <del>``` <del> <del>`phase`是配置文件被加载时的当前内容。你可看到所有的 phases 常量:[constants](./lib/constants.js) <del>这些常量可以通过`next/constants`引入: <del> <del>```js <del>const { PHASE_DEVELOPMENT_SERVER } = require('next/constants') <del>module.exports = (phase, { defaultConfig }) => { <del> if (phase === PHASE_DEVELOPMENT_SERVER) { <del> return { <del> /* development only config options here */ <del> } <del> } <del> <del> return { <del> /* config options for all phases except development here */ <del> } <del>} <del>``` <del> <del><a id="setting-a-custom-build-directory" style="display: none"></a> <del> <del>#### 设置自定义构建目录 <del> <del>你可以自定义一个构建目录,如新建`build`文件夹来代替`.next` 文件夹成为构建目录。如果没有配置构建目录,构建时将会自动新建`.next`文件夹 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> distDir: 'build', <del>} <del>``` <del> <del><a id="disabling-etag-generation" style="display: none"></a> <del> <del>#### 禁止 etag 生成 <del> <del>你可以禁止 etag 生成根据你的缓存策略。如果没有配置,Next 将会生成 etags 到每个页面中。 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> generateEtags: false, <del>} <del>``` <del> <del><a id="configuring-the-ondemandentries" style="display: none"></a> <del> <del>#### 配置 onDemandEntries <del> <del>Next 暴露一些选项来给你控制服务器部署以及缓存页面: <del> <del>```js <del>module.exports = { <del> onDemandEntries: { <del> // period (in ms) where the server will keep pages in the buffer <del> maxInactiveAge: 25 * 1000, <del> // number of pages that should be kept simultaneously without being disposed <del> pagesBufferLength: 2, <del> }, <del>} <del>``` <del> <del>这个只是在开发环境才有的功能。如果你在生成环境中想缓存 SSR 页面,请查看[SSR-caching](https://github.com/zeit/next.js/tree/canary/examples/ssr-caching) <del> <del><a id="configuring-extensions-looked-for-when-resolving-pages-in-pages" style="display: none"></a> <del> <del>#### 配置解析路由时的页面文件后缀名 <del> <del>如 typescript 模块[`@zeit/next-typescript`](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript),需要支持解析后缀名为`.ts`的文件。`pageExtensions` 允许你扩展后缀名来解析各种 pages 下的文件。 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> pageExtensions: ['jsx', 'js'], <del>} <del>``` <del> <del><a id="configuring-the-build-id" style="display: none"></a> <del> <del>#### 配置构建 ID <del> <del>Next.js 使用构建时生成的常量来标识你的应用服务是哪个版本。在每台服务器上运行构建命令时,可能会导致多服务器部署出现问题。为了保持同一个构建 ID,可以配置`generateBuildId`函数: <del> <del>```js <del>// next.config.js <del>module.exports = { <del> generateBuildId: async () => { <del> // For example get the latest git commit hash here <del> return 'my-build-id' <del> }, <del>} <del>``` <del> <del><a id="customizing-webpack-config" style="display: none"></a> <del> <del>### 自定义 webpack 配置 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-webpack-bundle-analyzer">Custom webpack bundle analyzer</a></li></ul> <del></details></p> <del> <del>可以使用些一些常见的模块 <del> <del>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css) <del>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) <del>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less) <del>- [@zeit/next-preact](https://github.com/zeit/next-plugins/tree/master/packages/next-preact) <del>- [@zeit/next-typescript](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript) <del> <del>_注意: `webpack`方法将被执行两次,一次在服务端一次在客户端。你可以用`isServer`属性区分客户端和服务端来配置_ <del> <del>多配置可以组合在一起,如: <del> <del>```js <del>const withTypescript = require('@zeit/next-typescript') <del>const withSass = require('@zeit/next-sass') <del> <del>module.exports = withTypescript( <del> withSass({ <del> webpack(config, options) { <del> // Further custom configuration here <del> return config <del> }, <del> }) <del>) <del>``` <del> <del>为了扩展`webpack`使用,可以在`next.config.js`定义函数。 <del> <del>```js <del>// next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js. <del> <del>module.exports = { <del> webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { <del> // Perform customizations to webpack config <del> // Important: return the modified config <del> return config <del> }, <del> webpackDevMiddleware: config => { <del> // Perform customizations to webpack dev middleware config <del> // Important: return the modified config <del> return config <del> }, <del>} <del>``` <del> <del>`webpack`的第二个参数是个对象,你可以自定义配置它,对象属性如下所示: <del> <del>- `buildId` - 字符串类型,构建的唯一标示 <del>- `dev` - `Boolean`型,判断你是否在开发环境下 <del>- `isServer` - `Boolean` 型,为`true`使用在服务端, 为`false`使用在客户端. <del>- `defaultLoaders` - 对象型 ,内部加载器, 你可以如下配置 <del> - `babel` - 对象型,配置`babel-loader`. <del> <del>`defaultLoaders.babel`使用案例如下: <del> <del>```js <del>// Example next.config.js for adding a loader that depends on babel-loader <del>// This source was taken from the @zeit/next-mdx plugin source: <del>// https://github.com/zeit/next-plugins/blob/master/packages/next-mdx <del>module.exports = { <del> webpack: (config, {}) => { <del> config.module.rules.push({ <del> test: /\.mdx/, <del> use: [ <del> options.defaultLoaders.babel, <del> { <del> loader: '@mdx-js/loader', <del> options: pluginOptions.options, <del> }, <del> ], <del> }) <del> <del> return config <del> }, <del>} <del>``` <del> <del><a id="customizing-babel-config" style="display: none"></a> <del> <del>### 自定义 babel 配置 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-custom-babel-config">Custom babel configuration</a></li></ul> <del></details></p> <del> <del>为了扩展方便我们使用`babel`,可以在应用根目录新建`.babelrc`文件,该文件可配置。 <del> <del>如果有该文件,我们将会考虑数据源,因此也需要定义 next 项目需要的东西,也就是 `next/babel`预设。 <del> <del>这种设计方案将会使你不诧异于我们可以定制 babel 配置。 <del> <del>下面是`.babelrc`文件案例: <del> <del>```json <del>{ <del> "presets": ["next/babel"], <del> "plugins": [] <del>} <del>``` <del> <del>`next/babel`预设可处理各种 React 应用所需要的情况。包括: <del> <del>- preset-env <del>- preset-react <del>- plugin-proposal-class-properties <del>- plugin-proposal-object-rest-spread <del>- plugin-transform-runtime <del>- styled-jsx <del> <del>presets / plugins 不允许添加到`.babelrc`中,然而你可以配置`next/babel`预设: <del> <del>```json <del>{ <del> "presets": [ <del> [ <del> "next/babel", <del> { <del> "preset-env": {}, <del> "transform-runtime": {}, <del> "styled-jsx": {}, <del> "class-properties": {} <del> } <del> ] <del> ], <del> "plugins": [] <del>} <del>``` <del> <del>`"preset-env"`模块选项应该保持为 false,否则 webpack 代码分割将被禁用。 <del> <del><a id="exposing-configuration-to-the-server--client-side" style="display: none"></a> <del> <del>### 暴露配置到服务端和客户端 <del> <del>在应用程序中通常需要提供配置值 <del> <del>Next.js 支持 2 种提供配置的方式: <del> <del>- 构建时配置 <del>- 运行时配置 <del> <del>#### 构建时配置 <del> <del>构建时配置的工作方式是将提供的值内联到 Javascript 包中。 <del> <del>你可以在`next.config.js`设置`env`: <del> <del>```js <del>// next.config.js <del>module.exports = { <del> env: { <del> customKey: 'value', <del> }, <del>} <del>``` <del> <del>这将允许你在代码中使用`process.env.customKey`,例如: <del> <del>```jsx <del>// pages/index.js <del>function Index() { <del> return <h1>The value of customKey is: {process.env.customKey}</h1> <del>} <del> <del>export default Index <del>``` <del> <del>#### 运行时配置 <del> <del>> ⚠️ 请注意,使用此选项时不可用 `target: 'serverless'` <del> <del>> ⚠️ 通常,您希望使用构建时配置来提供配置。原因是运行时配置增加了一个小的 rendering/initialization 开销。 <del> <del>`next/config`模块使你应用运行时可以读取些存储在`next.config.js`的配置项。`serverRuntimeConfig`属性只在服务器端可用,`publicRuntimeConfig`属性在服务端和客户端可用。 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> serverRuntimeConfig: { <del> // Will only be available on the server side <del> mySecret: 'secret', <del> secondSecret: process.env.SECOND_SECRET, // Pass through env variables <del> }, <del> publicRuntimeConfig: { <del> // Will be available on both server and client <del> staticFolder: '/static', <del> }, <del>} <del>``` <del> <del>```js <del>// pages/index.js <del>import getConfig from 'next/config' <del>// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else. <del>const { serverRuntimeConfig, publicRuntimeConfig } = getConfig() <del> <del>console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side <del>console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client <del> <del>function MyImage() { <del> return ( <del> <div> <del> <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" /> <del> </div> <del> ) <del>} <del> <del>export default MyImage <del>``` <del> <del>### 启动服务选择 hostname <del> <del>启动开发环境服务可以设置不同的 hostname,你可以在启动命令后面加上`--hostname 主机名` 或 `-H 主机名`。它将会启动一个 TCP 服务器来监听连接所提供的主机。 <del> <del><a id="cdn-support-with-asset-prefix" style="display: none"></a> <del> <del>### CDN 支持前缀 <del> <del>建立一个 CDN,你能配置`assetPrefix`选项,去配置你的 CDN 源。 <del> <del>```js <del>const isProd = process.env.NODE_ENV === 'production' <del>module.exports = { <del> // You may only need to add assetPrefix in the production. <del> assetPrefix: isProd ? 'https://cdn.mydomain.com' : '', <del>} <del>``` <del> <del>注意:Next.js 运行时将会自动添加前缀,但是对于`/static`是没有效果的,如果你想这些静态资源也能使用 CDN,你需要自己添加前缀。有一个方法可以判断你的环境来加前缀,如 [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-build-time)。 <del> <del><a id="production-deployment" style="display: none"></a> <del> <del>## 项目部署 <del> <del>部署中,你可以先构建打包生成环境代码,再启动服务。因此,构建和启动分为下面两条命令: <del> <del>```bash <del>next build <del>next start <del>``` <del> <del>例如,使用[`now`](https://zeit.co/now)去部署`package.json`配置文件如下: <del> <del>```json <del>{ <del> "name": "my-app", <del> "dependencies": { <del> "next": "latest" <del> }, <del> "scripts": { <del> "dev": "next", <del> "build": "next build", <del> "start": "next start" <del> } <del>} <del>``` <del> <del>然后就可以直接运行`now`了。 <del> <del>Next.js 也有其他托管解决方案。请查考 wiki 章节['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) 。 <del> <del>注意:`NODE_ENV`可以通过`next`命令配置,如果没有配置,会最大渲染,如果你使用编程式写法的话[programmatically](#custom-server-and-routing),你需要手动设置`NODE_ENV=production`。 <del> <del>注意:推荐将`.next`或自定义打包文件夹[custom dist folder](https://github.com/zeit/next.js#custom-configuration)放入`.gitignore` 或 `.npmignore`中。否则,使用`files` 或 `now.files` <del>添加部署白名单,并排除`.next`或自定义打包文件夹。 <del> <del><a id="browser-support" style="display: none"></a> <del> <del>### 无服务器部署 <del> <del><details> <del> <summary><b>例子</b></summary> <del> <ul> <del> <li><a href="https://github.com/zeit/now-examples/tree/master/nextjs">now.sh</a></li> <del> <li><a href="https://github.com/TejasQ/anna-artemov.now.sh">anna-artemov.now.sh</a></li> <del> <li>我们鼓励为本节提供更多示例</li> <del> </ul> <del></details> <del> <del>无服务器部署通过将应用程序拆分为更小的部分(也称为[**lambdas**](https://zeit.co/docs/v2/deployments/concepts/lambdas/))来显着提高可靠性和可伸缩性。在 Next.js 中,`pages`目录中的每个页面都变成了无服务器的 lambda。 <del>对于无服务器的人来说,有[许多好处](https://zeit.co/blog/serverless-express-js-lambdas-with-now-2#benefits-of-serverless-express)。引用的链接在 Express 的上下文中讨论了其中的一些,但这些原则普遍适用:无服务器允许分布式故障点,无限的可扩展性,并且通过“为您使用的内容付费”的模式来提供难以置信的价格。 <del> <del>要在 Next.js 中启用**无服务器模式**,可在`Next.config.js`中配置`target`值为`serverless`: <del> <del>```js <del>// next.config.js <del>module.exports = { <del> target: 'serverless', <del>} <del>``` <del> <del>`serverless`将每页输出一个 lambda。此文件是完全独立的,不需要运行任何依赖项: <del> <del>- `pages/index.js` => `.next/serverless/pages/index.js` <del>- `pages/about.js` => `.next/serverless/pages/about.js` <del> <del>Next.js 无服务器功能的签名类似于 Node.js HTTP 服务器回调: <del> <del>```ts <del>export function render(req: http.IncomingMessage, res: http.ServerResponse) => void <del>``` <del> <del>- [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage) <del>- [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) <del>- `void` 指的是没有返回值的函数,它等同于 JavaScript`undefined`。调用该函数将完成请求。 <del> <del>使用无服务配置, 你可以讲 Next.js 部署到[ZEIT Now](https://zeit.co/now) 并提供所有的好处和易于控制; [custom routes](https://zeit.co/guides/custom-next-js-server-to-routes/) 缓存头. 要了解更多信息,请参阅 [ZEIT Guide for Deploying Next.js with Now](https://zeit.co/guides/deploying-nextjs-with-now/) <del> <del>#### 降级部署 <del> <del>Next.js 为无服务器部署提供低级 API,因为托管平台具有不同的功能签名。通常,您需要使用兼容性层包装 Next.js 无服务器构建的输出。 <del> <del>例如,如果平台支持 Node.js[`http.Server`](https://nodejs.org/api/http.html#http_class_http_server)类: <del> <del>```js <del>const http = require('http') <del>const page = require('./.next/serverless/pages/about.js') <del>const server = new http.Server((req, res) => page.render(req, res)) <del>server.listen(3000, () => console.log('Listening on http://localhost:3000')) <del>``` <del> <del>有关特定平台示例,请参阅[the examples section above](#serverless-deployment). <del> <del>#### 摘要 <del> <del>- 用于实现无服务器部署的 Low-level API <del>- `pages`目录中的每个页面都成为无服务器功能(lambda) <del>- 创建最小的无服务器功能 (50Kb base zip size) <del>- 针对功能的快速[cold start](https://zeit.co/blog/serverless-ssr#cold-start) 进行了优化 <del>- 无服务器函数有 0 个依赖项 (依赖项包含在函数包中) <del>- 使用 Node.js 中的[http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)和[http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) <del>- 选择使用`target: 'serverless'` in `next.config.js` <del>- 在执行函数时不要加载`next.config.js`,请注意这意味着`publicRuntimeConfig` / `serverRuntimeConfig`不支持。 <del> <del>## 浏览器支持 <del> <del>Next.js 支持 IE11 和所有的现代浏览器使用了[`@babel/preset-env`](https://new.babeljs.io/docs/en/next/babel-preset-env.html)。为了支持 IE11,Next.js 需要全局添加`Promise`的 polyfill。有时你的代码或引入的其他 NPM 包的部分功能现代浏览器不支持,则需要用 polyfills 去实现。 <del> <del>ployflls 实现案例为[polyfills](https://github.com/zeit/next.js/tree/canary/examples/with-polyfills)。 <del> <del><a id="static-html-export" style="display: none"></a> <del> <del>## 导出静态页面 <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-static-export">Static export</a></li></ul> <del></details></p> <del> <del>`next export`可以输出一个 Next.js 应用作为静态资源应用而不依靠 Node.js 服务。 <del>这个输出的应用几乎支持 Next.js 的所有功能,包括动态路由,预获取,预加载以及动态导入。 <del> <del>`next export`将把所有有可能渲染出的 HTML 都生成。这是基于映射对象的`pathname`关键字关联到页面对象。这个映射叫做`exportPathMap`。 <del> <del>页面对象有 2 个属性: <del> <del>- `page` - 字符串类型,页面生成目录 <del>- `query` - 对象类型,当预渲染时,`query`对象将会传入页面的生命周期`getInitialProps`中。默认为`{}`。 <del> <del><a id="usage" style="display: none"></a> <del> <del>### 使用 <del> <del>通常开发 Next.js 应用你将会运行: <del> <del>``` <del>next build <del>next export <del>``` <del> <del>`next export`命令默认不需要任何配置,将会自动生成默认`exportPathMap`生成`pages`目录下的路由你页面。 <del> <del>如果你想动态配置路由,可以在`next.config.js`中添加异步函数`exportPathMap`。 <del> <del>```js <del>// next.config.js <del>module.exports = { <del> exportPathMap: async function(defaultPathMap) { <del> return { <del> '/': { page: '/' }, <del> '/about': { page: '/about' }, <del> '/readme.md': { page: '/readme' }, <del> '/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } }, <del> '/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } }, <del> '/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } }, <del> } <del> }, <del>} <del>``` <del> <del>> 注意:如果 path 的结尾是目录名,则将导出`/dir-name/index.html`,但是如果结尾有扩展名,将会导出对应的文件,如上`/readme.md`。如果你使用`.html`以外的扩展名解析文件时,你需要设置 header 的`Content-Type`头为"text/html". <del> <del>输入下面命令: <del> <del>```sh <del>next build <del>next export <del>``` <del> <del>你可以在`package.json`添加一个 NPM 脚本,如下所示: <del> <del>```json <del>{ <del> "scripts": { <del> "build": "next build", <del> "export": "npm run build && next export" <del> } <del>} <del>``` <del> <del>接着只用执行一次下面命令: <del> <del>```sh <del>npm run export <del>``` <del> <del>然后你将会有一个静态页面应用在`out` 目录下。 <del> <del>> 你也可以自定义输出目录。可以运行`next export -h`命令查看帮助。 <del> <del>现在你可以部署`out`目录到任意静态资源服务器上。注意如果部署 GitHub Pages 需要加个额外的步骤,[文档如下](https://github.com/zeit/next.js/wiki/Deploying-a-Next.js-app-into-GitHub-Pages) <del> <del>例如,访问`out`目录并用下面命令部署应用[ZEIT Now](https://zeit.co/now). <del> <del>```sh <del>now <del>``` <del> <del><a id="limitation" style="display: none"></a> <del> <del>### 复制自定义文件 <del> <del>如果您必须复制 robots.txt 等自定义文件或生成 sitemap.xml,您可以在其中执行此操作`exportPathMap`。 `exportPathMap`获取一些上下文参数来帮助您创建/复制文件: <del> <del>- `dev` - `true`表示在开发环境下使用`exportPathMap`. `false`表示运行于`next export`. 在开发中,“exportpathmap”用于定义路由,不需要复制文件等行为。 <del>- `dir` - 项目目录的绝对路径 <del>- `outDir` - 指向`out`目录的绝对路径(可配置为`-o`或`--outdir`)。当`dev`为`true`时,`outdir`的值将为`null`。 <del>- `distDir` - `.next`目录的绝对路径(可使用`distDir`配置键配置) <del>- `buildId` - 导出正在运行的 buildId <del> <del>```js <del>// next.config.js <del>const fs = require('fs') <del>const { join } = require('path') <del>const { promisify } = require('util') <del>const copyFile = promisify(fs.copyFile) <del> <del>module.exports = { <del> exportPathMap: async function( <del> defaultPathMap, <del> { dev, dir, outDir, distDir, buildId } <del> ) { <del> if (dev) { <del> return defaultPathMap <del> } <del> // This will copy robots.txt from your project root into the out directory <del> await copyFile(join(dir, 'robots.txt'), join(outDir, 'robots.txt')) <del> return defaultPathMap <del> }, <del>} <del>``` <del> <del>### 限制 <del> <del>使用`next export`,我们创建了个静态 HTML 应用。构建时将会运行页面里生命周期`getInitialProps` 函数。 <del> <del>`req`和`res`只在服务端可用,不能通过`getInitialProps`。 <del> <del>> 所以你不能预构建 HTML 文件时动态渲染 HTML 页面。如果你想动态渲染可以运行`next start`或其他自定义服务端 API。 <del> <del><a id="multi-zones" style="display: none"></a> <del> <del>## 多 zone <del> <del><p><details> <del> <summary><b>Examples</b></summary> <del> <ul><li><a href="./examples/with-zones">With Zones</a></li></ul> <del></details></p> <del> <del>一个 zone 时一个单独的 Next.js 应用。如果你有很多 zone,你可以合并成一个应用。 <del> <del>例如,你如下有两个 zone: <del> <del>- https://docs.my-app.com 服务于路由 `/docs/**` <del>- https://ui.my-app.com 服务于所有页面 <del> <del>有多 zone 应用技术支持,你可以将几个应用合并到一个,而且可以自定义 URL 路径,使你能同时单独开发各个应用。 <del> <del>> 与 microservices 观念类似, 只是应用于前端应用. <del> <del><a id="how-to-define-a-zone" style="display: none"></a> <del> <del>### 怎么定义一个 zone <del> <del>zone 没有单独的 API 文档。你需要做下面事即可: <del> <del>- 确保你的应用里只有需要的页面 (例如, https://ui.my-app.com 不包含 `/docs/**`) <del>- 确保你的应用有个前缀[assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix)。(你也可以定义动态前缀[dynamically](https://github.com/zeit/next.js#dynamic-assetprefix)) <del> <del><a id="how-to-merge-them" style="display: none"></a> <del> <del>### 怎么合并他们 <del> <del>你能使用 HTTP 代理合并 zone <del> <del>你能使用代理[micro proxy](https://github.com/zeit/micro-proxy)来作为你的本地代理服务。它允许你定义路由规则如下: <del> <del>```json <del>{ <del> "rules": [ <del> { <del> "pathname": "/docs**", <del> "method": ["GET", "POST", "OPTIONS"], <del> "dest": "https://docs.my-app.com" <del> }, <del> { "pathname": "/**", "dest": "https://ui.my-app.com" } <del> ] <del>} <del>``` <del> <del>生产环境部署,如果你使用了[ZEIT now](https://zeit.co/now),可以它的使用[path alias](https://zeit.co/docs/features/path-aliases) 功能。否则,你可以设置你已使用的代理服务编写上面规则来路由 HTML 页面 <del> <del><a id="recipes" style="display: none"></a> <del> <del>## 技巧 <del> <del>- [设置 301 重定向](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/) <del>- [只处理服务器端模块](https://arunoda.me/blog/ssr-and-server-only-modules) <del>- [构建项目 React-Material-UI-Next-Express-Mongoose-Mongodb](https://github.com/builderbook/builderbook) <del>- [构建一个 SaaS 产品 React-Material-UI-Next-MobX-Express-Mongoose-MongoDB-TypeScript](https://github.com/async-labs/saas) <del> <del><a id="faq" style="display: none"></a> <del> <del>## 问答 <del> <del><details> <del> <summary>这个产品可以用于生产环境吗?</summary> <del> https://zeit.co 都是一直用 Next.js 写的。 <del> <del>它的开发体验和终端用户体验都很好,所以我们决定开源出来给大家共享。 <del> <del></details> <del> <del><details> <del> <summary>体积多大?</summary> <del> <del>客户端大小根据应用需求不一样大小也不一样。 <del> <del>一个最简单 Next 应该用 gzip 压缩后大约 65kb <del> <del></details> <del> <del><details> <del> <summary>这个像 `create-react-app`?</summary> <del> <del>是或不是. <del> <del>是,因为它让你的 SSR 开发更简单。 <del> <del>不是,因为它规定了一定的目录结构,使我们能做以下更高级的事: <del> <del>- 服务端渲染 <del>- 自动代码分割 <del> <del>此外,Next.js 还提供两个内置特性: <del> <del>- 路由与懒加载组件: `<Link>` (通过引入 `next/link`) <del>- 修改`<head>`的组件: `<Head>` (通过引入 `next/head`) <del> <del>如果你想写共用组件,可以嵌入 Next.js 应用和 React 应用中,推荐使用`create-react-app`。你可以更改`import`保持代码清晰。 <del> <del></details> <del> <del><details> <del> <summary>怎么解决 CSS 嵌入 JS 问题?</summary> <del> <del>Next.js 自带[styled-jsx](https://github.com/zeit/styled-jsx)库支持 CSS 嵌入 JS。而且你可以选择其他嵌入方法到你的项目中,可参考文档[as mentioned before](#css-in-js)。 <del> <del></details> <del> <del><details> <del> <summary>哪些语法会被转换?怎么转换它们?</summary> <del> <del>我们遵循 V8 引擎的,如今 V8 引擎广泛支持 ES6 语法以及`async`和`await`语法,所以我们支持转换它们。但是 V8 引擎不支持修饰器语法,所以我们也不支持转换这语法。 <del> <del>可以参照[这些](https://github.com/zeit/next.js/blob/master/server/build/webpack.js#L79) 以及 [这些](https://github.com/zeit/next.js/issues/26) <del> <del></details> <del> <del><details> <del> <summary>为什么使用新路由?</summary> <del> <del>Next.js 的特别之处如下所示: <del> <del>- 路由不需要被提前知道 <del>- 路由总是被懒加载 <del>- 顶层组件可以定义生命周期`getInitialProps`来阻止路由加载(当服务端渲染或路由懒加载时) <del> <del>因此,我们可以介绍一个非常简单的路由方法,它由下面两部分组成: <del> <del>- 每个顶层组件都将会收到一个`url`对象,来检查 url 或修改历史记录 <del>- `<Link />`组件用于包装如(`<a/>`)标签的元素容器,来执行客户端转换。 <del> <del>我们使用了些有趣的场景来测试路由的灵活性,例如,可查看[nextgram](https://github.com/zeit/nextgram)。 <del> <del></details> <del> <del><details> <del><summary>我怎么定义自定义路由?</summary> <del> <del>我们通过请求处理来[添加](#custom-server-and-routing)任意 URL 与任意组件之前的映射关系。 <del> <del>在客户端,我们`<Link>`组件有个属性`as`,可以装饰改变获取到的 URL。 <del> <del></details> <del> <del><details> <del><summary>怎么获取数据?</summary> <del> <del>这由你决定。`getInitialProps`是一个异步函数`async`(也就是函数将会返回个`Promise`)。你可以在任意位置获取数据。 <del> <del></details> <del> <del><details> <del> <summary>我可以使用 GraphQL 吗?</summary> <del> <del>是的! 这里有个例子[Apollo](./examples/with-apollo). <del> <del></details> <del> <del><details> <del><summary>我可以使用 Redux 吗?</summary> <del> <del>是的! 这里有个[例子](./examples/with-redux) <del> <del></details> <del> <del><details> <del><summary>我可以在 Next 应用中使用我喜欢的 Javascript 库或工具包吗?</summary> <del> <del>从我们第一次发版就已经提供**很多**例子,你可以查看这些[例子](./examples)。 <del> <del></details> <del> <del><details> <del><summary>什么启发我们做这个?</summary> <del> <del>我们实现的大部分目标都是通过 Guillermo Rauch 的[Web 应用的 7 原则](http://rauchg.com/2014/7-principles-of-rich-web-applications/)来启发出的。 <del> <del>PHP 的易用性也是个很好的灵感来源,我们觉得 Next.js 可以替代很多需要用 PHP 输出 HTML 的场景。 <del> <del>与 PHP 不同的是,我们得利于 ES6 模块系统,每个文件会输出一个**组件或方法**,以便可以轻松的导入用于懒加载和测试 <del> <del>我们研究 React 的服务器渲染时并没有花费很大的步骤,因为我们发现一个类似于 Next.js 的产品,React 作者 Jordan Walke 写的[react-page](https://github.com/facebookarchive/react-page) (现在已经废弃) <del> <del></details> <del> <del><a id="contributing" style="display: none"></a> <del> <del>## 贡献 <del> <del>可查看 [contributing.md](./contributing.md) <del> <del><a id="authors" style="display: none"></a> <del> <del>## 作者 <del> <del>- Arunoda Susiripala ([@arunoda](https://twitter.com/arunoda)) – [ZEIT](https://zeit.co) <del>- Tim Neutkens ([@timneutkens](https://twitter.com/timneutkens)) – [ZEIT](https://zeit.co) <del>- Naoyuki Kanezawa ([@nkzawa](https://twitter.com/nkzawa)) – [ZEIT](https://zeit.co) <del>- Tony Kovanen ([@tonykovanen](https://twitter.com/tonykovanen)) – [ZEIT](https://zeit.co) <del>- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) – [ZEIT](https://zeit.co) <del>- Dan Zajdband ([@impronunciable](https://twitter.com/impronunciable)) – Knight-Mozilla / Coral Project
1
PHP
PHP
refactor the creation of eloquent models
104396130b1795f1b7257a63740ef1db42c0d073
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function getModels($columns = array('*')) <ide> // also set the proper connection name for the model after we create it. <ide> foreach ($results as $result) <ide> { <del> $models[] = $model = $this->model->newExisting(); <del> <del> $model->setRawAttributes((array) $result, true); <add> $models[] = $model = $this->model->newFromBuilder($result); <ide> <ide> $model->setConnection($connection); <ide> } <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function newInstance($attributes = array(), $exists = false) <ide> * @param array $attributes <ide> * @return Illuminate\Database\Eloquent\Model <ide> */ <del> public function newExisting($attributes = array()) <add> public function newFromBuilder($attributes = array()) <ide> { <del> return $this->newInstance($attributes, true); <add> $instance = $this->newInstance(array(), true); <add> <add> $instance->setRawAttributes((array) $attributes, true); <add> <add> return $instance; <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testGetModelsProperlyHydratesModels() <ide> $records[] = array('name' => 'taylor', 'age' => 26); <ide> $records[] = array('name' => 'dayle', 'age' => 28); <ide> $builder->getQuery()->shouldReceive('get')->once()->with(array('foo'))->andReturn($records); <del> $model = m::mock('Illuminate\Database\Eloquent\Model'); <add> $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,getConnectionName,newInstance]'); <ide> $model->shouldReceive('getTable')->once()->andReturn('foobars'); <ide> $builder->getQuery()->shouldReceive('from')->once()->with('foobars'); <ide> $builder->setModel($model); <ide> $model->shouldReceive('getConnectionName')->once()->andReturn('foo_connection'); <del> $model->shouldReceive('newExisting')->twice()->andReturn(new EloquentBuilderTestModelStub, new EloquentBuilderTestModelStub); <add> $model->shouldReceive('newInstance')->andReturnUsing(function() { return new EloquentBuilderTestModelStub; }); <ide> $models = $builder->getModels(array('foo')); <ide> <ide> $this->assertEquals('taylor', $models[0]->name);
3
Javascript
Javascript
use gatsby link where applicable
8134a480a5b1ab56f23968e522e7ff794a6a0cbb
<ide><path>client/src/client-only-routes/ShowSettings.js <ide> import { <ide> import { submitNewAbout, updateUserFlag, verifyCert } from '../redux/settings'; <ide> import { createFlashMessage } from '../components/Flash/redux'; <ide> <del>import Spacer from '../components/helpers/Spacer'; <del>import Loader from '../components/helpers/Loader'; <del>import FullWidthRow from '../components/helpers/FullWidthRow'; <add>import { FullWidthRow, Link, Loader, Spacer } from '../components/helpers'; <ide> import About from '../components/settings/About'; <ide> import Privacy from '../components/settings/Privacy'; <ide> import Email from '../components/settings/Email'; <ide> export function ShowSettings(props) { <ide> <main> <ide> <Spacer size={2} /> <ide> <FullWidthRow> <del> <Button <del> block={true} <del> bsSize='lg' <del> bsStyle='primary' <del> className='btn-invert' <del> href={`/${username}`} <add> <Link <add> className='btn-invert btn btn-lg btn-primary btn-block' <add> to={`/${username}`} <ide> > <ide> Show me my public portfolio <del> </Button> <add> </Link> <ide> <Button <ide> block={true} <ide> bsSize='lg'
1
Ruby
Ruby
fix a typo [ci skip]
5850ea056054c0610ddc1461dcf71d26ff60fa70
<ide><path>activerecord/test/cases/helper.rb <ide> # Enable Identity Map only when ENV['IM'] is set to "true" <ide> ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "true") <ide> <del># Avoid deprecation warning setting dependent_restric_raises to false. The default is true <add># Avoid deprecation warning setting dependent_restrict_raises to false. The default is true <ide> ActiveRecord::Base.dependent_restrict_raises = false <ide> <ide> # Connect to the database
1
Java
Java
add test with @schedules container annotation
c3dd9ff342b461c1194d50f8575e9582994fb07b
<ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java <ide> * @author Mark Fisher <ide> * @author Juergen Hoeller <ide> * @author Chris Beams <add> * @author Sam Brannen <ide> */ <ide> public class ScheduledAnnotationBeanPostProcessorTests { <ide> <add> private final StaticApplicationContext context = new StaticApplicationContext(); <add> <ide> @Test <ide> public void fixedDelayTask() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(FixedDelayTestBean.class); <ide> context.registerBeanDefinition("postProcessor", processorDefinition); <ide> public void fixedDelayTask() { <ide> <ide> @Test <ide> public void fixedRateTask() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.FixedRateTestBean.class); <ide> public void fixedRateTask() { <ide> <ide> @Test <ide> public void fixedRateTaskWithInitialDelay() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateWithInitialDelayTestBean.class); <ide> context.registerBeanDefinition("postProcessor", processorDefinition); <ide> public void fixedRateTaskWithInitialDelay() { <ide> <ide> @Test <ide> public void severalFixedRates() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(SeveralFixedRatesTestBean.class); <add> severalFixedRates(context, processorDefinition, targetDefinition); <add> } <add> <add> @Test <add> public void severalFixedRatesWithSchedulesContainer() { <add> BeanDefinition processorDefinition = new RootBeanDefinition( <add> ScheduledAnnotationBeanPostProcessor.class); <add> BeanDefinition targetDefinition = new RootBeanDefinition( <add> SeveralFixedRatesWithSchedulesContainerTestBean.class); <add> severalFixedRates(context, processorDefinition, targetDefinition); <add> } <add> <add> private void severalFixedRates(StaticApplicationContext context, <add> BeanDefinition processorDefinition, BeanDefinition targetDefinition) { <ide> context.registerBeanDefinition("postProcessor", processorDefinition); <ide> context.registerBeanDefinition("target", targetDefinition); <ide> context.refresh(); <ide> public void severalFixedRates() { <ide> public void cronTask() throws InterruptedException { <ide> Assume.group(TestGroup.LONG_RUNNING); <ide> <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.CronTestBean.class); <ide> public void cronTask() throws InterruptedException { <ide> <ide> @Test <ide> public void metaAnnotationWithFixedRate() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationFixedRateTestBean.class); <ide> context.registerBeanDefinition("postProcessor", processorDefinition); <ide> public void metaAnnotationWithFixedRate() { <ide> <ide> @Test <ide> public void metaAnnotationWithCronExpression() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.MetaAnnotationCronTestBean.class); <ide> public void metaAnnotationWithCronExpression() { <ide> @Test <ide> public void propertyPlaceholderWithCron() { <ide> String businessHoursCronExpression = "0 0 9-17 * * MON-FRI"; <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); <ide> Properties properties = new Properties(); <ide> public void propertyPlaceholderWithCron() { <ide> <ide> @Test <ide> public void propertyPlaceholderWithFixedDelay() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); <ide> Properties properties = new Properties(); <ide> public void propertyPlaceholderWithFixedDelay() { <ide> <ide> @Test <ide> public void propertyPlaceholderWithFixedRate() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); <ide> Properties properties = new Properties(); <ide> public void propertyPlaceholderWithFixedRate() { <ide> @Test <ide> public void propertyPlaceholderForMetaAnnotation() { <ide> String businessHoursCronExpression = "0 0 9-17 * * MON-FRI"; <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); <ide> Properties properties = new Properties(); <ide> public void propertyPlaceholderForMetaAnnotation() { <ide> <ide> @Test(expected = BeanCreationException.class) <ide> public void emptyAnnotation() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.EmptyAnnotationTestBean.class); <ide> public void emptyAnnotation() { <ide> <ide> @Test(expected = BeanCreationException.class) <ide> public void invalidCron() throws Throwable { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.InvalidCronTestBean.class); <ide> public void invalidCron() throws Throwable { <ide> <ide> @Test(expected = BeanCreationException.class) <ide> public void nonVoidReturnType() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.NonVoidReturnTypeTestBean.class); <ide> public void nonVoidReturnType() { <ide> <ide> @Test(expected = BeanCreationException.class) <ide> public void nonEmptyParamList() { <del> StaticApplicationContext context = new StaticApplicationContext(); <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessorTests.NonEmptyParamListTestBean.class); <ide> public void fixedRate() { <ide> } <ide> <ide> <add> static class SeveralFixedRatesWithSchedulesContainerTestBean { <add> <add> @Schedules({ @Scheduled(fixedRate = 4000), <add> @Scheduled(fixedRate = 4000, initialDelay = 2000) }) <add> public void fixedRate() { <add> } <add> } <add> <ide> static class SeveralFixedRatesTestBean { <ide> <ide> @Scheduled(fixedRate=4000)
1
Javascript
Javascript
simplify validatermoptions() error handling
94b090850389621172292e9c946388ca080e1ccb
<ide><path>lib/internal/fs/utils.js <ide> const validateRmOptions = hideStackFrames((path, options, callback) => { <ide> ); <ide> <ide> lazyLoadFs().stat(path, (err, stats) => { <del> if (err && err.code === 'ENOENT') { <del> if (options.force) { <add> if (err) { <add> if (options.force && err.code === 'ENOENT') { <ide> return callback(null, options); <ide> } <ide> return callback(err, options); <ide> } <ide> <del> if (err) { <del> return callback(err); <del> } <del> <ide> if (stats.isDirectory() && !options.recursive) { <ide> return callback(new ERR_FS_EISDIR({ <ide> code: 'EISDIR',
1
Python
Python
update error message
f39ec04cf53e8582609b771e17d2056e732d0c12
<ide><path>libcloud/common/aws.py <ide> <ide> params['TagSpecification.1.Tag.Value'] = 'foo' <ide> params['TagSpecification.2.Tag.Value'] = 'bar' <add> <add>See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html <add>for details. <ide> """.strip() <ide> <ide>
1
Ruby
Ruby
add documentation for local_assigns [ci skip]
3e66017b55fe2a94d3dbd50d5de8422f5724be4a
<ide><path>actionview/lib/action_view/base.rb <ide> module ActionView #:nodoc: <ide> # Headline: <%= headline %> <ide> # First name: <%= person.first_name %> <ide> # <add> # The local variables passed to sub templates can be accessed as a hash using the <tt>local_assigns</tt> hash. This lets you access the <add> # variables as: <add> # <add> # Headline: <%= local_assigns[:headline] %> <add> # <add> # This is useful in cases where you aren't sure if the local variable has been assigned. Alternately, you could also use <add> # <tt>defined? headline</tt> to first check if the variable has been assigned before using it. <add> # <ide> # === Template caching <ide> # <ide> # By default, Rails will compile each template to a method in order to render it. When you alter a template,
1
Python
Python
fix loading when no package found
adb0b7e43bcb40ead52834b0c03c3776a91cd1d7
<ide><path>spacy/__init__.py <ide> <ide> def load(name, **overrides): <ide> data_path = overrides.get('path', util.get_data_path()) <del> meta = parse_package_meta(data_path, name) <del> lang = meta['lang'] if meta and 'lang' in meta else 'en' <add> meta = parse_package_meta(data_path, name, require=False) <add> lang = meta['lang'] if meta and 'lang' in meta else name <ide> cls = get_lang_class(lang) <ide> overrides['meta'] = meta <del> overrides['path'] = Path(data_path / name) <add> model_path = Path(data_path) / name <add> if model_path.exists(): <add> overrides['path'] = model_path <ide> return cls(**overrides) <ide> <ide> <ide> def info(name): <del> meta = parse_package_meta(util.get_data_path(), name) <add> meta = parse_package_meta(util.get_data_path(), name, require=True) <ide> print(json.dumps(meta, indent=2)) <ide><path>spacy/util.py <ide> def check_renamed_kwargs(renamed, kwargs): <ide> raise TypeError("Keyword argument %s now renamed to %s" % (old, new)) <ide> <ide> <del>def parse_package_meta(package_path, package, on_error=False): <add>def parse_package_meta(package_path, package, require=True): <ide> location = os.path.join(str(package_path), package, 'meta.json') <del> if not os.path.isfile(location) and on_error: <del> on_error() <del> else: <add> if os.path.isfile(location): <ide> with io.open(location, encoding='utf8') as f: <ide> meta = json.load(f) <ide> return meta <del> return False <add> elif require: <add> raise IOError("Could not read meta.json from %s" % location) <add> else: <add> return None <ide> <ide> <ide> def print_msg(*text, **kwargs):
2
Ruby
Ruby
remove dead code
0e6410737539ae8d2417ce7dc0eb794eb87af064
<ide><path>railties/test/application/assets_test.rb <ide> def teardown <ide> teardown_app <ide> end <ide> <del> def app <del> @app ||= Rails.application <del> end <del> <ide> def precompile! <ide> quietly do <ide> Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
1
Ruby
Ruby
update clang version
a4cf3c273b1a78994c823b2c10eeb13a94ffd7a5
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def uncached_version <ide> when 51 then "5.1" <ide> when 60 then "6.0" <ide> when 61 then "6.1" <del> else "6.1" <add> when 70 then "7.0" <add> else "7.0" <ide> end <ide> end <ide> end <ide> def installed? <ide> <ide> def latest_version <ide> case MacOS.version <del> when "10.11" then "700.0.53" <add> when "10.11" then "700.0.53.3" <ide> when "10.10" then "602.0.53" <ide> when "10.9" then "600.0.57" <ide> when "10.8" then "503.0.40"
1
Javascript
Javascript
fix flowfixme in swipeablequickactionbutton
fc6eb51996b35548d4b153f54b7ce5938b8416ed
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableQuickActionButton.js <ide> const View = require('View'); <ide> <ide> const {PropTypes} = React; <ide> <add>import type {ImageSource} from 'ImageSource'; <add> <ide> /** <ide> * Standard set of quick action buttons that can, if the user chooses, be used <ide> * with SwipeableListView. Each button takes an image and text with optional <ide> const {PropTypes} = React; <ide> class SwipeableQuickActionButton extends React.Component { <ide> props: { <ide> accessibilityLabel?: string, <del> imageSource: $FlowFixMe, <del> imageStyle?: $FlowFixMe, <add> imageSource: ImageSource | number, <add> imageStyle?: ?View.propTypes.style, <ide> onPress?: Function, <del> style?: $FlowFixMe, <add> style?: ?View.propTypes.style, <ide> testID?: string, <del> text?: string, <del> textStyle?: $FlowFixMe, <add> text?: ?(string | Object | Array<string | Object>), <add> textStyle?: ?View.propTypes.style, <ide> }; <ide> <ide> static propTypes = {
1
Go
Go
remove dead code for "inspect --pretty"
4d87f9083bfb3147566997b3f48c4805229f7c94
<ide><path>api/client/swarm/inspect.go <ide> import ( <ide> <ide> type inspectOptions struct { <ide> format string <del> // pretty bool <ide> } <ide> <ide> func newInspectCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> func newInspectCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> Short: "Inspect the Swarm", <ide> Args: cli.NoArgs, <ide> RunE: func(cmd *cobra.Command, args []string) error { <del> // if opts.pretty && len(opts.format) > 0 { <del> // return fmt.Errorf("--format is incompatible with human friendly format") <del> // } <ide> return runInspect(dockerCli, opts) <ide> }, <ide> } <ide> <ide> flags := cmd.Flags() <ide> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template") <del> //flags.BoolVarP(&opts.pretty, "pretty", "h", false, "Print the information in a human friendly format.") <ide> return cmd <ide> } <ide> <ide> func runInspect(dockerCli *client.DockerCli, opts inspectOptions) error { <ide> return swarm, nil, nil <ide> } <ide> <del> // if !opts.pretty { <ide> return inspect.Inspect(dockerCli.Out(), []string{""}, opts.format, getRef) <del> // } <del> <del> //return printHumanFriendly(dockerCli.Out(), opts.refs, getRef) <ide> }
1
Ruby
Ruby
support non-master init.defaultbranch
af234779af9a8d83b6a7e68292cee369d5527ca9
<ide><path>Library/Homebrew/test/cmd/install_spec.rb <ide> repo_path.join("bin").mkpath <ide> <ide> repo_path.cd do <del> system "git", "init" <add> system "git", "-c", "init.defaultBranch=master", "init" <ide> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <ide> FileUtils.touch "bin/something.bin" <ide> FileUtils.touch "README" <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> def formula_gsub_origin_commit(before, after = "") <ide> <ide> tap_path.cd do <ide> system "git", "fetch" <del> system "git", "reset", "--hard", "origin/master" <add> system "git", "reset", "--hard", "origin/HEAD" <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/dev-cmd/bottle_spec.rb <ide> <ide> it "adds the bottle block to a formula that has none" do <ide> core_tap.path.cd do <del> system "git", "init" <add> system "git", "-c", "init.defaultBranch=master", "init" <ide> setup_test_formula "testball" <ide> system "git", "add", "--all" <ide> system "git", "commit", "-m", "testball 0.1" <ide> def install <ide> <ide> it "replaces the bottle block in a formula that already has a bottle block" do <ide> core_tap.path.cd do <del> system "git", "init" <add> system "git", "-c", "init.defaultBranch=master", "init" <ide> setup_test_formula "testball", bottle_block: <<~EOS <ide> <ide> bottle do <ide> def install <ide> <ide> it "updates the bottle block in a formula that already has a bottle block when using --keep-old" do <ide> core_tap.path.cd do <del> system "git", "init" <add> system "git", "-c", "init.defaultBranch=master", "init" <ide> setup_test_formula "testball", bottle_block: <<~EOS <ide> <ide> bottle do <ide><path>Library/Homebrew/test/download_strategies/git_spec.rb <ide> def git_commit_all <ide> end <ide> <ide> def setup_git_repo <del> system "git", "init" <add> system "git", "-c", "init.defaultBranch=master", "init" <ide> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <ide> FileUtils.touch "README" <ide> git_commit_all <ide><path>Library/Homebrew/test/formula_spec.rb <ide> def setup_tab_for_prefix(prefix, options = {}) <ide> testball_repo.cd do <ide> FileUtils.touch "LICENSE" <ide> <del> system("git", "init") <add> system("git", "-c", "init.defaultBranch=master", "init") <ide> system("git", "add", "--all") <ide> system("git", "commit", "-m", "Initial commit") <ide> end
5
Python
Python
fix generation of v8 constants on freebsd
3d67f895521cf905922d20af9b03e5c73c363868
<ide><path>tools/genv8constants.py <ide> <ide> sys.exit() <ide> <del>pattern = re.compile('(00000000|0000000000000000) <(.*)>:'); <add>pattern = re.compile('([0-9a-fA-F]{8}|[0-9a-fA-F]{16}) <(.*)>:'); <ide> v8dbg = re.compile('^v8dbg.*$') <ide> numpattern = re.compile('^[0-9a-fA-F]{2} $'); <ide> octets = 4 <ide> def out_reset(): <ide> def out_define(): <ide> global curr_sym, curr_val, curr_octet, outfile, octets <ide> if curr_sym != None: <add> wrapped_val = curr_val & 0xffffffff; <ide> if curr_val & 0x80000000 != 0: <del> outfile.write("#define %s -0x%x\n" % (curr_sym.upper(), 0x100000000 - curr_val)); <add> wrapped_val = 0x100000000 - wrapped_val; <add> outfile.write("#define %s -0x%x\n" % (curr_sym.upper(), wrapped_val)); <ide> else: <del> outfile.write("#define %s 0x%x\n" % (curr_sym.upper(), curr_val)); <add> outfile.write("#define %s 0x%x\n" % (curr_sym.upper(), wrapped_val)); <ide> out_reset(); <ide> <ide> for line in pipe: <ide> def out_define(): <ide> if match == None: <ide> continue; <ide> <del> octets = len(match.group(1)) / 2; <del> <ide> # Print previous symbol <ide> out_define(); <ide>
1
Text
Text
fix typos in italian translation
1cdd931f59e1c0fabb77b88651c82d434c7e6396
<ide><path>docs/italian/CONTRIBUTING.md <ide> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td> <ide> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td> <ide> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td> <del> <td><a href="/docs/romanian/CONTRIBUTING.md"> Română </a></td> <ide> <td><a href="/docs/italian/CONTRIBUTING.md"> Italiano </a></td> <ide> </tr> <ide> </table> <ide> Applichiamo rigorosamente il nostro ["Codice di condotta"](https://www.freecodec <ide> <ide> Ti auguriamo un felice contributo 🎉! <ide> <del>## Ecco alcuni modi divertenti che ci puoi aiutare <add>## Ecco alcuni modi divertenti in cui ci puoi aiutare <ide> <ide> Puoi scegliere di contribuire a qualsiasi area che ti interessa: <ide> <del>1. [Contribuirsci a questo codice open source.](#contribute-to-this-open-source-codebase). Aiuta a modificare gli [articoli guida](https://guide.freecodecamp.org/), [sfide di codifica](https://learn.freecodecamp.org/), o correggi i bug/errori sulla piattaforma di apprendimento. <add>1. [Contribuisci a questo codice open source.](#contribute-to-this-open-source-codebase). Aiuta a modificare gli [articoli guida](https://guide.freecodecamp.org/), [sfide di programmazione](https://learn.freecodecamp.org/), o correggi i bug/errori sulla piattaforma di apprendimento. <ide> <del>2. Aiuta i coleghi sul nostro [forum pubblico](https://www.freecodecamp.org/forum/). [Rispondi alle loro domande di codifica](https://www.freecodecamp.org/forum/?max_posts=1) o [dai loro feedback sui loro progetti di codifica](https://www.freecodecamp.org/forum/c/project-feedback?max_posts=1) <add>2. Aiuta i colleghi sul nostro [forum pubblico](https://www.freecodecamp.org/forum/). [Rispondi alle loro domande di programmazione](https://www.freecodecamp.org/forum/?max_posts=1) o [dai loro feedback sui loro progetti di programmazione](https://www.freecodecamp.org/forum/c/project-feedback?max_posts=1) <ide> <del>3. Aiutaci a aggiungere i sottotitoli ai nostri [video del canale YouTube](https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ/videos). <add>3. Aiutaci ad aggiungere i sottotitoli ai nostri [video del canale YouTube](https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ/videos). <ide> <ide> ## Contribuisci a questo codice open source <ide> <del>Abbiamo un enorme numero di codice open source delle migliaia di [sfide di codifica](https://learn.freecodecamp.org) e [articoli guida] (https://guide.freecodecamp.org). <add>Abbiamo un enorme numero di codice open source delle migliaia di [sfide di programmazione](https://learn.freecodecamp.org) e [articoli guida](https://guide.freecodecamp.org). <ide> <ide> Puoi aiutarci: <ide> <ide> - [📝 Ricerca, scrivi e aggiorna i nostri articoli guida](#research-write-and-update-our-guide-articles) <ide> <del>- [💻 Crea, aggiorna e correggi i bug/errori nelle nostre sfide di codifica](#create-update-and-fix-bugs-in-our-coding-challenges) <add>- [💻 Crea, aggiorna e correggi i bug/errori nelle nostre sfide di programmazione](#create-update-and-fix-bugs-in-our-coding-challenges) <ide> <del>- [🌐 Traduci gli articoli guida e le sfide di codifica](#translate-guide-articles-and-coding-challenges) <add>- [🌐 Traduci gli articoli guida e le sfide di programmazione](#translate-guide-articles-and-coding-challenges) <ide> <ide> - [🛠 Aiutaci a correggere i bug/errori nella piattaforma di apprendimento di freeCodeCamp.org](#help-us-fix-bugs-in-freecodecamporgs-learning-platform) <ide> <del>### Ricerca, scrivi e aggiorna i nostri articoli di guida <add>### Ricerca, scrivi e aggiorna i nostri articoli guida <ide> <del>**Cosa sono gli articoli della Guida?** <add>**Cosa sono gli articoli Guida?** <ide> <del>Gli articoli della guida ti aiutano a comprendere rapidamente il concetto di tecnologia. Queste sono brevi spiegazioni in inglese semplice che è possibile leggere prima di passare a risorse più approfondite. <add>Gli articoli guida ti aiutano a comprendere rapidamente il concetto di tecnologia. Queste sono brevi spiegazioni in un inglese semplice che è possibile leggere prima di passare a risorse più approfondite. <ide> <ide> Puoi trovare un [articolo di esempio sugli elementi HTML qui](./client/src/pages/html/elements/index.md). <ide> <ide> **Di cosa posso scrivere in un articolo?** <ide> <del>Accogliamo con piacere il tuo aiuto nel scrivere questi articoli. Non devi essere un esperto in un argomento per scriverne: questa intera guida è open source, quindi anche se commetti un errore, qualcun altro contribuirà a correggerlo. <add>Accogliamo con piacere il tuo aiuto nello scrivere questi articoli. Non devi essere un esperto in un argomento per scriverne: questa intera guida è open source, quindi anche se commetti un errore, qualcun altro contribuirà per correggerlo. <ide> <del>Per aiutare, trova un "articolo di stub/tronco" sul nostro [sito web di guida](https://www.freecodecamp.org/guide), scrivi l'articolo, quindi apri una richiesta di pull/integrazione delle modifiche per sostituire lo stub con il tuo articolo. Una [richiesta pull/integrazione delle modifiche](https://help.github.com/articles/about-pull-requests/) è il modo in cui suggerirai le modifiche. Permette agli altri di conoscere le tue modifiche, rivederle e adottarle. <add>Per aiutare, trova un "articolo di stub/tronco" sul nostro [sito web di guida](https://www.freecodecamp.org/guide), scrivi l'articolo, quindi apri una pull request delle modifiche per sostituire lo stub con il tuo articolo. Una [pull request](https://help.github.com/articles/about-pull-requests/) è il modo in cui suggerirai le modifiche. Permette agli altri di conoscere le tue modifiche, rivederle e adottarle. <ide> <ide> Se non riesci a trovare uno stub sull'argomento di cui vorresti scrivere, puoi aprire un PR che crea lo stub e include il tuo articolo di brutta copia. <ide> <del>Se vuoi contribuire a migliorare gli articoli della guida, ecco [come lavorare sugli articoli della guida](/docs/how-to-work-on-guide-articles.md). <add>Se vuoi contribuire a migliorare gli articoli guida, ecco [come lavorare sugli articoli guida](/docs/how-to-work-on-guide-articles.md). <ide> <del>### Crea, aggiorna e correggi i bug/errori nelle nostre sfide di codifica <add>### Crea, aggiorna e correggi i bug/errori nelle nostre sfide di programmazione <ide> <del>Tutte le nostre sfide di codifica sono curate dalla comunità, portando la conoscenza di esperti da volontari come te. <add>Tutte le nostre sfide di programmazione sono curate dalla comunità, portando la conoscenza di esperti da volontari come te. <ide> <del>Puoi aiutarli ad espanderli e rendere più chiara la loro formulazione. Puoi aggiornare le storie degli utenti per spiegare meglio il concetto e persino rimuovere quelli ridondanti/ripetitivi. È inoltre possibile migliorare i test di sfida per renderli più accurati negli test del codice delle persone. <add>Puoi aiutarli ad espanderli e rendere più chiara la loro formulazione. Puoi aggiornare le storie degli utenti per spiegare meglio il concetto e persino rimuovere quelli ridondanti/ripetitivi. È inoltre possibile migliorare i test di sfida per renderli più accurati dei test del codice degli altri. <ide> <del>Se sei interessato a migliorare queste chalenges di codifica, ecco [come lavorare sulle sfide di codifica](/docs/how-to-work-on-coding-challenges.md). <add>Se sei interessato a migliorare queste sfide di programmazione, ecco [come lavorare sulle sfide di programmazione](/docs/how-to-work-on-coding-challenges.md). <ide> <del>### Traduci gli articoli guida e le sfide di codifica <add>### Traduci gli articoli guida e le sfide di programmazione <ide> <del>Puoi aiutarci a tradurre i nostri articoli guida e le sfide di codifica per una lingua che parli. Attualmente abbiamo tradotto le versioni in: <add>Puoi aiutarci a tradurre i nostri articoli guida e le sfide di programmazione per una lingua che parli. Attualmente abbiamo tradotto le versioni in: <ide> <ide> - [Cinese (中文)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/chinese) <ide> - [Russo (русский)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/russian) <del>- [Arabico (عربى)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/arabic) <add>- [Arabo (عربى)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/arabic) <ide> - [Spagnolo (Español)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/spanish) <del>- [Portuguese (Português)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/portuguese) <del>- [Rumeno (Português)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/romanian) <del>- [Italiano (Português)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/italian) <add>- [Portoghese (Português)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/portuguese) <add>- [Italiano (Italiano)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/italian) <ide> <del>Ci piacerebbe il tuo aiuto per migliorare la qualità di queste traduzioni. Milioni di persone usano la versione in lingua inglese di freeCodeCamp.org, e ci aspettiamo che altri milioni usino anche queste versioni tradotte. <add>Ci piacerebbe ricevere il tuo aiuto per migliorare la qualità di queste traduzioni. Milioni di persone usano la versione in lingua inglese di freeCodeCamp.org, e ci aspettiamo che altri milioni usino anche queste versioni tradotte. <ide> <ide> ### Aiutaci a correggere i bug/errori nella piattaforma di apprendimento di freeCodeCamp.org <ide> <ide> In linea di massima, <ide> <ide> Contribuire a questo richiede una certa comprensione delle API, ES6 Sintassi e molta curiosità. <ide> <del>In sostanza, ci aspettiamo una certa familiarità di base, con alcune delle tecnologie, strumenti e librerie sopra citate. Detto questo, non è necessario che tu sia un esperto su di loro. <add>In sostanza, ci aspettiamo una certa familiarità di base, con alcune delle tecnologie, strumenti e librerie sopra citate. Detto questo, non è necessario che tu sia un esperto riguardo a questi argomenti. <ide> <del>Sentiti libero di farci domande, sui relativi ai problemi, e saremo lieti di chiarire. In caso di dubbio, puoi raggiungere Mrugesh Mohapatra [`@raisedadead`](https://github.com/raisedadead) o Stuart Taylor [`@bouncey`](https://github.com/bouncey) dalla nostra piattaforma squadra dev per aiutarti con questo. <add>Sentiti libero di farci domande, nei relativi thread, e saremo lieti di chiarire. In caso di dubbio, puoi raggiungere Mrugesh Mohapatra [`@raisedadead`](https://github.com/raisedadead) o Stuart Taylor [`@bouncey`](https://github.com/bouncey) dalla nostra piattaforma dev team per aiutarti. <ide> <ide> Se vuoi aiutarci a migliorare il nostro codebase, ecco [come installare freeCodeCamp localmente](/docs/how-to-setup-freecodecamp-locally.md). <ide> <ide> ## Domande frequenti <ide> <del>**Come posso segnalare un bug/errore, che non è a/sulla bordo/lavagna?** <add>**Come posso segnalare un bug/errore, che non è sulla lavagna?** <ide> <del>Se pensi di aver trovato un bug/errore, leggi prima l'articolo ["Aiuto che ho trovato un bug/errore"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) e segui le sue istruzioni. <add>Se pensi di aver trovato un bug/errore, leggi prima l'articolo ["Aiuto! Ho trovato un bug/errore"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) e segui le sue istruzioni. <ide> <del>Se sei sicuro che sia un nuovo bug, vai avanti e crea un nuovo problema in GitHub. Assicurati di includere quante più informazioni possibili in modo che noi possiamo riprodurre il bug. Abbiamo un modello di problema predefinito per aiutarti con questo. <add>Se sei sicuro che sia un nuovo bug, vai avanti e crea un nuovo issue su GitHub. Assicurati di includere quante più informazioni possibili in modo che noi possiamo riprodurre il bug. Abbiamo un modello di problema predefinito per aiutarti con questo. <ide> <del>Si prega di notare che eventuali problemi che richiedono aiuto nella codifica per una sfida saranno chiusi. Il tracker dei problemi è strettamente correlato ai problemi e alle discussioni relativi al codebase. Dovresti [cercare assistenza sul forum](https://www.freecodecamp.org/forum) prima di segnalare ogniqualvolta ci sono dubbi. <add>Si prega di notare che eventuali problemi che richiedono aiuto nella programmazione per una sfida saranno chiusi. Il tracker dei problemi è strettamente correlato ai problemi e alle discussioni relativi al codebase. Dovresti [cercare assistenza sul forum](https://www.freecodecamp.org/forum) prima di segnalare ogniqualvolta ci sono dubbi. <ide> <ide> **Come posso segnalare un problema di sicurezza?** <ide> <del>Si prega di non creare problemi su GitHub per problemi di sicurezza. Invece, si prega di inviare una mail a `[email protected]` e lo esamineremo immediatamente. <add>Si prega di non creare issue su GitHub per problemi di sicurezza. Invece, si prega di inviare una mail a `[email protected]` e lo esamineremo immediatamente. <ide> <ide> **Mi sono bloccato su qualcosa che non è in questa documentazione. Come posso ottenere aiuto?** <ide> <ide> Sentiti libero di chiedere aiuto su: <ide> <ide> Siamo lieti di aiutarti a contribuire a uno qualsiasi degli argomenti su cui vorresti lavorare. Assicurati di cercare la tua domanda prima di pubblicarne una nuova. Sii educato e paziente. I nostri volontari e moderatori della comunità sono sempre in giro per guidarti nelle tue domande. <ide> <del>**Sono nuovo a GitHub e Open Source in generale:** <add>**Sono nuovo su GitHub e nell'Open Source in generale:** <ide> <del>Leggi la nostra [Guida su Come contribuire alla open source](https://github.com/freeCodeCamp/how-to-contribute-to-open-source). <add>Leggi la nostra [Guida su come contribuire all'open source](https://github.com/freeCodeCamp/how-to-contribute-to-open-source). <ide> <del>**Che cosa significano queste etichette diverse, che sono taggate su problemi?** <add>**Che cosa significano le diverse etichette che sono taggate sui problemi?** <ide> <del>I nostri moderatori della communita' [smistano](https://en.wikipedia.org/wiki/Software_bug#Bug_management) i problemi e le richieste di pull/integrazione delle modifiche in base alla loro priorità, gravità e altri fattori. Puoi [trovare qui un glossario completo dei loro significati](https://github.com/freecodecamp/freecodecamp/labels). <add>I nostri moderatori della comunita' [smistano](https://en.wikipedia.org/wiki/Software_bug#Bug_management) i problemi e le pull request in base alla loro priorità, gravità e altri fattori. Puoi [trovare qui un glossario completo dei loro significati](https://github.com/freecodecamp/freecodecamp/labels). <ide> <del>Dovresti esaminare questi problemi di **`Help Wanted/Ho bisogno di aiuto`** oppure **`first timers welcome/Principianti`** per una rapida ricerca di ciò che è disponibile per te su cui lavorare. Questi sono in palio e non c'è bisogno di andare avanti prima di lavorare su questi. <add>Dovresti esaminare gli issue **`Help Wanted`** oppure **`first timers welcome`** per una rapida ricerca di ciò che è disponibile e su cui puoi lavorare. Questi issue sono in ballo e non c'è bisogno di andare avanti prima di lavorare su questi. <ide> <ide> Se questi problemi mancano di chiarezza su ciò che deve essere fatto, sentiti libero di porre domande nei commenti. <ide> <del>**Ho trovato un errore di battitura, dovrei segnalare un problema prima di poter effettuare una richiesta di pull/integrazione delle modifiche?** <add>**Ho trovato un errore di battitura, dovrei segnalare un problema prima di poter effettuare una pull request?** <ide> <del>Per errori di battitura e altre variazioni di testo, è possibile aprire direttamente le richieste di pull/integrazione delle modifiche senza creare prima un problema. I problemi sono di più per discutere di problemi più grandi associati al codice, o più aspetti strutturali del curriculum. <add>Per errori di battitura e altre variazioni di testo, è possibile aprire direttamente le pull request senza creare prima un issue. Gli issue sono utilizzati per discutere di problemi più grandi associati al codice, o di aspetti strutturali del curriculum.
1
PHP
PHP
fix bug in paginator
5e59a72b5b8629ea78b961e96bc57e42290007e2
<ide><path>laravel/database/query.php <ide> public function paginate($per_page = 20, $columns = array('*')) <ide> // retrieved the count from the table. <ide> list($orderings, $this->orderings) = array($this->orderings, null); <ide> <del> $page = Paginator::page($total = $this->count($columns), $per_page); <add> $total = $this->count(reset($columns)); <add> <add> $page = Paginator::page($total, $per_page); <ide> <ide> $this->orderings = $orderings; <ide>
1
Javascript
Javascript
fix autocomplete when useglobal is false
8e58c7557bd4ebec5240810c18f41d057534f3b2
<ide><path>lib/repl.js <ide> const { setImmediate } = require('timers'); <ide> // Lazy-loaded. <ide> let processTopLevelAwait; <ide> <add>const globalBuiltins = <add> new Set(vm.runInNewContext('Object.getOwnPropertyNames(globalThis)')); <add> <ide> const parentModule = module; <ide> const replMap = new WeakMap(); <ide> const domainSet = new WeakSet(); <ide> REPLServer.prototype.createContext = function() { <ide> context = vm.createContext(); <ide> }); <ide> for (const name of ObjectGetOwnPropertyNames(global)) { <del> // Only set properties on the context that do not exist as primordial. <del> if (!(name in primordials)) { <add> // Only set properties that do not already exist as a global builtin. <add> if (!globalBuiltins.has(name)) { <ide> ObjectDefineProperty(context, name, <ide> ObjectGetOwnPropertyDescriptor(global, name)); <ide> } <ide> function complete(line, callback) { <ide> completionGroups.push( <ide> filteredOwnPropertyNames.call(this, contextProto)); <ide> } <del> completionGroups.push( <del> filteredOwnPropertyNames.call(this, this.context)); <add> const contextOwnNames = <add> filteredOwnPropertyNames.call(this, this.context); <add> if (!this.useGlobal) { <add> // When the context is not `global`, builtins are not own <add> // properties of it. <add> contextOwnNames.push(...globalBuiltins); <add> } <add> completionGroups.push(contextOwnNames); <ide> if (filter !== '') addCommonWords(completionGroups); <ide> completionGroupsLoaded(); <ide> } else {
1
Javascript
Javascript
add sort test
14cce3958d38bb990d4e208d0f40659a77123025
<ide><path>test/unit/src/renderers/webgl/WebGLRenderLists.tests.js <ide> export default QUnit.module( 'Renderers', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( 'push', ( assert ) => { <add> QUnit.test( 'push', ( assert ) => { <ide> <ide> var list = new WebGLRenderList(); <del> var objA = { id: 'A' }; <add> var objA = { id: 'A', renderOrder: 0 }; <ide> var matA = { transparent: true, program: { id: 1 } }; <ide> var geoA = {}; <ide> <del> var objB = { id: 'B' }; <add> var objB = { id: 'B', renderOrder: 0 }; <ide> var matB = { transparent: true, program: { id: 2 } }; <ide> var geoB = {}; <ide> <del> var objC = { id: 'C' }; <add> var objC = { id: 'C', renderOrder: 0 }; <ide> var matC = { transparent: false, program: { id: 3 } }; <ide> var geoC = {}; <ide> <del> var objD = { id: 'D' }; <add> var objD = { id: 'D', renderOrder: 0 }; <ide> var matD = { transparent: false, program: { id: 4 } }; <ide> var geoD = {}; <ide> <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matA, <ide> program: matA.program, <ide> groupOrder: 0, <add> renderOrder: 0, <ide> z: 0.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matB, <ide> program: matB.program, <ide> groupOrder: 1, <add> renderOrder: 0, <ide> z: 1.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> list.push( objC, geoC, matC, 2, 2.5, {} ); <ide> assert.ok( list.transparent.length === 2, 'Transparent list is length 2 after adding first opaque item.' ); <ide> assert.ok( list.opaque.length === 1, 'Opaque list list is length 1 after adding first opaque item.' ); <del> assert.opaque( <add> assert.deepEqual( <ide> list.opaque[ 0 ], <ide> { <ide> id: 'C', <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matC, <ide> program: matC.program, <ide> groupOrder: 2, <add> renderOrder: 0, <ide> z: 2.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> list.push( objD, geoD, matD, 3, 3.5, {} ); <ide> assert.ok( list.transparent.length === 2, 'Transparent list is length 2 after adding second opaque item.' ); <ide> assert.ok( list.opaque.length === 2, 'Opaque list list is length 2 after adding second opaque item.' ); <del> assert.opaque( <add> assert.deepEqual( <ide> list.opaque[ 1 ], <ide> { <ide> id: 'D', <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matD, <ide> program: matD.program, <ide> groupOrder: 3, <add> renderOrder: 0, <ide> z: 3.5, <ide> group: {} <ide> }, <add> 'The second opaque render list item is structured correctly.' <ide> ); <ide> <ide> } ); <ide> <del> QUnit.todo( 'unshift', ( assert ) => { <add> QUnit.test( 'unshift', ( assert ) => { <ide> <ide> var list = new WebGLRenderList(); <del> var objA = { id: 'A' }; <add> var objA = { id: 'A', renderOrder: 0 }; <ide> var matA = { transparent: true, program: { id: 1 } }; <ide> var geoA = {}; <ide> <del> var objB = { id: 'B' }; <add> var objB = { id: 'B', renderOrder: 0 }; <ide> var matB = { transparent: true, program: { id: 2 } }; <ide> var geoB = {}; <ide> <del> var objC = { id: 'C' }; <add> var objC = { id: 'C', renderOrder: 0 }; <ide> var matC = { transparent: false, program: { id: 3 } }; <ide> var geoC = {}; <ide> <del> var objD = { id: 'D' }; <add> var objD = { id: 'D', renderOrder: 0 }; <ide> var matD = { transparent: false, program: { id: 4 } }; <ide> var geoD = {}; <ide> <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matA, <ide> program: matA.program, <ide> groupOrder: 0, <add> renderOrder: 0, <ide> z: 0.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matB, <ide> program: matB.program, <ide> groupOrder: 1, <add> renderOrder: 0, <ide> z: 1.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> list.unshift( objC, geoC, matC, 2, 2.5, {} ); <ide> assert.ok( list.transparent.length === 2, 'Transparent list is length 2 after adding first opaque item.' ); <ide> assert.ok( list.opaque.length === 1, 'Opaque list list is length 1 after adding first opaque item.' ); <del> assert.opaque( <add> assert.deepEqual( <ide> list.opaque[ 0 ], <ide> { <ide> id: 'C', <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matC, <ide> program: matC.program, <ide> groupOrder: 2, <add> renderOrder: 0, <ide> z: 2.5, <ide> group: {} <ide> }, <ide> export default QUnit.module( 'Renderers', () => { <ide> list.unshift( objD, geoD, matD, 3, 3.5, {} ); <ide> assert.ok( list.transparent.length === 2, 'Transparent list is length 2 after adding second opaque item.' ); <ide> assert.ok( list.opaque.length === 2, 'Opaque list list is length 2 after adding second opaque item.' ); <del> assert.opaque( <add> assert.deepEqual( <ide> list.opaque[ 0 ], <ide> { <ide> id: 'D', <ide> export default QUnit.module( 'Renderers', () => { <ide> material: matD, <ide> program: matD.program, <ide> groupOrder: 3, <add> renderOrder: 0, <ide> z: 3.5, <ide> group: {} <ide> }, <add> 'The second opaque render list item is structured correctly.' <add> ); <add> <add> } ); <add> <add> QUnit.test( 'sort', ( assert ) => { <add> <add> var list = new WebGLRenderList(); <add> var items = [ { id: 4 }, { id: 5 }, { id: 2 }, { id: 3 } ]; <add> <add> items.forEach( item => { <add> <add> list.push( item, {}, { transparent: true }, 0, 0, {} ); <add> list.push( item, {}, { transparent: false }, 0, 0, {} ); <add> <add> } ); <add> <add> list.sort( ( a, b ) => a.id - b.id, ( a, b ) => b.id - a.id ); <add> <add> assert.deepEqual( <add> list.opaque.map( item => item.id ), <add> [ 2, 3, 4, 5 ], <add> 'The opaque sort is applied to the opaque items list.' <add> ); <add> <add> assert.deepEqual( <add> list.transparent.map( item => item.id ), <add> [ 5, 4, 3, 2 ], <add> 'The transparent sort is applied to the transparent items list.' <ide> ); <ide> <ide> } ); <ide> <ide> QUnit.todo( 'finish', ( assert ) => { <ide> <add> assert.ok( false, "everything's gonna be alright" ); <add> <ide> } ); <ide> <ide> } );
1
Text
Text
fix typo in webcrypto.md
f683cf901c8bc7d8183072f8554cf870f4a6ddbe
<ide><path>doc/api/webcrypto.md <ide> The algorithms currently supported include: <ide> * `'NODE-ED25519'`<sup>1</sup> <ide> * `'NODE-ED448'`<sup>1</sup> <ide> <del><sup>1</sup> Non-standadrd Node.js extension <add><sup>1</sup> Non-standard Node.js extension <ide> <ide> ### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` <ide> <!-- YAML
1
Text
Text
suggest the wiki
83f8afe273ceb26aed837a88bd8c3f3d4c8392e0
<ide><path>ISSUE_TEMPLATE.md <ide> --- Have a general question? --- <ide> <ide> First check out the Docs: https://facebook.github.io/immutable-js/docs/ <add>And check out the Wiki: https://github.com/facebook/immutable-js/wiki/ <ide> Search existing issues: https://github.com/facebook/immutable-js/search?type=Issues&q=question <ide> Ask on Stack Overflow!: https://stackoverflow.com/questions/tagged/immutable.js?sort=votes <ide>
1
Text
Text
update idea guidelines
5a1b7c6ce7f9ad22197d9dba16f71e29e04a001c
<ide><path>import-into-idea.md <del>The following has been tested against Intellij IDEA 12.0 <add>The following has been tested against Intellij IDEA 13.1 <ide> <ide> ## Steps <ide> <ide> _Within your locally cloned spring-framework working directory:_ <ide> <del>1. Generate IDEA metadata with `./gradlew :spring-oxm:compileTestJava cleanIdea idea` <del>2. Import into IDEA as usual <del>3. Set the Project JDK as appropriate <del>4. Add git support <add>1. Pre-compile `spring-oxm` with `./gradlew cleanIdea :spring-oxm:compileTestJava` <add>2. Import into IDEA (File->import project->import from external model->Gradle) <add>3. Set the Project JDK as appropriate (1.8+) <add>4. Exclude the `spring-aspects` module (Go to File->Project Structure->Modules) <ide> 5. Code away <ide> <ide> ## Known issues <ide> <del>1. Those steps don't work currently for Intellij IDEA 13+ <add>1. `spring-oxm` should be pre-compiled since it's using repackaged dependencies (see *RepackJar tasks) <ide> 2. `spring-aspects` does not compile out of the box due to references to aspect types unknown to IDEA. <ide> See http://youtrack.jetbrains.com/issue/IDEA-64446 for details. In the meantime, the 'spring-aspects' <del>module has been excluded from the overall project to avoid compilation errors. <add>should be excluded from the overall project to avoid compilation errors. <ide> 3. While all JUnit tests pass from the command line with Gradle, many will fail when run from IDEA. <ide> Resolving this is a work in progress. If attempting to run all JUnit tests from within IDEA, you will <ide> likely need to set the following VM options to avoid out of memory errors:
1
Ruby
Ruby
make the each visitor top-down left-right
e08696421f37d7c0cf488c40bf1c21520f1a0db5
<ide><path>actionpack/lib/action_dispatch/journey/visitors.rb <ide> def initialize(block) <ide> end <ide> <ide> def visit(node) <del> super <ide> block.call(node) <add> super <ide> end <ide> end <ide>
1
Python
Python
fix timeseriesgenerator glitch
5422fdd38baad36730cb6aeb946e17eeae6a551c
<ide><path>keras/preprocessing/sequence.py <ide> def __init__(self, data, targets, length, <ide> self.reverse = reverse <ide> self.batch_size = batch_size <ide> <add> if self.start_index > self.end_index: <add> raise ValueError('`start_index+length=%i > end_index=%i` ' <add> 'is disallowed, as no part of the sequence ' <add> 'would be left to be used as current step.' <add> % (self.start_index, self.end_index)) <add> <ide> def __len__(self): <ide> return int(np.ceil( <del> (self.end_index - self.start_index) / <add> (self.end_index - self.start_index + 1) / <ide> (self.batch_size * self.stride))) <ide> <ide> def _empty_batch(self, num_rows): <ide> def _empty_batch(self, num_rows): <ide> def __getitem__(self, index): <ide> if self.shuffle: <ide> rows = np.random.randint( <del> self.start_index, self.end_index, size=self.batch_size) <add> self.start_index, self.end_index + 1, size=self.batch_size) <ide> else: <ide> i = self.start_index + self.batch_size * self.stride * index <ide> rows = np.arange(i, min(i + self.batch_size * <del> self.stride, self.end_index), self.stride) <add> self.stride, self.end_index + 1), self.stride) <ide> <ide> samples, targets = self._empty_batch(len(rows)) <ide> for j, row in enumerate(rows): <ide><path>tests/keras/preprocessing/sequence_test.py <add>from math import ceil <add> <ide> import numpy as np <del>from numpy.testing import assert_allclose <add>from numpy.testing import assert_allclose, assert_raises <ide> <ide> import pytest <ide> <ide> def test_TimeseriesGenerator(): <ide> length=10, sampling_rate=2, <ide> start_index=10, end_index=30, <ide> batch_size=2) <del> assert len(data_gen) == 5 <add> assert len(data_gen) == 6 <ide> assert (np.allclose(data_gen[0][0], <ide> np.array([[[10], [12], [14], [16], [18]], <ide> [[11], [13], [15], [17], [19]]]))) <ide> def test_TimeseriesGenerator(): <ide> length=10, sampling_rate=2, <ide> start_index=10, end_index=30, <ide> batch_size=2) <del> <del> assert len(data_gen) == 5 <add> assert len(data_gen) == 6 <ide> assert np.allclose(data_gen[0][0], np.array( <ide> [np.array(data[10:19:2]), np.array(data[11:20:2])])) <ide> assert (np.allclose(data_gen[0][1], <ide> np.array([targets[20], targets[21]]))) <ide> <add> with assert_raises(ValueError) as context: <add> TimeseriesGenerator(data, targets, length=50) <add> error = str(context.exception) <add> assert '`start_index+length=50 > end_index=49` is disallowed' in error <add> <add> <add>def test_TimeSeriesGenerator_doesnt_miss_any_sample(): <add> x = np.array([[i] for i in range(10)]) <add> <add> for length in range(3, 10): <add> g = TimeseriesGenerator(x, x, <add> length=length, <add> batch_size=1) <add> expected = max(0, len(x) - length) <add> actual = len(g) <add> <add> assert expected == actual <add> <add> if len(g) > 0: <add> # All elements in range(length, 10) should be used as current step <add> expected = np.arange(length, 10).reshape(-1, 1) <add> <add> y = np.concatenate([g[ix][1] for ix in range(len(g))], axis=0) <add> assert_allclose(y, expected) <add> <add> x = np.array([[i] for i in range(23)]) <add> <add> strides = (1, 1, 5, 7, 3, 5, 3) <add> lengths = (3, 3, 4, 3, 1, 3, 7) <add> batch_sizes = (6, 6, 6, 5, 6, 6, 6) <add> shuffles = (False, True, True, False, False, False, False) <add> <add> for stride, length, batch_size, shuffle in zip(strides, <add> lengths, <add> batch_sizes, <add> shuffles): <add> g = TimeseriesGenerator(x, x, <add> length=length, <add> sampling_rate=1, <add> stride=stride, <add> start_index=0, <add> end_index=None, <add> shuffle=shuffle, <add> reverse=False, <add> batch_size=batch_size) <add> if shuffle: <add> # all batches have the same size when shuffle is True. <add> expected_sequences = ceil( <add> (23 - length) / float(batch_size * stride)) * batch_size <add> else: <add> # last batch will be different if `(samples - length) / stride` <add> # is not a multiple of `batch_size`. <add> expected_sequences = ceil((23 - length) / float(stride)) <add> <add> expected_batches = ceil(expected_sequences / float(batch_size)) <add> <add> y = [g[ix][1] for ix in range(len(g))] <add> <add> actual_sequences = sum(len(_y) for _y in y) <add> actual_batches = len(y) <add> <add> assert expected_sequences == actual_sequences <add> assert expected_batches == actual_batches <add> <ide> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
2
Python
Python
add test for limited imp loaders, #380
b786eac5574e478d51314333fb6309456bff7b76
<ide><path>flask/testsuite/config.py <ide> :copyright: (c) 2011 by Armin Ronacher. <ide> :license: BSD, see LICENSE for more details. <ide> """ <add>from __future__ import with_statement <add> <ide> import os <ide> import sys <ide> import flask <add>import pkgutil <ide> import unittest <add>from contextlib import contextmanager <ide> from flask.testsuite import FlaskTestCase <ide> <ide> <ide> def test_session_lifetime(self): <ide> self.assert_equal(app.permanent_session_lifetime.seconds, 42) <ide> <ide> <add>class LimitedLoaderMockWrapper(object): <add> def __init__(self, loader): <add> self.loader = loader <add> <add> def __getattr__(self, name): <add> if name in ('archive', 'get_filename'): <add> msg = 'Mocking a loader which does not have `%s.`' % name <add> raise AttributeError, msg <add> return getattr(self.loader, name) <add> <add> <add>@contextmanager <add>def patch_pkgutil_get_loader(wrapper_class=LimitedLoaderMockWrapper): <add> """Patch pkgutil.get_loader to give loader without get_filename or archive. <add> <add> This provides for tests where a system has custom loaders, e.g. Google App <add> Engine's HardenedModulesHook, which have neither the `get_filename` method <add> nor the `archive` attribute. <add> """ <add> old_get_loader = pkgutil.get_loader <add> def get_loader(*args, **kwargs): <add> return wrapper_class(old_get_loader(*args, **kwargs)) <add> try: <add> pkgutil.get_loader = get_loader <add> yield <add> finally: <add> pkgutil.get_loader = old_get_loader <add> <add> <ide> class InstanceTestCase(FlaskTestCase): <ide> <ide> def test_explicit_instance_paths(self): <ide> def test_installed_module_paths(self): <ide> if 'site_app' in sys.modules: <ide> del sys.modules['site_app'] <ide> <add> def test_installed_module_paths_with_limited_loader(self): <add> here = os.path.abspath(os.path.dirname(__file__)) <add> expected_prefix = os.path.join(here, 'test_apps') <add> real_prefix, sys.prefix = sys.prefix, expected_prefix <add> site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages') <add> sys.path.append(site_packages) <add> with patch_pkgutil_get_loader(): <add> try: <add> import site_app <add> self.assert_equal(site_app.app.instance_path, <add> os.path.join(expected_prefix, 'var', <add> 'site_app-instance')) <add> finally: <add> sys.prefix = real_prefix <add> sys.path.remove(site_packages) <add> if 'site_app' in sys.modules: <add> del sys.modules['site_app'] <add> <ide> def test_installed_package_paths(self): <ide> here = os.path.abspath(os.path.dirname(__file__)) <ide> expected_prefix = os.path.join(here, 'test_apps') <ide> def test_installed_package_paths(self): <ide> if 'installed_package' in sys.modules: <ide> del sys.modules['installed_package'] <ide> <add> def test_installed_package_paths_with_limited_loader(self): <add> here = os.path.abspath(os.path.dirname(__file__)) <add> expected_prefix = os.path.join(here, 'test_apps') <add> real_prefix, sys.prefix = sys.prefix, expected_prefix <add> installed_path = os.path.join(expected_prefix, 'path') <add> sys.path.append(installed_path) <add> with patch_pkgutil_get_loader(): <add> try: <add> import installed_package <add> self.assert_equal(installed_package.app.instance_path, <add> os.path.join(expected_prefix, 'var', <add> 'installed_package-instance')) <add> finally: <add> sys.prefix = real_prefix <add> sys.path.remove(installed_path) <add> if 'installed_package' in sys.modules: <add> del sys.modules['installed_package'] <add> <ide> def test_prefix_package_paths(self): <ide> here = os.path.abspath(os.path.dirname(__file__)) <ide> expected_prefix = os.path.join(here, 'test_apps') <ide> def test_prefix_package_paths(self): <ide> if 'site_package' in sys.modules: <ide> del sys.modules['site_package'] <ide> <add> def test_prefix_package_paths_with_limited_loader(self): <add> here = os.path.abspath(os.path.dirname(__file__)) <add> expected_prefix = os.path.join(here, 'test_apps') <add> real_prefix, sys.prefix = sys.prefix, expected_prefix <add> site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages') <add> sys.path.append(site_packages) <add> with patch_pkgutil_get_loader(): <add> try: <add> import site_package <add> self.assert_equal(site_package.app.instance_path, <add> os.path.join(expected_prefix, 'var', <add> 'site_package-instance')) <add> finally: <add> sys.prefix = real_prefix <add> sys.path.remove(site_packages) <add> if 'site_package' in sys.modules: <add> del sys.modules['site_package'] <add> <ide> def test_egg_installed_paths(self): <ide> here = os.path.abspath(os.path.dirname(__file__)) <ide> expected_prefix = os.path.join(here, 'test_apps')
1
Text
Text
read both types of bash completions
f8c574bbc08d4361bbb85a66194941f7f96a17cc
<ide><path>docs/Shell-Completion.md <ide> To make Homebrew's completions available in `bash`, you must source the definiti <ide> <ide> ```sh <ide> if type brew 2&>/dev/null; then <del> source "$(brew --prefix)/etc/bash_completion.d/*" <del>else <del> echo "run: brew install git bash-completion" <add> for COMPLETION in $(brew --prefix)/etc/bash_completion.d/* <add> do <add> [[ -f $COMPLETION ]] && source "$COMPLETION" <add> done <add> if [[ -f $(brew --prefix)/etc/profile.d/bash_completion.sh ]]; <add> then <add> source "$(brew --prefix)/etc/profile.d/bash_completion.sh" <add> fi <ide> fi <ide> ``` <ide> <ide> ## Configuring Completions in `zsh` <add> <ide> To make Homebrew's completions available in `zsh`, you must get the Homebrew-managed zsh site-functions on your `FPATH` before initialising `zsh`'s completion facility. Add the following to your `~/.zshrc` file: <ide> <ide> ```sh <ide> Additionally, if you receive "zsh compinit: insecure directories" warnings when <ide> ``` <ide> <ide> ## Configuring Completions in `fish` <add> <ide> No configuration is needed in `fish`. Friendly!
1
Mixed
Python
add cross-field validate method
ac2d39892d6b3fbbe5cd53b9ef83367249ba4880
<ide><path>docs/api-guide/serializers.md <ide> Deserialization is similar. First we parse a stream into python native datatype <ide> <ide> When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages. <ide> <del>**TODO: Describe validation in more depth** <del> <del>## Custom field validation <add>### Field-level validation <ide> <ide> You can specify custom field-level validation by adding `validate_<fieldname>()` methods to your `Serializer` subclass. These are analagous to `clean_<fieldname>` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized data as a first argument, and the field name in that data as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). Your `validate_<fieldname>` methods should either just return the data dictionary or raise a `ValidationError`. For example: <ide> <ide> You can specify custom field-level validation by adding `validate_<fieldname>()` <ide> raise serializers.ValidationError("Blog post is not about Django") <ide> return data <ide> <add>### Final cross-field validation <add> <add>To do any other validation that requires access to multiple fields, add a method called `validate` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. <add> <ide> ## Dealing with nested objects <ide> <ide> The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, <ide><path>rest_framework/serializers.py <ide> def clean_fields(self, data): <ide> <ide> return data <ide> <add> def clean_all(self, attrs): <add> """ <add> Run the `validate` method on the serializer, if it exists <add> """ <add> try: <add> validate_method = getattr(self, 'validate', None) <add> if validate_method: <add> attrs = validate_method(attrs) <add> except ValidationError as err: <add> self._errors['non_field_errors'] = err.messages <add> return attrs <add> <ide> def restore_object(self, attrs, instance=None): <ide> """ <ide> Deserialize a dictionary of attributes into an object instance. <ide> def from_native(self, data): <ide> if data is not None: <ide> attrs = self.restore_fields(data) <ide> attrs = self.clean_fields(attrs) <add> attrs = self.clean_all(attrs) <ide> else: <ide> self._errors['non_field_errors'] = 'No input provided' <ide> <ide><path>rest_framework/tests/serializer.py <ide> def validate_content(self, attrs, source): <ide> self.assertFalse(serializer.is_valid()) <ide> self.assertEquals(serializer.errors, {'content': [u'Test not in value']}) <ide> <add> def test_cross_field_validation(self): <add> <add> class CommentSerializerWithCrossFieldValidator(CommentSerializer): <add> <add> def validate(self, attrs): <add> if attrs["email"] not in attrs["content"]: <add> raise serializers.ValidationError("Email address not in content") <add> return attrs <add> <add> data = { <add> 'email': '[email protected]', <add> 'content': 'A comment from [email protected]', <add> 'created': datetime.datetime(2012, 1, 1) <add> } <add> <add> serializer = CommentSerializerWithCrossFieldValidator(data) <add> self.assertTrue(serializer.is_valid()) <add> <add> data['content'] = 'A comment from [email protected]' <add> <add> serializer = CommentSerializerWithCrossFieldValidator(data) <add> self.assertFalse(serializer.is_valid()) <add> self.assertEquals(serializer.errors, {'non_field_errors': [u'Email address not in content']}) <add> <ide> <ide> class MetadataTests(TestCase): <ide> def test_empty(self):
3
Ruby
Ruby
drop support for passing incomplete paths
e891bb42726679b7fb7e347b8bf4cabcff1bec22
<ide><path>Library/Homebrew/formulary.rb <ide> def initialize alias_path <ide> # Loads formulae from disk using a path <ide> class FromPathLoader < FormulaLoader <ide> def initialize path <del> # require allows filenames to drop the .rb extension, but everything else <del> # in our codebase will require an exact and fullpath. <del> path = "#{path}.rb" unless File.extname(path) == ".rb" <ide> path = Pathname.new(path).expand_path <del> super path.stem, path <add> super path.basename(".rb").to_s, path <ide> end <ide> end <ide> <ide> def self.loader_for(ref) <ide> return TapLoader.new(ref) <ide> end <ide> <del> if ref.include?("/") || File.extname(ref) == ".rb" <add> if File.extname(ref) == ".rb" <ide> return FromPathLoader.new(ref) <ide> end <ide>
1
Java
Java
append suffx to user dest in simpmessagingtemplate
7a5b3c1eed58b3d4b3051a8f19509e02a74e2ba9
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java <ide> public MessageChannel getMessageChannel() { <ide> * @see org.springframework.messaging.simp.user.UserDestinationMessageHandler <ide> */ <ide> public void setUserDestinationPrefix(String prefix) { <del> Assert.notNull(prefix, "UserDestinationPrefix must not be null"); <del> this.userDestinationPrefix = prefix; <add> Assert.hasText(prefix, "'userDestinationPrefix' must not be empty"); <add> this.userDestinationPrefix = prefix.endsWith("/") ? prefix : prefix + "/"; <add> <ide> } <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java <ide> public void convertAndSendWithCustomHeaderNonNative() { <ide> assertNull(headerAccessor.getNativeHeader("key")); <ide> } <ide> <add> // SPR-11868 <add> <add> @Test <add> public void convertAndSendWithCustomDestinationPrefix() { <add> this.messagingTemplate.setUserDestinationPrefix("/prefix"); <add> this.messagingTemplate.convertAndSendToUser("joe", "/queue/foo", "data"); <add> List<Message<byte[]>> messages = this.messageChannel.getMessages(); <add> <add> assertEquals(1, messages.size()); <add> <add> Message<byte[]> message = messages.get(0); <add> SimpMessageHeaderAccessor headerAccessor = <add> MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); <add> <add> assertNotNull(headerAccessor); <add> assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType()); <add> assertEquals("/prefix/joe/queue/foo", headerAccessor.getDestination()); <add> } <add> <ide> @Test <ide> public void convertAndSendWithMutableSimpMessageHeaders() { <ide> SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java <ide> public void annotationMethodMessageHandler() { <ide> <ide> SimpMessagingTemplate simpMessagingTemplate = this.appContext.getBean(SimpMessagingTemplate.class); <ide> assertNotNull(simpMessagingTemplate); <del> assertEquals("/personal", simpMessagingTemplate.getUserDestinationPrefix()); <add> assertEquals("/personal/", simpMessagingTemplate.getUserDestinationPrefix()); <ide> <ide> List<MessageConverter> converters = compositeMessageConverter.getConverters(); <ide> assertThat(converters.size(), Matchers.is(3));
3
Ruby
Ruby
simplify logical statement
422b3d70d5aba24e6a8f94722db449d5647f22d3
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def current_controller <ide> <ide> def use_recall_for(key) <ide> if @recall[key] && ([email protected]?(key) || @options[key] == @recall[key]) <del> if named_route_exists? <del> @options[key] = @recall.delete(key) if segment_keys.include?(key) <del> else <del> @options[key] = @recall.delete(key) <add> if !named_route_exists? || segment_keys.include?(key) <add> @options[key] = @recall.delete(key) <ide> end <ide> end <ide> end
1
Java
Java
fix concurrent reads issue in mimetypeutils cache
1b93ea97ac4fb7011e4afb026bb32d0c589aa198
<ide><path>spring-core/src/main/java/org/springframework/util/MimeTypeUtils.java <ide> public V get(K key) { <ide> } <ide> this.lock.writeLock().lock(); <ide> try { <add> // retrying in case of concurrent reads on the same key <add> if (this.queue.remove(key)) { <add> this.queue.add(key); <add> return this.cache.get(key); <add> } <ide> if (this.queue.size() == this.maxSize) { <ide> K leastUsed = this.queue.poll(); <ide> if (leastUsed != null) {
1
Ruby
Ruby
remove unnecessary early return
f0fc15ade8cdff5ad50da4a6d5b900ab3cd1dd90
<ide><path>Library/Homebrew/formula.rb <ide> def stage <ide> <ide> def prepare_patches <ide> active_spec.add_legacy_patches(patches) <del> return if patchlist.empty? <ide> <ide> patchlist.grep(DATAPatch) { |p| p.path = path } <ide>
1
Text
Text
move sysctls docs to current api version
de22669377d074a2594de33be01ae4d9723283a8
<ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `GET /images/search` now supports maximum returned search results `limit`. <ide> * `POST /containers/{name:.*}/copy` is now removed and errors out starting from this API version. <ide> * API errors are now returned as JSON instead of plain text. <add>* `POST /containers/create` and `POST /containers/(id)/start` allow you to configure kernel parameters (sysctls) for use in the container. <ide> <ide> ### v1.23 API changes <ide> <ide> This section lists each version from latest to oldest. Each listing includes a <ide> <ide> [Docker Remote API v1.21](docker_remote_api_v1.21.md) documentation <ide> <del>* `POST /containers/create` and `POST /containers/(id)/start` allow you to configure kernel parameters (sysctls) for use in the container. <ide> * `GET /volumes` lists volumes from all volume drivers. <ide> * `POST /volumes/create` to create a volume. <ide> * `GET /volumes/(name)` get low-level information about a volume. <ide><path>docs/reference/api/docker_remote_api_v1.21.md <ide> Json Parameters: <ide> - **Devices** - A list of devices to add to the container specified as a JSON object in the <ide> form <ide> `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` <del> - **Sysctls** - A list of kernel parameters (sysctls) to set in the container, specified as <del> `{ <name>: <Value> }`, for example: <del> `{ "net.ipv4.ip_forward": "1" }` <del> <ide> - **Ulimits** - A list of ulimits to set in the container, specified as <ide> `{ "Name": <name>, "Soft": <soft limit>, "Hard": <hard limit> }`, for example: <ide> `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard": 2048 }` <ide> Return low-level information on the container `id` <ide> "Type": "json-file" <ide> }, <ide> "SecurityOpt": null, <del> "Sysctls": { <del> "net.ipv4.ip_forward": "1" <del> }, <ide> "VolumesFrom": null, <ide> "Ulimits": [{}], <ide> "VolumeDriver": "" <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Create a container <ide> - **Ulimits** - A list of ulimits to set in the container, specified as <ide> `{ "Name": <name>, "Soft": <soft limit>, "Hard": <hard limit> }`, for example: <ide> `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard": 2048 }` <add> - **Sysctls** - A list of kernel parameters (sysctls) to set in the container, specified as <add> `{ <name>: <Value> }`, for example: <add> `{ "net.ipv4.ip_forward": "1" }` <ide> - **SecurityOpt**: A list of string values to customize labels for MLS <ide> systems, such as SELinux. <ide> - **StorageOpt**: Storage driver options per container. Options can be passed in the form <ide> Return low-level information on the container `id` <ide> "Type": "json-file" <ide> }, <ide> "SecurityOpt": null, <add> "Sysctls": { <add> "net.ipv4.ip_forward": "1" <add> }, <ide> "StorageOpt": null, <ide> "VolumesFrom": null, <ide> "Ulimits": [{}],
3
Text
Text
expand anchor text [ci-skip]
56d8d103d43d1600beb84f34d4da2982193ae5f4
<ide><path>guides/source/routing.md <ide> Deeply-nested resources quickly become cumbersome. In this case, for example, th <ide> /publishers/1/magazines/2/photos/3 <ide> ``` <ide> <del>The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular [article](http://weblog.jamisbuck.org/2007/2/5/nesting-resources) by Jamis Buck proposes a rule of thumb for good Rails design: <add>The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a [popular article by Jamis Buck](http://weblog.jamisbuck.org/2007/2/5/nesting-resources) proposes a rule of thumb for good Rails design: <ide> <ide> TIP: Resources should never be nested more than 1 level deep. <ide>
1
Python
Python
handle errors during create_url_adapter
ed9775fb77bc2291473c176937326aadd435f73c
<ide><path>flask/ctx.py <ide> def __init__(self, app, environ, request=None, session=None): <ide> if request is None: <ide> request = app.request_class(environ) <ide> self.request = request <del> self.url_adapter = app.create_url_adapter(self.request) <add> self.url_adapter = None <add> try: <add> self.url_adapter = app.create_url_adapter(self.request) <add> except HTTPException as e: <add> self.request.routing_exception = e <ide> self.flashes = None <ide> self.session = session <ide> <ide> def __init__(self, app, environ, request=None, session=None): <ide> # functions. <ide> self._after_request_functions = [] <ide> <del> self.match_request() <add> if self.url_adapter is not None: <add> self.match_request() <ide> <ide> def _get_g(self): <ide> return _app_ctx_stack.top.g <ide><path>tests/test_reqctx.py <ide> def index(): <ide> assert response.status_code == 500 <ide> assert not flask.request <ide> assert not flask.current_app <add> <add> <add>def test_bad_environ_raises_bad_request(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/') <add> def index(): <add> # shouldn't get here anyway <add> assert False <add> <add> response = app.test_client().get('/', headers={'host': 'ąśź.com'}) <add> assert response.status_code == 400 <add> <add> <add>def test_normal_environ_completes(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/') <add> def index(): <add> return 'Hello World!' <add> <add> response = app.test_client().get('/', headers={'host': 'xn--on-0ia.com'}) <add> assert response.status_code == 200
2
Python
Python
get buildbot running
eb1b0edf8256ded7c8aec9ae186a0f6af893d29d
<ide><path>build.py <ide> def x(cmd): <ide> <ide> if install_mode == 'pip': <ide> x('python setup.py sdist') <del> x('pip install dist/*') <add> dists = os.listdir('dist') <add> assert len(dists) == 1 <add> x('pip install dist/%s' % dists[0]) <ide> <ide> elif install_mode == 'setup-install': <ide> x('python setup.py install')
1
Python
Python
remove workarounds for gh-9527
8948d651d2fd97ed6d1fad120c8619ed915df72c
<ide><path>numpy/linalg/linalg.py <ide> def slogdet(a): <ide> real_t = _realType(result_t) <ide> signature = 'D->Dd' if isComplexType(t) else 'd->dd' <ide> sign, logdet = _umath_linalg.slogdet(a, signature=signature) <del> if isscalar(sign): <del> sign = sign.astype(result_t) <del> else: <del> sign = sign.astype(result_t, copy=False) <del> if isscalar(logdet): <del> logdet = logdet.astype(real_t) <del> else: <del> logdet = logdet.astype(real_t, copy=False) <add> sign = sign.astype(result_t, copy=False) <add> logdet = logdet.astype(real_t, copy=False) <ide> return sign, logdet <ide> <ide> def det(a): <ide> def det(a): <ide> t, result_t = _commonType(a) <ide> signature = 'D->D' if isComplexType(t) else 'd->d' <ide> r = _umath_linalg.det(a, signature=signature) <del> if isscalar(r): <del> r = r.astype(result_t) <del> else: <del> r = r.astype(result_t, copy=False) <add> r = r.astype(result_t, copy=False) <ide> return r <ide> <ide> # Linear Least Squares
1
Python
Python
add a model.check_trainable_weights_consistency
cab77c8f23bf81eaa06aeeeb28a4da3b716f7bd7
<ide><path>keras/engine/topology.py <ide> from .. import initializers <ide> from ..utils.io_utils import ask_to_proceed_with_overwrite <ide> from ..utils.layer_utils import print_summary as print_layer_summary <add>from ..utils.layer_utils import count_params <ide> from ..utils.generic_utils import has_arg <ide> from ..utils import conv_utils <ide> from ..legacy import interfaces <ide> def count_params(self): <ide> self.name + ', but the layer isn\'t built. ' <ide> 'You can build it manually via: `' + <ide> self.name + '.build(batch_input_shape)`.') <del> return sum([K.count_params(p) for p in self.weights]) <add> return count_params(self.weights) <ide> <ide> <ide> class InputLayer(Layer): <ide><path>keras/engine/training.py <ide> from .. import losses <ide> from .. import metrics as metrics_module <ide> from ..utils.generic_utils import Progbar <add>from ..utils.layer_utils import count_params <ide> from .. import callbacks as cbks <ide> from ..legacy import interfaces <ide> <ide> def handle_metrics(metrics, weights=None): <ide> trainable_weights = self.trainable_weights <ide> self._collected_trainable_weights = trainable_weights <ide> <add> def _check_trainable_weights_consistency(self): <add> """Check trainable weights count consistency. <add> <add> This will raise a warning if `trainable_weights` and <add> `_collected_trainable_weights` are consistent (i.e. have the same <add> number of parameters). <add> Inconsistency will typically arise when one modifies `model.trainable` <add> without calling `model.compile` again. <add> """ <add> if not hasattr(self, '_collected_trainable_weights'): <add> return <add> <add> if (count_params(self.trainable_weights) != <add> count_params(self._collected_trainable_weights)): <add> warnings.warn(UserWarning( <add> 'Discrepancy between trainable weights and collected trainable' <add> ' weights, did you set `model.trainable` without calling' <add> ' `model.compile` after ?')) <add> <ide> def _make_train_function(self): <ide> if not hasattr(self, 'train_function'): <ide> raise RuntimeError('You must compile your model before using it.') <add> self._check_trainable_weights_consistency() <ide> if self.train_function is None: <ide> inputs = self._feed_inputs + self._feed_targets + self._feed_sample_weights <ide> if self.uses_learning_phase and not isinstance(K.learning_phase(), int): <ide><path>keras/utils/layer_utils.py <ide> import numpy as np <ide> <ide> <add>def count_params(weights): <add> """Count the total number of scalars composing the weights. <add> <add> # Arguments <add> weights: An iterable containing the weights on which to compute params <add> <add> # Returns <add> The total number of scalars composing the weights <add> """ <add> return int(np.sum([K.count_params(p) for p in set(weights)])) <add> <add> <ide> def print_summary(model, line_length=None, positions=None, print_fn=print): <ide> """Prints a summary of a model. <ide> <ide> def print_layer_summary_with_connections(layer): <ide> else: <ide> print_fn('_' * line_length) <ide> <del> trainable_count = int( <del> np.sum([K.count_params(p) for p in set(model.trainable_weights)])) <add> model._check_trainable_weights_consistency() <add> if hasattr(model, '_collected_trainable_weights'): <add> trainable_count = count_params(model._collected_trainable_weights) <add> else: <add> trainable_count = count_params(model.trainable_weights) <add> <ide> non_trainable_count = int( <ide> np.sum([K.count_params(p) for p in set(model.non_trainable_weights)])) <ide> <ide><path>tests/keras/engine/test_training.py <ide> def test_model_custom_target_tensors(): <ide> [output_a_np, output_b_np]) <ide> <ide> <add>@pytest.mark.skipif(sys.version_info < (3,), reason='Cannot catch warnings in python 2') <add>@keras_test <add>def test_trainable_weights_count_consistency(): <add> """Tests the trainable weights consistency check of Model. <add> <add> This verifies that a warning is shown if model.trainable is modified <add> and the model is summarized/run without a new call to .compile() <add> <add> Reproduce issue #8121 <add> """ <add> a = Input(shape=(3,), name='input_a') <add> model1 = Model(inputs=a, outputs=Dense(1)(a)) <add> <add> model1.trainable = False <add> b = Input(shape=(3,), name='input_b') <add> y = model1(b) <add> model2 = Model(inputs=b, outputs=Dense(1)(y)) <add> <add> model2.compile(optimizer='adam', loss='mse') <add> <add> model1.trainable = True <add> <add> # Should warn on .summary() <add> with pytest.warns(UserWarning) as w: <add> model2.summary() <add> warning_raised = any(['Discrepancy' in str(w_.message) for w_ in w]) <add> assert warning_raised, 'No warning raised when trainable is modified without .compile.' <add> <add> # And on .fit() <add> with pytest.warns(UserWarning) as w: <add> model2.fit(x=np.zeros((5, 3)), y=np.zeros((5, 1))) <add> warning_raised = any(['Discrepancy' in str(w_.message) for w_ in w]) <add> assert warning_raised, 'No warning raised when trainable is modified without .compile.' <add> <add> # And shouldn't warn if we recompile <add> model2.compile(optimizer='adam', loss='mse') <add> with pytest.warns(None) as w: <add> model2.summary() <add> assert len(w) == 0, "Warning raised even when .compile() is called after modifying .trainable" <add> <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
4
Ruby
Ruby
remove useless conditional
67b1a7942e8b0bc2f30af78bbcb81c535a87e5dc
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb <ide> def render_partial(view, template, block) <ide> layout = find_template(layout.to_s, template_keys) <ide> end <ide> <del> object = locals[as] if object.nil? # Respect object when object is false <ide> locals[as] = object if @has_object <ide> <ide> content = template.render(view, locals) do |*name|
1
Ruby
Ruby
use short hash for git last_commit
45b3bfd11ac1d9d12d0e885576702eab2acc60cb
<ide><path>Library/Homebrew/download_strategy.rb <ide> def source_modified_time <ide> end <ide> <ide> def last_commit <del> Utils.popen_read("git", "--git-dir", git_dir ,"rev-parse", "HEAD").chomp <add> Utils.popen_read("git", "--git-dir", git_dir ,"rev-parse", "--short", "HEAD").chomp <ide> end <ide> <ide> private
1
Text
Text
fix typo in http2 endafterheaders description
7643c5239dd12f5190c5bf2bb3cce7d11d12b3f8
<ide><path>doc/api/http2.md <ide> added: v10.11.0 <ide> <ide> * {boolean} <ide> <del>Set the `true` if the `END_STREAM` flag was set in the request or response <add>Set to `true` if the `END_STREAM` flag was set in the request or response <ide> HEADERS frame received, indicating that no additional data should be received <ide> and the readable side of the `Http2Stream` will be closed. <ide>
1
Python
Python
fix failing test in test_multi
768562ffd48859febd9a5b07329fa661136128a2
<ide><path>celery/tests/bin/test_multi.py <ide> def test_info_not_verbose(self): <ide> self.assertFalse(self.fh.getvalue()) <ide> <ide> def test_error(self): <del> self.t.say = Mock() <add> self.t.carp = Mock() <ide> self.t.usage = Mock() <ide> self.assertEqual(self.t.error('foo'), 1) <del> self.t.say.assert_called_with('foo') <add> self.t.carp.assert_called_with('foo') <ide> self.t.usage.assert_called_with() <ide> <del> self.t.say = Mock() <add> self.t.carp = Mock() <ide> self.assertEqual(self.t.error(), 1) <del> self.assertFalse(self.t.say.called) <add> self.assertFalse(self.t.carp.called) <ide> <ide> self.assertEqual(self.t.retcode, 1) <ide>
1
Text
Text
update improved article, fixed references
92d62218bf4a49d096f61d97760a9290698012ff
<ide><path>guide/english/computer-science/data-structures/index.md <ide> title: Data Structures <ide> --- <ide> ## Data Structures <ide> <del>Data Structure is a way of collecting and organising data in such a way that we can perform operations on these data in an effective way. Data Structures is about rendering data elements in terms of some relationship, for better organization and storage. For example, we have data player's name "Virat" and age 26. Here "Virat" is of String data type and 26 is of integer data type. <add>Data Structure is a means of collecting and organising data so as to perform operations on it efficiently. It is a means to find relationships among data elements for better organization and storage. Let us say that we have the name and age of a number of cricket players and we have to find a way to categorise them. Consider the example of a player with the name "Virat" who is 26 years old. In this example, we'd categorise "Virat" as a string which is a basically a collection of characters and the age as an integer. <ide> <del> We can organize this data as a record like Player record. Now we can collect and store player's records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag" 33 <add>We can now get a series of records of Players which is stored in the format as mentioned above. Every record has a string and an integer. And thus, this trivial example demonstrates how data structures are useful. <add>For example: <add>``` <add>"Dhoni" 30, "Gambhir" 31, "Sehwag" 33 <add>``` <add>would be how the data would be stored. <ide> <del>In simple language, Data Structures are structures programmed to store ordered data, so that various operations can be performed on it easily. It represents the knowledge of data to be organized in memory. It should be designed and implemented in such a way that it reduces the complexity and increases the effieciency. <add>In simpler terms, Data Structures are structures programmed to store ordered data, so that various operations can be performed on it easily. It should be designed and implemented in such a way that it reduces the complexity and increases the efficiency of access of data elements. <ide> <ide> <!-- Data Structures in memory--> <del>In Computer memory i.e RAM, different data structures are created like stack, queue, linked list, heaps, etc according to the requirement of the program so as to use the memory efficiently. <add>A few examples of standard Data Structures include: <add>* Array <add>* Stack <add>* Queue <add>* Tree <add>* Linked List <add>* Graphs <add>* Maps <ide> <add>**Note:** Data Types are not to be confused with Data Structures. Data Types are irreducible as opposed to Data Structures which consist of multiple fields of different data. In the above example, integer is a data type whereas the record(which consists of an integer and a string) is a data structure. <ide> <ide> #### More Information: <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <ide> * [Data Structures](http://www.studytonight.com/data-structures/introduction-to-data-structures) <del>* [Geek for Geek](http://www.geeksforgeeks.org/data-structures/) <add>* [Geeks for Geeks](http://www.geeksforgeeks.org/data-structures/) <ide> * [Tutorials Point](https://www.tutorialspoint.com/data_structures_algorithms/data_structure_overview.htm) <del>* [Data Structures](http://www.studytonight.com/data-structures/introduction-to-data-structures) <add>* [Difference between Data Structure and Data Type](https://stackoverflow.com/questions/4630377/explain-the-difference-between-a-data-structure-and-a-data-type)
1
Text
Text
update changelog for 2.8.3
8eaae63c965adfe9aa66f7cdd63bf184712ac1e5
<ide><path>CHANGELOG.md <ide> <ide> - No changes from 2.8.2. <ide> <add>### 2.8.3 (November 1, 2016) <add> <add>- [#14528](https://github.com/emberjs/ember.js/pull/14528) [BUGFIX] Fix memory leak (leaking component instances in the component registry). <add>- [#14509](https://github.com/emberjs/ember.js/pull/14509) [BUGFIX] Fix overwriting rest positional parameters when passed as named parameters. Allows `link-to` to be used as a contextual component. <add>- [#14550](https://github.com/emberjs/ember.js/pull/14550) [BUGFIX lts-2-8] Allow canceling items queued by `run.schedule`. <add> <ide> ### 2.8.2 (October 6, 2016) <ide> <ide> - [#14365](https://github.com/emberjs/ember.js/pull/14365) [BUGFIX] Fix an issue with URLs with encoded characters and a trailing slash.
1
Javascript
Javascript
add backend placeholder to solution form
f247090895217636df6cd574aa3777a554983491
<ide><path>client/src/templates/Challenges/projects/SolutionForm.js <ide> import PropTypes from 'prop-types'; <ide> <ide> import { Form } from '../../../components/formHelpers'; <ide> import { <add> backend, <ide> backEndProject, <ide> frontEndProject, <ide> pythonProject <ide> const propTypes = { <ide> updateSolutionForm: PropTypes.func.isRequired <ide> }; <ide> <del>const frontEndProjectFields = ['solution']; <del>const backEndProjectFields = ['solution', 'githubLink']; <add>// back end challenges and front end projects use a single form field <add>const solutionField = ['solutionLink']; <add>const backEndProjectFields = ['solutionLink', 'githubLink']; <ide> <ide> const options = { <ide> types: { <del> solution: 'url', <add> solutionLink: 'url', <ide> githubLink: 'url' <ide> }, <del> required: ['solution'] <add> required: ['solutionLink'] <ide> }; <ide> <ide> export class SolutionForm extends Component { <ide> export class SolutionForm extends Component { <ide> ? 'Submit and go to my next challenge' <ide> : "I've completed this challenge"; <ide> <del> let solutionFormFields = frontEndProjectFields; <del> let solutionLink = 'Link, ex: '; <add> let formFields = solutionField; <add> let solutionLink = 'ex: '; <ide> let solutionFormID = 'front-end-form'; <ide> <ide> switch (challengeType) { <ide> case frontEndProject: <del> solutionFormFields = frontEndProjectFields; <add> formFields = solutionField; <ide> solutionLink = <ide> solutionLink + 'https://codepen.io/camperbot/full/oNvPqqo'; <ide> break; <ide> <add> case backend: <add> formFields = solutionField; <add> solutionLink = solutionLink + 'https://project-name.camperbot.repl.co/'; <add> break; <add> <ide> case backEndProject: <del> solutionFormFields = backEndProjectFields; <add> formFields = backEndProjectFields; <ide> solutionLink = solutionLink + 'https://project-name.camperbot.repl.co/'; <ide> solutionFormID = 'back-end-form'; <ide> break; <ide> <ide> case pythonProject: <del> solutionFormFields = frontEndProjectFields; <add> formFields = solutionField; <ide> solutionLink = <ide> solutionLink + <ide> (description.includes('Colaboratory') <ide> export class SolutionForm extends Component { <ide> break; <ide> <ide> default: <del> solutionFormFields = frontEndProjectFields; <add> formFields = solutionField; <ide> solutionLink = <ide> solutionLink + 'https://codepen.io/camperbot/full/oNvPqqo'; <ide> } <ide> <ide> return ( <ide> <Form <ide> buttonText={`${buttonCopy}`} <del> formFields={solutionFormFields} <add> formFields={formFields} <ide> id={solutionFormID} <ide> options={{ <ide> ...options, <ide> placeholders: { <del> solution: solutionLink, <add> solutionLink: solutionLink, <ide> githubLink: 'ex: https://github.com/camperbot/hello' <ide> } <ide> }}
1
Python
Python
decrease refresh frequency
a5070b77177e55271a262fd856a194370fb36223
<ide><path>celery/bin/celeryev.py <ide> def abbrtask(S, max): <ide> class CursesMonitor(object): <ide> win = None <ide> screen_width = None <add> screen_delay = 0.1 <ide> selected_task = None <ide> selected_position = 0 <ide> selected_str = "Selected: " <ide> def resetscreen(self): <ide> curses.echo() <ide> curses.endwin() <ide> <add> def nap(self): <add> curses.napms(int(self.screen_delay * 1000)) <add> <ide> @property <ide> def tasks(self): <ide> return self.state.tasks_by_timestamp()[:self.limit] <ide> def __init__(self, display): <ide> def run(self): <ide> while not self.shutdown: <ide> self.display.draw() <add> self.display.nap() <ide> <ide> <ide> def eventtop():
1
Text
Text
add apapirovski to tsc
04195adaa953e339d71dff7ae59d5261a0294895
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> <ide> * [addaleax](https://github.com/addaleax) - <ide> **Anna Henningsen** &lt;[email protected]&gt; (she/her) <add>* [apapirovski](https://github.com/apapirovski) - <add>**Anatoli Papirovski** &lt;[email protected]&gt; (he/him) <ide> * [ChALkeR](https://github.com/ChALkeR) - <ide> **Сковорода Никита Андреевич** &lt;[email protected]&gt; (he/him) <ide> * [cjihrig](https://github.com/cjihrig) -
1
Javascript
Javascript
fix bug of "reopen project" menu
21b4a2147a6a8e3899010f71576e522a408bcd41
<ide><path>src/menu-helpers.js <ide> function cloneMenuItem(item) { <ide> item, <ide> 'type', <ide> 'label', <add> 'id', // added for atom-i18n package, and used only internal. <ide> 'enabled', <ide> 'visible', <ide> 'command', <ide> function cloneMenuItem(item) { <ide> 'beforeGroupContaining', <ide> 'afterGroupContaining' <ide> ); <del> if (item.id === null || item.id === undefined) { item.id = normalizeLabel(item.label) } <add> if (item.id === null || item.id === undefined) { <add> // item.id is internally used by the function defined in this file, because `atom-i18n` localize item.label. <add> // cloneMenuItem() create menus from template (menu_{darwin, linux, win32}.cson), then `atom-i18n` can localize menu. <add> item.id = normalizeLabel(item.label) <add> } <ide> if (item.submenu != null) { <ide> item.submenu = item.submenu.map(submenuItem => cloneMenuItem(submenuItem)); <ide> } <ide><path>src/reopen-project-menu-manager.js <ide> module.exports = class ReopenProjectMenuManager { <ide> static createProjectsMenu(projects) { <ide> return { <ide> label: 'File', <add> id: 'File', <ide> submenu: [ <ide> { <ide> label: 'Reopen Project', <add> id: 'Reopen Project', <ide> submenu: projects.map((project, index) => ({ <ide> label: this.createLabel(project), <ide> command: 'application:reopen-project',
2
PHP
PHP
add .phar to blocked php extensions
ccea1bfcbb37cf923dc1bb30cdbf2effbfb1619c
<ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> protected function shouldBlockPhpUpload($value, $parameters) <ide> } <ide> <ide> $phpExtensions = [ <del> 'php', 'php3', 'php4', 'php5', 'phtml', <add> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar', <ide> ]; <ide> <ide> return ($value instanceof UploadedFile)
1
PHP
PHP
refresh the retryuntil timer on job retry
72596ae3612bb6dfa21468f8d7d77f6cc545890d
<ide><path>src/Illuminate/Queue/Console/RetryCommand.php <ide> protected function getJobIdsByRanges(array $ranges) <ide> protected function retryJob($job) <ide> { <ide> $this->laravel['queue']->connection($job->connection)->pushRaw( <del> $this->resetAttempts($job->payload), $job->queue <add> $this->retryRefresh($job->payload), $job->queue <ide> ); <ide> } <ide> <add> /** <add> * Possibly refresh job attempts and retryUntil value <add> * <add> * @param string $payload <add> * @return string <add> */ <add> protected function retryRefresh($payload) <add> { <add> $payload = $this->resetAttempts($payload); <add> <add> $payload = $this->refreshRetryUntil($payload); <add> <add> return $payload; <add> } <add> <ide> /** <ide> * Reset the payload attempts. <ide> * <ide> protected function resetAttempts($payload) <ide> <ide> return json_encode($payload); <ide> } <add> <add> /** <add> * Refreshes a jobs retryUntil time with it's own retryUntil method <add> * <add> * @param string $payload <add> * @return string <add> */ <add> protected function refreshRetryUntil($payload) <add> { <add> $payload = json_decode($payload, true); <add> <add> $jobInstance = unserialize($payload['data']['command']); <add> <add> $newRetryUntil = $jobInstance->retryUntil()->timestamp; <add> <add> $payload['retryUntil'] = $newRetryUntil; <add> <add> return json_encode($payload); <add> } <ide> }
1
PHP
PHP
apply fixes from styleci
71265318358ee150fe8b13f68a03cb9f869fb483
<ide><path>tests/Container/ContainerTest.php <ide> public function testContainerCanResolveClasses() <ide> $this->assertInstanceOf(ContainerConcreteStub::class, $class); <ide> } <ide> <del> public function testContainerCanCatchCircularDependency() { <add> public function testContainerCanCatchCircularDependency() <add> { <ide> $this->expectException(CircularDependencyException::class); <ide> <ide> $container = new Container; <ide> $container->get(CircularAStub::class); <ide> } <ide> } <ide> <del>class CircularAStub { <del> public function __construct(CircularBStub $b) { <del> <add>class CircularAStub <add>{ <add> public function __construct(CircularBStub $b) <add> { <ide> } <ide> } <ide> <del>class CircularBStub { <del> public function __construct(CircularCStub $c) { <del> <add>class CircularBStub <add>{ <add> public function __construct(CircularCStub $c) <add> { <ide> } <ide> } <ide> <del>class CircularCStub { <del> public function __construct(CircularAStub $a) { <del> <add>class CircularCStub <add>{ <add> public function __construct(CircularAStub $a) <add> { <ide> } <ide> } <ide>
1
PHP
PHP
remove extra lines
eff1f84050c9e2711ce552000d24a47e7482c06d
<ide><path>app/Providers/ErrorServiceProvider.php <ide> public function boot() <ide> // even register several error handlers to handle different types of <ide> // exceptions. If nothing is returned, the default error view is <ide> // shown, which includes a detailed stack trace during debug. <del> <ide> App::error(function(Exception $e) <ide> { <ide> Log::error($e); <ide><path>app/Providers/RouteServiceProvider.php <ide> public function map() <ide> // Once the application has booted, we will include the default routes <ide> // file. This "namespace" helper will load the routes file within a <ide> // route group which automatically sets the controller namespace. <del> <ide> $this->namespaced(function() <ide> { <ide> require app_path().'/Http/routes.php';
2
Javascript
Javascript
add more error checking for font translation
050acaf5e07ddddcea4892b649fe7f4352333429
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> constructor.prototype = { <ide> translateFont: function(fontDict, xref, resources) { <ide> var descriptor = xref.fetch(fontDict.get("FontDescriptor")); <del> var fontName = descriptor.get("FontName").name; <del> fontName = fontName.replace("+", "_"); <add> <add> var fontName = descriptor.get("FontName"); <add> assertWellFormed(IsName(fontName), "invalid font name"); <add> fontName = fontName.name.replace("+", "_"); <ide> <ide> var fontFile = descriptor.get2("FontFile", "FontFile2"); <ide> if (!fontFile) <ide> var CanvasGraphics = (function() { <ide> <ide> // Get the font charset if any <ide> var charset = descriptor.get("CharSet"); <del> if (charset) <del> charset = charset.split("/"); <add> assertWellFormed(IsString(charset), "invalid charset"); <ide> <add> charset = charset.split("/"); <ide> } else if (IsName(encoding)) { <del> var encoding = Encodings[encoding]; <add> var encoding = Encodings[encoding.name]; <ide> if (!encoding) <ide> error("Unknown encoding"); <ide> <ide> var widths = xref.fetchIfRef(fontDict.get("Widths")); <ide> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar")); <del> alert(firstchar); <ide> assertWellFormed(IsArray(widths) && IsInteger(firstChar), <ide> "invalid Widths or FirstChar"); <ide> var charset = []; <ide> var CanvasGraphics = (function() { <ide> <ide> return { <ide> name: fontName, <del> file: fontFile, <del> properties: properties <add> file: fontFile, <add> properties: properties <ide> } <ide> }, <ide>
1
Python
Python
change version number on master to 1.8
eee46518b869ae05490c085783fd5b09a40b2273
<ide><path>setup.py <ide> AUTHOR_EMAIL = "[email protected]" <ide> PLATFORMS = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"] <ide> MAJOR = 1 <del>MINOR = 7 <add>MINOR = 8 <ide> MICRO = 0 <ide> ISRELEASED = False <ide> VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
1
Text
Text
add options description for send apis
5d1578d85b6f09d827a6fe954d0617e1c13267b3
<ide><path>doc/api/cluster.md <ide> Workers will call `process.exit(0)` if the `'disconnect'` event occurs <ide> on `process` and `.exitedAfterDisconnect` is not `true`. This protects against <ide> accidental disconnection. <ide> <del>### worker.send(message\[, sendHandle\]\[, callback\]) <add>### worker.send(message\[, sendHandle\[, options\]\]\[, callback\]) <ide> <!-- YAML <ide> added: v0.7.0 <ide> changes: <ide> changes: <ide> <ide> * `message` {Object} <ide> * `sendHandle` {Handle} <add>* `options` {Object} The `options` argument, if present, is an object used to <add> parameterize the sending of certain types of handles. `options` supports <add> the following properties: <add> * `keepOpen` {boolean} A value that can be used when passing instances of <add> `net.Socket`. When `true`, the socket is kept open in the sending process. <add> **Default:** `false`. <ide> * `callback` {Function} <ide> * Returns: {boolean} <ide> <ide><path>doc/api/process.md <ide> added: v0.5.9 <ide> <ide> * `message` {Object} <ide> * `sendHandle` {net.Server|net.Socket} <del>* `options` {Object} <add>* `options` {Object} used to parameterize the sending of certain types of <add> handles.`options` supports the following properties: <add> * `keepOpen` {boolean} A value that can be used when passing instances of <add> `net.Socket`. When `true`, the socket is kept open in the sending process. <add> **Default:** `false`. <ide> * `callback` {Function} <ide> * Returns: {boolean} <ide>
2
Ruby
Ruby
fix last changeset to pass unittests
2e175d35cd4fc4438f6d263c8fe205939cd4b95f
<ide><path>actionpack/lib/action_controller/assertions.rb <ide> def assert_generates(expected_path, options, defaults={}, extras = {}, message=n <ide> # Load routes.rb if it hasn't been loaded. <ide> ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? <ide> <del> generated_path, found_extras = ActionController::Routing::Routes.generate(options, extras) <add> generated_path, extra_keys = ActionController::Routing::Routes.generate(options, extras) <add> found_extras = options.reject {|k, v| ! extra_keys.include? k} <add> <ide> msg = build_message(message, "found extras <?>, not <?>", found_extras, extras) <ide> assert_block(msg) { found_extras == extras } <ide> <ide><path>actionpack/lib/action_controller/url_rewriter.rb <ide> def rewrite_url(path, options) <ide> rewritten_url <ide> end <ide> <del> def rewrite_path(original_options) <del> options = original_options.symbolize_keys <del> options.update(params.symbolize_keys) if (params = options[:params]) <add> def rewrite_path(options) <add> options = options.symbolize_keys <add> options.update(options[:params].symbolize_keys) if options[:params] <ide> RESERVED_OPTIONS.each {|k| options.delete k} <del> path, extra_keys = Routing::Routes.generate(options, @request) # Warning: Routes will mutate and violate the options hash <add> path, extra_keys = Routing::Routes.generate(options.dup, @request) # Warning: Routes will mutate and violate the options hash <ide> <del> path << build_query_string(original_options.symbolize_keys, extra_keys) unless extra_keys.empty? <add> path << build_query_string(options, extra_keys) unless extra_keys.empty? <ide> <ide> path <ide> end
2
PHP
PHP
add test for inline attachments
f366a9ff834b96f3b971568916b40b06e1f8cc16
<ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSendNoTemplateWithAttachmentsAsBoth() { <ide> $this->assertContains($expected, $result['message']); <ide> } <ide> <add>/** <add> * Test setting inline attachments and messages. <add> * <add> * @return void <add> */ <add> public function testSendWithInlineAttachments() { <add> $this->CakeEmail->transport('debug'); <add> $this->CakeEmail->from('[email protected]'); <add> $this->CakeEmail->to('[email protected]'); <add> $this->CakeEmail->subject('My title'); <add> $this->CakeEmail->emailFormat('both'); <add> $this->CakeEmail->attachments(array( <add> 'cake.png' => array( <add> 'file' => CAKE . 'VERSION.txt', <add> 'contentId' => 'abc123' <add> ) <add> )); <add> $result = $this->CakeEmail->send('Hello'); <add> <add> $boundary = $this->CakeEmail->getBoundary(); <add> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']); <add> $expected = "--$boundary\r\n" . <add> "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" . <add> "\r\n" . <add> "--rel-$boundary\r\n" . <add> "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" . <add> "\r\n" . <add> "--alt-$boundary\r\n" . <add> "Content-Type: text/plain; charset=UTF-8\r\n" . <add> "Content-Transfer-Encoding: 8bit\r\n" . <add> "\r\n" . <add> "Hello" . <add> "\r\n" . <add> "\r\n" . <add> "\r\n" . <add> "--alt-$boundary\r\n" . <add> "Content-Type: text/html; charset=UTF-8\r\n" . <add> "Content-Transfer-Encoding: 8bit\r\n" . <add> "\r\n" . <add> "Hello" . <add> "\r\n" . <add> "\r\n" . <add> "\r\n" . <add> "--alt-{$boundary}--\r\n" . <add> "\r\n" . <add> "--$boundary\r\n" . <add> "Content-Type: application/octet-stream\r\n" . <add> "Content-Transfer-Encoding: base64\r\n" . <add> "Content-ID: <abc123>\r\n" . <add> "Content-Disposition: inline; filename=\"cake.png\"\r\n\r\n"; <add> $this->assertContains($expected, $result['message']); <add> $this->assertContains('--rel-' . $boundary . '--', $result['message']); <add> $this->assertContains('--' . $boundary . '--', $result['message']); <add>} <add> <ide> /** <ide> * testSendWithLog method <ide> *
1
Javascript
Javascript
fix a grammar problem
45a439c75ff92dbd38d8972256781a02666435db
<ide><path>lib/library/ModuleLibraryPlugin.js <ide> class ModuleLibraryPlugin extends AbstractLibraryPlugin { <ide> const { name } = library; <ide> if (name) { <ide> throw new Error( <del> `Library name must unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` <add> `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` <ide> ); <ide> } <ide> return {
1
PHP
PHP
move view error binding to a service provider
ab6bd591304b87720ea39401a090db0b6e71ba55
<ide><path>src/Illuminate/View/Middleware/ErrorBinder.php <add><?php namespace Illuminate\View\Middleware; <add> <add>use Closure; <add>use Illuminate\Support\ViewErrorBag; <add>use Illuminate\Contracts\Routing\Middleware; <add>use Illuminate\Contracts\View\Factory as ViewFactory; <add> <add>class ErrorBinder implements Middleware { <add> <add> /** <add> * The view factory implementation. <add> * <add> * @var \Illuminate\Contracts\View\Factory <add> */ <add> protected $view; <add> <add> /** <add> * Create a new error binder instance. <add> * <add> * @param \Illuminate\Contracts\View\Factory $view <add> * @return void <add> */ <add> public function __construct(ViewFactory $view) <add> { <add> $this->view = $view; <add> } <add> <add> /** <add> * Handle an incoming request. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @param \Closure $next <add> * @return mixed <add> */ <add> public function handle($request, Closure $next) <add> { <add> // If the current session has an "errors" variable bound to it, we will share <add> // its value with all view instances so the views can easily access errors <add> // without having to bind. An empty bag is set when there aren't errors. <add> if ($request->session()->has('errors')) <add> { <add> $this->view->share( <add> 'errors', $request->session()->get('errors') <add> ); <add> } <add> <add> // Putting the errors in the view for every view allows the developer to just <add> // assume that some errors are always available, which is convenient since <add> // they don't have to continually run checks for the presence of errors. <add> else <add> { <add> $this->view->share('errors', new ViewErrorBag); <add> } <add> <add> return $next($request); <add> } <add> <add>} <ide><path>src/Illuminate/View/ViewServiceProvider.php <ide> public function register() <ide> <ide> $this->registerViewFinder(); <ide> <del> // Once the other components have been registered we're ready to include the <del> // view environment and session binder. The session binder will bind onto <del> // the "before" application event and add errors into shared view data. <ide> $this->registerFactory(); <del> <del> $this->registerSessionBinder(); <ide> } <ide> <ide> /** <ide> public function registerFactory() <ide> }); <ide> } <ide> <del> /** <del> * Register the session binder for the view environment. <del> * <del> * @return void <del> */ <del> protected function registerSessionBinder() <del> { <del> list($app, $me) = array($this->app, $this); <del> <del> $app->booted(function() use ($app, $me) <del> { <del> // If the current session has an "errors" variable bound to it, we will share <del> // its value with all view instances so the views can easily access errors <del> // without having to bind. An empty bag is set when there aren't errors. <del> if ($me->sessionHasErrors($app)) <del> { <del> $errors = $app['session.store']->get('errors'); <del> <del> $app['view']->share('errors', $errors); <del> } <del> <del> // Putting the errors in the view for every view allows the developer to just <del> // assume that some errors are always available, which is convenient since <del> // they don't have to continually run checks for the presence of errors. <del> else <del> { <del> $app['view']->share('errors', new ViewErrorBag); <del> } <del> }); <del> } <del> <del> /** <del> * Determine if the application session has errors. <del> * <del> * @param \Illuminate\Foundation\Application $app <del> * @return bool <del> */ <del> public function sessionHasErrors($app) <del> { <del> $config = $app['config']['session']; <del> <del> if (isset($app['session.store']) && ! is_null($config['driver'])) <del> { <del> return $app['session.store']->has('errors'); <del> } <del> } <del> <ide> }
2
Javascript
Javascript
bring bundle example up-to-date
14bd4fb5c50d84a744d0a5fb60c902ade7396696
<ide><path>examples/bundle/bundle-treemap.js <del>var w = 960, <del> h = 500, <add>var width = 960, <add> height = 500, <ide> fill = d3.scale.ordinal().range(colorbrewer.Greys[9].slice(1, 4)), <ide> stroke = d3.scale.linear().domain([0, 1e4]).range(["brown", "steelblue"]); <ide> <ide> var treemap = d3.layout.treemap() <del> .size([w, h]) <add> .size([width, height]) <ide> .value(function(d) { return d.size; }); <ide> <ide> var bundle = d3.layout.bundle(); <ide> <ide> var div = d3.select("#chart").append("div") <ide> .style("position", "relative") <del> .style("width", w + "px") <del> .style("height", h + "px"); <add> .style("width", width + "px") <add> .style("height", height + "px"); <ide> <ide> var line = d3.svg.line() <ide> .interpolate("bundle") <ide> d3.json("../data/flare-imports.json", function(classes) { <ide> .text(function(d) { return d.children ? null : d.key; }); <ide> <ide> div.append("svg") <del> .attr("width", w) <del> .attr("height", h) <add> .attr("width", width) <add> .attr("height", height) <ide> .style("position", "absolute") <ide> .selectAll("path.link") <ide> .data(bundle(links))
1
Mixed
Go
fix nits in comments and log
a1ed5b7be248ed0bbf7a33d3ae1902965994cc53
<ide><path>libnetwork/datastore/datastore.go <ide> func makeDefaultScopes() map[string]*ScopeCfg { <ide> var defaultRootChain = []string{"docker", "network", "v1.0"} <ide> var rootChain = defaultRootChain <ide> <del>// DefaultScopes returns a map of default scopes and it's config for clients to use. <add>// DefaultScopes returns a map of default scopes and its config for clients to use. <ide> func DefaultScopes(dataDir string) map[string]*ScopeCfg { <ide> if dataDir != "" { <ide> defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db" <ide><path>libnetwork/discoverapi/discoverapi.go <ide> package discoverapi <ide> <del>// Discover is an interface to be implemented by the componenet interested in receiving discover events <add>// Discover is an interface to be implemented by the component interested in receiving discover events <ide> // like new node joining the cluster or datastore updates <ide> type Discover interface { <ide> // DiscoverNew is a notification for a new discovery event, Example:a new node joining a cluster <ide><path>libnetwork/docs/macvlan.md <ide> Instead of attaching container network interfaces to a Docker host Linux bridge <ide> <ide> When using traditional Linux bridges there are two common techniques to get traffic out of a container and into the physical network and vice versa. The first method to connect containers to the underlying network is to use Iptable rules which perform a NAT translation from a bridge that represents the Docker network to the physical Ethernet connection such as `eth0`. The upside of Iptables using the Docker built-in bridge driver is that the NIC does not have to be in promiscuous mode. The second bridge driver method is to move a host's external Ethernet connection into the bridge. Moving the host Ethernet connection can at times be unforgiving. Common mistakes such as cutting oneself off from the host, or worse, creating bridging loops that can cripple a VLAN throughout a data center can open a network design up to potential risks as the infrastructure grows. <ide> <del>Connecting containers without any NATing is where the VLAN drivers accel. Rather then having to manage a bridge for each Docker network containers are connected directly to a `parent` interface such as `eth0` that attaches the container to the same broadcast domain as the parent interface. A simple example is if a host's `eth0` is on the network `192.168.1.0/24` with a gateway of `192.168.1.1` then a Macvlan Docker network can start containers on the addresses `192.168.1.2 - 192.168.1.254`. Containers use the same network as the parent `-o parent` that is specified in the `docker network create` command. <add>Connecting containers without any NATing is where the VLAN drivers accel. Rather than having to manage a bridge for each Docker network containers are connected directly to a `parent` interface such as `eth0` that attaches the container to the same broadcast domain as the parent interface. A simple example is if a host's `eth0` is on the network `192.168.1.0/24` with a gateway of `192.168.1.1` then a Macvlan Docker network can start containers on the addresses `192.168.1.2 - 192.168.1.254`. Containers use the same network as the parent `-o parent` that is specified in the `docker network create` command. <ide> <ide> There are positive performance implication as a result of bypassing the Linux bridge, along with the simplicity of less moving parts, which is also attractive. Macvlan containers are easy to troubleshoot. The actual MAC and IP address of the container is bridged into the upstream network making a problematic application easy for operators to trace from the network. Existing underlay network management and monitoring tools remain relevant. <ide> <ide> For more on Docker networking commands see: [Working with Docker network command <ide> <ide> VLANs have long been a primary means of virtualizing data center networks and are still in virtually all existing networks today. VLANs work by tagging a Layer-2 isolation domain with a 12-bit identifier ranging from 1-4094. The VLAN tag is inserted into a packet header that enables a logical grouping of a single subnet or multiple subnets of IPv4 and/or IPv6. It is very common for network operators to separate traffic using VLANs based on a subnet(s) function or security profile such as `web`, `db` or any other isolation requirements. <ide> <del>It is very common to have a compute host requirement of running multiple virtual networks concurrently on a host. Linux networking has long supported VLAN tagging, also known by it's standard 802.1Q, for maintaining datapath isolation between networks. The Ethernet link connected to a Docker host can be configured to support the 802.1q VLAN IDs by creating Linux sub-interfaces, each sub-interface being allocated a unique VLAN ID. <add>It is very common to have a compute host requirement of running multiple virtual networks concurrently on a host. Linux networking has long supported VLAN tagging, also known by its standard 802.1Q, for maintaining datapath isolation between networks. The Ethernet link connected to a Docker host can be configured to support the 802.1q VLAN IDs by creating Linux sub-interfaces, each sub-interface being allocated a unique VLAN ID. <ide> <ide> ![Simple Macvlan Mode Example](images/multi_tenant_8021q_vlans.png) <ide> <ide> In the next example, the network is tagged and isolated by the Docker host. A pa <ide> <ide> ``` <ide> # now add networks and hosts as you would normally by attaching to the master (sub)interface that is tagged <del>docker network create -d macvlan \ <add>docker network create -d macvlan \ <ide> --subnet=192.168.50.0/24 \ <ide> --gateway=192.168.50.1 \ <ide> -o parent=eth0.50 macvlan50 <ide> In the second network, tagged and isolated by the Docker host, `eth0.60` is the <ide> <ide> ``` <ide> # now add networks and hosts as you would normally by attaching to the master (sub)interface that is tagged. <del>docker network create -d macvlan \ <add>docker network create -d macvlan \ <ide> --subnet=192.168.60.0/24 \ <ide> --gateway=192.168.60.1 \ <ide> -o parent=eth0.60 -o \ <ide> The same as the example before except there is an additional subnet bound to the <ide> <ide> <ide> ``` <del>docker network create -d macvlan \ <add>docker network create -d macvlan \ <ide> --subnet=10.1.20.0/24 --subnet=10.1.10.0/24 \ <ide> --gateway=10.1.20.1 --gateway=10.1.10.1 \ <ide> -o parent=eth0.101 mcv101 <ide><path>libnetwork/drivers/macvlan/macvlan_endpoint.go <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> return nil <ide> } <ide> <del>// DeleteEndpoint remove the endpoint and associated netlink interface <add>// DeleteEndpoint removes the endpoint and associated netlink interface <ide> func (d *driver) DeleteEndpoint(nid, eid string) error { <ide> defer osl.InitOSContext()() <ide> if err := validateID(nid, eid); err != nil { <ide><path>libnetwork/drivers/macvlan/macvlan_network.go <ide> func (d *driver) createNetwork(config *configuration) error { <ide> return 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> func parseNetworkOptions(id string, option options.Generic) (*configuration, err <ide> return config, nil <ide> } <ide> <del>// parseNetworkGenericOptions parse generic driver docker network options <add>// parseNetworkGenericOptions parses generic driver docker network options <ide> func parseNetworkGenericOptions(data interface{}) (*configuration, error) { <ide> var ( <ide> err error <ide><path>libnetwork/drivers/macvlan/macvlan_setup.go <ide> func setMacVlanMode(mode string) (netlink.MacvlanMode, error) { <ide> } <ide> } <ide> <del>// parentExists check if the specified interface exists in the default namespace <add>// parentExists checks if the specified interface exists in the default namespace <ide> func parentExists(ifaceStr string) bool { <ide> _, err := ns.NlHandle().LinkByName(ifaceStr) <ide> if err != nil { <ide><path>libnetwork/endpoint.go <ide> func (ep *endpoint) Delete(force bool) error { <ide> ep.releaseAddress() <ide> <ide> if err := n.getEpCnt().DecEndpointCnt(); err != nil { <del> log.Warnf("failed to decrement endpoint coint for ep %s: %v", ep.ID(), err) <add> log.Warnf("failed to decrement endpoint count for ep %s: %v", ep.ID(), err) <ide> } <ide> <ide> return nil <ide><path>libnetwork/error.go <ide> func (nnr NetworkNameError) Error() string { <ide> // Forbidden denotes the type of this error <ide> func (nnr NetworkNameError) Forbidden() {} <ide> <del>// UnknownNetworkError is returned when libnetwork could not find in it's database <add>// UnknownNetworkError is returned when libnetwork could not find in its database <ide> // a network with the same name and id. <ide> type UnknownNetworkError struct { <ide> name string <ide><path>libnetwork/network.go <ide> type Network interface { <ide> Type() string <ide> <ide> // Create a new endpoint to this network symbolically identified by the <del> // specified unique name. The options parameter carry driver specific options. <add> // specified unique name. The options parameter carries driver specific options. <ide> CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) <ide> <ide> // Delete the network. <ide><path>libnetwork/resolvconf/resolvconf.go <ide> func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) { <ide> // if the resulting resolvConf has no more nameservers defined, add appropriate <ide> // default DNS servers for IPv4 and (optionally) IPv6 <ide> if len(GetNameservers(cleanedResolvConf, types.IP)) == 0 { <del> logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultIPv4Dns) <add> logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: %v", defaultIPv4Dns) <ide> dns := defaultIPv4Dns <ide> if ipv6Enabled { <del> logrus.Infof("IPv6 enabled; Adding default IPv6 external servers : %v", defaultIPv6Dns) <add> logrus.Infof("IPv6 enabled; Adding default IPv6 external servers: %v", defaultIPv6Dns) <ide> dns = append(dns, defaultIPv6Dns...) <ide> } <ide> cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
10
Javascript
Javascript
update examples to use modules
1534529f8ce746140bcd66725c748ae70bfb4fdb
<ide><path>src/ng/directive/input.js <ide> var ngValueDirective = function() { <ide> form will update the model only when the control loses focus (blur event). If `escape` key is <ide> pressed while the input field is focused, the value is reset to the value in the current model. <ide> <del> <example name="ngModelOptions-directive-blur"> <add> <example name="ngModelOptions-directive-blur" module="optionsExample"> <ide> <file name="index.html"> <del> <div ng-controller="Ctrl"> <add> <div ng-controller="ExampleController"> <ide> <form name="userForm"> <ide> Name: <ide> <input type="text" name="userName" <ide> var ngValueDirective = function() { <ide> </div> <ide> </file> <ide> <file name="app.js"> <del> function Ctrl($scope) { <del> $scope.user = { name: 'say', data: '' }; <add> angular.module('optionsExample', []) <add> .controller('ExampleController', ['$scope', function($scope) { <add> $scope.user = { name: 'say', data: '' }; <ide> <del> $scope.cancel = function (e) { <del> if (e.keyCode == 27) { <del> $scope.userForm.userName.$rollbackViewValue(); <del> } <del> }; <del> } <add> $scope.cancel = function (e) { <add> if (e.keyCode == 27) { <add> $scope.userForm.userName.$rollbackViewValue(); <add> } <add> }; <add> }]); <ide> </file> <ide> <file name="protractor.js" type="protractor"> <ide> var model = element(by.binding('user.name')); <ide> var ngValueDirective = function() { <ide> This one shows how to debounce model changes. Model will be updated only 1 sec after last change. <ide> If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. <ide> <del> <example name="ngModelOptions-directive-debounce"> <add> <example name="ngModelOptions-directive-debounce" module="optionsExample"> <ide> <file name="index.html"> <del> <div ng-controller="Ctrl"> <add> <div ng-controller="ExampleController"> <ide> <form name="userForm"> <ide> Name: <ide> <input type="text" name="userName" <ide> var ngValueDirective = function() { <ide> </div> <ide> </file> <ide> <file name="app.js"> <del> function Ctrl($scope) { <del> $scope.user = { name: 'say' }; <del> } <add> angular.module('optionsExample', []) <add> .controller('ExampleController', ['$scope', function($scope) { <add> $scope.user = { name: 'say' }; <add> }]); <ide> </file> <ide> </example> <ide> */
1
Ruby
Ruby
allow anonymous access in private registries
cc12738f8e31b5a674057a2945fdbda7c2c12825
<ide><path>Library/Homebrew/download_strategy.rb <ide> class CurlGitHubPackagesDownloadStrategy < CurlDownloadStrategy <ide> def initialize(url, name, version, **meta) <ide> meta ||= {} <ide> meta[:headers] ||= [] <del> token = ENV.fetch("HOMEBREW_REGISTRY_ACCESS_TOKEN", "QQ==") <del> meta[:headers] << ["Authorization: Bearer #{token}"] <add> token = Homebrew::EnvConfig.artifact_domain ? ENV.fetch("HOMEBREW_REGISTRY_ACCESS_TOKEN", "") : "QQ==" <add> meta[:headers] << ["Authorization: Bearer #{token}"] unless token.empty? <ide> super(url, name, version, meta) <ide> end <ide>
1