content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | add lost log messages about template rendering | cdda7defa0a37ff776ca961c8eeae347a46dd59b | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def reset_session #:doc:
<ide>
<ide> private
<ide> def render_for_file(template_path, status = nil, layout = nil, locals = {}) #:nodoc:
<del> logger.info("Rendering #{template_path}" + (status ? " (#{status})" : '')) if logger
<ide> render_for_text @template.render(:file => template_path, :locals => locals, :layout => layout), status
<ide> end
<ide>
<ide><path>actionpack/lib/action_view/base.rb
<ide> def render(options = {}, local_assigns = {}, &block) #:nodoc:
<ide> ActiveSupport::Deprecation.warn("use_full_path option has been deprecated and has no affect.", caller)
<ide> end
<ide>
<add> logger.info("Rendering #{options[:file]}") if logger
<ide> pick_template(options[:file]).render_template(self, options[:locals])
<ide> elsif options[:partial]
<ide> render_partial(options)
<ide> def set_controller_content_type(content_type)
<ide>
<ide> def render_with_layout(options, local_assigns, &block)
<ide> partial_layout = options.delete(:layout)
<add> logger.info("Rendering template within #{partial_layout}") if logger
<add>
<ide> if block_given?
<ide> begin
<ide> @_proc_for_layout = block | 2 |
Text | Text | fix eslint-plugin readme.md | 4a97791341c6c8fb58ee38f399d8ec8952aa2ba6 | <ide><path>packages/eslint-plugin-react-native-community/README.md
<ide> # eslint-plugin-react-native-community
<ide>
<del>This plugin is intended to be used in `@react-native-community/eslint-plugin`. You probably want to install that package instead.
<add>This plugin is intended to be used in [`@react-native-community/eslint-config`](https://github.com/facebook/react-native/tree/master/packages/eslint-config-react-native-community). You probably want to install that package instead.
<ide>
<ide> ## Installation
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 3baf47598da6cfdefda6625c713e79f0ff2c29a5 | <ide><path>src/Illuminate/Database/Eloquent/Relations/HasOne.php
<ide> public function match(array $models, Collection $results, $relation)
<ide> */
<ide> public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
<ide> {
<del> if($this->isOneOfMany()) {
<add> if ($this->isOneOfMany()) {
<ide> $this->mergeJoinsTo($query);
<ide> }
<del>
<add>
<ide> return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphOne.php
<ide> public function match(array $models, Collection $results, $relation)
<ide> */
<ide> public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
<ide> {
<del> if($this->isOneOfMany()) {
<add> if ($this->isOneOfMany()) {
<ide> $this->mergeJoinsTo($query);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentMorphOneOfManyTest.php
<ide> public function testWithExistsWithConstraintsInJoinSubSelect()
<ide>
<ide> $product->states()->create([
<ide> 'state' => 'draft',
<del> 'type' => 'foo'
<add> 'type' => 'foo',
<ide> ]);
<ide> $product = MorphOneOfManyTestProduct::withExists('current_foo_state')->first();
<ide> $this->assertTrue($product->current_foo_state_exists);
<ide> public function current_foo_state()
<ide> {
<ide> return $this->morphOne(MorphOneOfManyTestState::class, 'stateful')->ofMany(
<ide> ['id' => 'max'],
<del> function($q) {
<add> function ($q) {
<ide> $q->where('type', 'foo');
<ide> }
<ide> ); | 3 |
Go | Go | remove canaccess(), and move to daemon | 69f72417f444c2e0589767019e697a161bb912a9 | <ide><path>daemon/daemon_unix.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide> "sync"
<add> "syscall"
<ide> "time"
<ide>
<ide> "github.com/containerd/cgroups"
<ide> func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools
<ide> if dirPath == "/" {
<ide> break
<ide> }
<del> if !idtools.CanAccess(dirPath, remappedRoot) {
<add> if !canAccess(dirPath, remappedRoot) {
<ide> return fmt.Errorf("a subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories", config.Root)
<ide> }
<ide> }
<ide> func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools
<ide> return nil
<ide> }
<ide>
<add>// canAccess takes a valid (existing) directory and a uid, gid pair and determines
<add>// if that uid, gid pair has access (execute bit) to the directory.
<add>//
<add>// Note: this is a very rudimentary check, and may not produce accurate results,
<add>// so should not be used for anything other than the current use, see:
<add>// https://github.com/moby/moby/issues/43724
<add>func canAccess(path string, pair idtools.Identity) bool {
<add> statInfo, err := os.Stat(path)
<add> if err != nil {
<add> return false
<add> }
<add> perms := statInfo.Mode().Perm()
<add> if perms&0o001 == 0o001 {
<add> // world access
<add> return true
<add> }
<add> ssi := statInfo.Sys().(*syscall.Stat_t)
<add> if ssi.Uid == uint32(pair.UID) && (perms&0o100 == 0o100) {
<add> // owner access.
<add> return true
<add> }
<add> if ssi.Gid == uint32(pair.GID) && (perms&0o010 == 0o010) {
<add> // group access.
<add> return true
<add> }
<add> return false
<add>}
<add>
<ide> func setupDaemonRootPropagation(cfg *config.Config) error {
<ide> rootParentMount, mountOptions, err := getSourceMount(cfg.Root)
<ide> if err != nil {
<ide><path>pkg/idtools/idtools_unix.go
<ide> func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting
<ide> return nil
<ide> }
<ide>
<del>// CanAccess takes a valid (existing) directory and a uid, gid pair and determines
<del>// if that uid, gid pair has access (execute bit) to the directory
<del>func CanAccess(path string, pair Identity) bool {
<del> statInfo, err := os.Stat(path)
<del> if err != nil {
<del> return false
<del> }
<del> perms := statInfo.Mode().Perm()
<del> if perms&0o001 == 0o001 {
<del> // world access
<del> return true
<del> }
<del> ssi := statInfo.Sys().(*syscall.Stat_t)
<del> if ssi.Uid == uint32(pair.UID) && (perms&0o100 == 0o100) {
<del> // owner access.
<del> return true
<del> }
<del> if ssi.Gid == uint32(pair.GID) && (perms&0o010 == 0o010) {
<del> // group access.
<del> return true
<del> }
<del> return false
<del>}
<del>
<ide> // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
<ide> // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
<ide> func LookupUser(name string) (user.User, error) {
<ide><path>pkg/idtools/idtools_unix_test.go
<ide> package idtools // import "github.com/docker/docker/pkg/idtools"
<ide> import (
<ide> "fmt"
<ide> "os"
<add> "os/exec"
<ide> "os/user"
<ide> "path/filepath"
<add> "syscall"
<ide> "testing"
<ide>
<ide> "golang.org/x/sys/unix"
<ide> func TestNewIDMappings(t *testing.T) {
<ide>
<ide> err = MkdirAllAndChown(dirName, 0o700, Identity{UID: rootUID, GID: rootGID})
<ide> assert.Check(t, err, "Couldn't change ownership of file path. Got error")
<del> assert.Check(t, CanAccess(dirName, idMapping.RootPair()), "Unable to access %s directory with user UID:%d and GID:%d", dirName, rootUID, rootGID)
<add> cmd := exec.Command("ls", "-la", dirName)
<add> cmd.SysProcAttr = &syscall.SysProcAttr{
<add> Credential: &syscall.Credential{Uid: uint32(rootUID), Gid: uint32(rootGID)},
<add> }
<add> out, err := cmd.CombinedOutput()
<add> assert.Check(t, err, "Unable to access %s directory with user UID:%d and GID:%d:\n%s", dirName, rootUID, rootGID, string(out))
<ide> }
<ide>
<ide> func TestLookupUserAndGroup(t *testing.T) { | 3 |
Go | Go | remove dead code looking for non-existent err msg | d351aef8afc5a215668248652aad52856949eaa0 | <ide><path>api/client/inspect.go
<ide> func (cli *DockerCli) CmdInspect(args ...string) error {
<ide> for _, name := range cmd.Args() {
<ide> obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, nil))
<ide> if err != nil {
<del> if strings.Contains(err.Error(), "Too many") {
<del> fmt.Fprintf(cli.err, "Error: %v", err)
<del> status = 1
<del> continue
<del> }
<del>
<ide> obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, nil))
<ide> if err != nil {
<ide> if strings.Contains(err.Error(), "No such") { | 1 |
Javascript | Javascript | add hidestack testcase | a5bf0a2fbcbbf5434ff672309819a5385569fda6 | <ide><path>test/cases/compile/error-hide-stack/errors.js
<add>module.exports = [
<add> [/Module build failed: Message\nStack/]
<add>];
<ide>\ No newline at end of file
<ide><path>test/cases/compile/error-hide-stack/index.js
<add>it("should hide stack in details", function() {
<add> (function f() {
<add> require("./loader!");
<add> }).should.throw();
<add>});
<ide><path>test/cases/compile/error-hide-stack/loader.js
<add>module.exports = function() {
<add> var err = new Error("Message");
<add> err.stack = "Stack";
<add> err.hideStack = true;
<add> throw err;
<add>};
<ide>\ No newline at end of file | 3 |
Javascript | Javascript | add test for mounting into a document fragment | 5f93ee6f6ce068228b01516c021c9054b627bf11 | <ide><path>src/renderers/dom/fiber/__tests__/ReactDOMFiber-test.js
<ide> describe('ReactDOMFiber', () => {
<ide> expect(actualDocument).toBe(iframeDocument);
<ide> expect(iframeContainer.appendChild).toHaveBeenCalledTimes(1);
<ide> });
<add>
<add> it('should mount into a document fragment', () => {
<add> var fragment = document.createDocumentFragment();
<add> ReactDOM.render(<div>foo</div>, fragment);
<add> expect(container.innerHTML).toBe('');
<add> container.appendChild(fragment);
<add> expect(container.innerHTML).toBe('<div>foo</div>');
<add> });
<ide> }); | 1 |
PHP | PHP | add new `conjoin()` method to collection | 5b6ba5acb3961b809148fca234f0285d4cb22891 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function collapse()
<ide> return new static(Arr::collapse($this->items));
<ide> }
<ide>
<add> /**
<add> * Conjoin all values of a collection with those of another, regardless of keys.
<add> *
<add> * @param \Traversable $source
<add> * @return self
<add> */
<add> public function conJoin($source)
<add> {
<add> foreach ($source as $item) {
<add> $this->push($item);
<add> }
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Determine if an item exists in the collection.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testCombineWithCollection()
<ide> $this->assertSame($expected, $actual);
<ide> }
<ide>
<add> public function testConJoinWithArray()
<add> {
<add> $expected = [
<add> 0 => 4,
<add> 1 => 5,
<add> 2 => 6,
<add> 3 => 'a',
<add> 4 => 'b',
<add> 5 => 'c',
<add> ];
<add>
<add> $collection = new Collection([4, 5, 6]);
<add> $actual = $collection->conJoin(['a', 'b', 'c'])->toArray();
<add>
<add> $this->assertSame($expected, $actual);
<add> }
<add>
<add> public function testConJoinWithCollection()
<add> {
<add> $expected = [
<add> 0 => 4,
<add> 1 => 5,
<add> 2 => 6,
<add> 3 => 'a',
<add> 4 => 'b',
<add> 5 => 'c',
<add> ];
<add>
<add> $firstCollection = new Collection([4, 5, 6]);
<add> $secondCollection = new Collection(['a', 'b', 'c']);
<add> $actual = $firstCollection->conJoin($secondCollection)->toArray();
<add>
<add> $this->assertSame($expected, $actual);
<add> }
<add>
<ide> public function testReduce()
<ide> {
<ide> $data = new Collection([1, 2, 3]); | 2 |
Mixed | Text | update nel docs after latest refactor | 40276fd3be231be6969f8c51889c13e77a726fa8 | <ide><path>spacy/ml/models/entity_linker.py
<add>from pathlib import Path
<ide> from typing import Optional, Callable, Iterable
<ide> from thinc.api import chain, clone, list2ragged, reduce_mean, residual
<ide> from thinc.api import Model, Maxout, Linear
<ide> def build_nel_encoder(tok2vec: Model, nO: Optional[int] = None) -> Model:
<ide>
<ide>
<ide> @registry.misc.register("spacy.KBFromFile.v1")
<del>def load_kb(kb_path: str) -> Callable[[Vocab], KnowledgeBase]:
<add>def load_kb(kb_path: Path) -> Callable[[Vocab], KnowledgeBase]:
<ide> def kb_from_file(vocab):
<ide> kb = KnowledgeBase(vocab, entity_vector_length=1)
<ide> kb.from_disk(kb_path)
<ide><path>website/docs/api/architectures.md
<ide> into the "real world". This requires 3 main components:
<ide> > window_size = 1
<ide> > maxout_pieces = 3
<ide> > subword_features = true
<del>>
<del>> [kb_loader]
<del>> @misc = "spacy.EmptyKB.v1"
<del>> entity_vector_length = 64
<del>>
<del>> [get_candidates]
<del>> @misc = "spacy.CandidateGenerator.v1"
<ide> > ```
<ide>
<ide> The `EntityLinker` model architecture is a Thinc `Model` with a
<ide> The `EntityLinker` model architecture is a Thinc `Model` with a
<ide>
<ide> ### spacy.EmptyKB.v1 {#EmptyKB}
<ide>
<del>A function that creates a default, empty `KnowledgeBase` from a
<del>[`Vocab`](/api/vocab) instance.
<add>A function that creates an empty `KnowledgeBase` from a [`Vocab`](/api/vocab)
<add>instance. This is the default when a new entity linker component is created.
<ide>
<ide> | Name | Description |
<ide> | ---------------------- | ----------------------------------------------------------------------------------- |
<ide> | `entity_vector_length` | The length of the vectors encoding each entity in the KB. Defaults to `64`. ~~int~~ |
<ide>
<add>### spacy.KBFromFile.v1 {#KBFromFile}
<add>
<add>A function that reads an existing `KnowledgeBase` from file.
<add>
<add>| Name | Description |
<add>| --------- | -------------------------------------------------------- |
<add>| `kb_path` | The location of the KB that was stored to file. ~~Path~~ |
<add>
<ide> ### spacy.CandidateGenerator.v1 {#CandidateGenerator}
<ide>
<ide> A function that takes as input a [`KnowledgeBase`](/api/kb) and a
<ide><path>website/docs/api/entitylinker.md
<ide> architectures and their arguments and hyperparameters.
<ide> > "incl_prior": True,
<ide> > "incl_context": True,
<ide> > "model": DEFAULT_NEL_MODEL,
<del>> "kb_loader": {'@misc': 'spacy.EmptyKB.v1', 'entity_vector_length': 64},
<add>> "entity_vector_length": 64,
<ide> > "get_candidates": {'@misc': 'spacy.CandidateGenerator.v1'},
<ide> > }
<ide> > nlp.add_pipe("entity_linker", config=config)
<ide> > ```
<ide>
<del>| Setting | Description |
<del>| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<del>| `labels_discard` | NER labels that will automatically get a "NIL" prediction. Defaults to `[]`. ~~Iterable[str]~~ |
<del>| `incl_prior` | Whether or not to include prior probabilities from the KB in the model. Defaults to `True`. ~~bool~~ |
<del>| `incl_context` | Whether or not to include the local context in the model. Defaults to `True`. ~~bool~~ |
<del>| `model` | The [`Model`](https://thinc.ai/docs/api-model) powering the pipeline component. Defaults to [EntityLinker](/api/architectures#EntityLinker). ~~Model~~ |
<del>| `kb_loader` | Function that creates a [`KnowledgeBase`](/api/kb) from a `Vocab` instance. Defaults to [EmptyKB](/api/architectures#EmptyKB), a function returning an empty `KnowledgeBase` with an `entity_vector_length` of `64`. ~~Callable[[Vocab], KnowledgeBase]~~ |
<del>| `get_candidates` | Function that generates plausible candidates for a given `Span` object. Defaults to [CandidateGenerator](/api/architectures#CandidateGenerator), a function looking up exact, case-dependent aliases in the KB. ~~Callable[[KnowledgeBase, Span], Iterable[Candidate]]~~ |
<add>| Setting | Description |
<add>| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<add>| `labels_discard` | NER labels that will automatically get a "NIL" prediction. Defaults to `[]`. ~~Iterable[str]~~ |
<add>| `incl_prior` | Whether or not to include prior probabilities from the KB in the model. Defaults to `True`. ~~bool~~ |
<add>| `incl_context` | Whether or not to include the local context in the model. Defaults to `True`. ~~bool~~ |
<add>| `model` | The [`Model`](https://thinc.ai/docs/api-model) powering the pipeline component. Defaults to [EntityLinker](/api/architectures#EntityLinker). ~~Model~~ |
<add>| `entity_vector_length` | Size of encoding vectors in the KB. Defaults to 64. ~~int~~ |
<add>| `get_candidates` | Function that generates plausible candidates for a given `Span` object. Defaults to [CandidateGenerator](/api/architectures#CandidateGenerator), a function looking up exact, case-dependent aliases in the KB. ~~Callable[[KnowledgeBase, Span], Iterable[Candidate]]~~ |
<ide>
<ide> ```python
<ide> %%GITHUB_SPACY/spacy/pipeline/entity_linker.py
<ide> architectures and their arguments and hyperparameters.
<ide> > config = {"model": {"@architectures": "my_el.v1"}}
<ide> > entity_linker = nlp.add_pipe("entity_linker", config=config)
<ide> >
<del>> # Construction via add_pipe with custom KB and candidate generation
<del>> config = {"kb": {"@misc": "my_kb.v1"}}
<del>> entity_linker = nlp.add_pipe("entity_linker", config=config)
<del>>
<ide> > # Construction from class
<ide> > from spacy.pipeline import EntityLinker
<ide> > entity_linker = EntityLinker(nlp.vocab, model)
<ide> > ```
<ide>
<ide> Create a new pipeline instance. In your application, you would normally use a
<ide> shortcut for this and instantiate the component using its string name and
<del>[`nlp.add_pipe`](/api/language#add_pipe). Note that both the internal
<del>`KnowledgeBase` as well as the Candidate generator can be customized by
<del>providing custom registered functions.
<del>
<del>| Name | Description |
<del>| ---------------- | -------------------------------------------------------------------------------------------------------------------------------- |
<del>| `vocab` | The shared vocabulary. ~~Vocab~~ |
<del>| `model` | The [`Model`](https://thinc.ai/docs/api-model) powering the pipeline component. ~~Model~~ |
<del>| `name` | String name of the component instance. Used to add entries to the `losses` during training. ~~str~~ |
<del>| _keyword-only_ | |
<del>| `kb_loader` | Function that creates a [`KnowledgeBase`](/api/kb) from a `Vocab` instance. ~~Callable[[Vocab], KnowledgeBase]~~ |
<del>| `get_candidates` | Function that generates plausible candidates for a given `Span` object. ~~Callable[[KnowledgeBase, Span], Iterable[Candidate]]~~ |
<del>| `labels_discard` | NER labels that will automatically get a `"NIL"` prediction. ~~Iterable[str]~~ |
<del>| `incl_prior` | Whether or not to include prior probabilities from the KB in the model. ~~bool~~ |
<del>| `incl_context` | Whether or not to include the local context in the model. ~~bool~~ |
<add>[`nlp.add_pipe`](/api/language#add_pipe).
<add>
<add>Upon construction of the entity linker component, an empty knowledge base is
<add>constructed with the provided `entity_vector_length`. If you want to use a
<add>custom knowledge base, you should either call
<add>[`set_kb`](/api/entitylinker#set_kb) or provide a `kb_loader` in the
<add>[`initialize`](/api/entitylinker#initialize) call.
<add>
<add>| Name | Description |
<add>| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
<add>| `vocab` | The shared vocabulary. ~~Vocab~~ |
<add>| `model` | The [`Model`](https://thinc.ai/docs/api-model) powering the pipeline component. ~~Model~~ |
<add>| `name` | String name of the component instance. Used to add entries to the `losses` during training. ~~str~~ |
<add>| _keyword-only_ | |
<add>| `entity_vector_length` | Size of encoding vectors in the KB. ~~int~~ |
<add>| `get_candidates` | Function that generates plausible candidates for a given `Span` object. ~~Callable[[KnowledgeBase, Span], Iterable[Candidate]]~~ |
<add>| `labels_discard` | NER labels that will automatically get a `"NIL"` prediction. ~~Iterable[str]~~ |
<add>| `incl_prior` | Whether or not to include prior probabilities from the KB in the model. ~~bool~~ |
<add>| `incl_context` | Whether or not to include the local context in the model. ~~bool~~ |
<ide>
<ide> ## EntityLinker.\_\_call\_\_ {#call tag="method"}
<ide>
<ide> applied to the `Doc` in order. Both [`__call__`](/api/entitylinker#call) and
<ide> | `batch_size` | The number of documents to buffer. Defaults to `128`. ~~int~~ |
<ide> | **YIELDS** | The processed documents in order. ~~Doc~~ |
<ide>
<add>## EntityLinker.set_kb {#initialize tag="method" new="3"}
<add>
<add>The `kb_loader` should be a function that takes a `Vocab` instance and creates
<add>the `KnowledgeBase`, ensuring that the strings of the knowledge base are synced
<add>with the current vocab.
<add>
<add>> #### Example
<add>>
<add>> ```python
<add>> def create_kb(vocab):
<add>> kb = KnowledgeBase(vocab, entity_vector_length=128)
<add>> kb.add_entity(...)
<add>> kb.add_alias(...)
<add>> return kb
<add>> entity_linker = nlp.add_pipe("entity_linker")
<add>> entity_linker.set_kb(lambda: [], nlp=nlp, kb_loader=create_kb)
<add>> ```
<add>
<add>| Name | Description |
<add>| ----------- | ---------------------------------------------------------------------------------------------------------------- |
<add>| `kb_loader` | Function that creates a [`KnowledgeBase`](/api/kb) from a `Vocab` instance. ~~Callable[[Vocab], KnowledgeBase]~~ |
<add>
<ide> ## EntityLinker.initialize {#initialize tag="method" new="3"}
<ide>
<ide> Initialize the component for training. `get_examples` should be a function that
<ide> network,
<ide> setting up the label scheme based on the data. This method is typically called
<ide> by [`Language.initialize`](/api/language#initialize).
<ide>
<add>Optionally, a `kb_loader` argument may be specified to change the internal
<add>knowledge base. This argument should be a function that takes a `Vocab` instance
<add>and creates the `KnowledgeBase`, ensuring that the strings of the knowledge base
<add>are synced with the current vocab.
<add>
<ide> <Infobox variant="warning" title="Changed in v3.0" id="begin_training">
<ide>
<ide> This method was previously called `begin_training`.
<ide> This method was previously called `begin_training`.
<ide> >
<ide> > ```python
<ide> > entity_linker = nlp.add_pipe("entity_linker")
<del>> entity_linker.initialize(lambda: [], nlp=nlp)
<add>> entity_linker.initialize(lambda: [], nlp=nlp, kb_loader=my_kb)
<ide> > ```
<ide>
<ide> | Name | Description |
<ide> | -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
<ide> | `get_examples` | Function that returns gold-standard annotations in the form of [`Example`](/api/example) objects. ~~Callable[[], Iterable[Example]]~~ |
<ide> | _keyword-only_ | |
<ide> | `nlp` | The current `nlp` object. Defaults to `None`. ~~Optional[Language]~~ |
<add>| `kb_loader` | Function that creates a [`KnowledgeBase`](/api/kb) from a `Vocab` instance. ~~Callable[[Vocab], KnowledgeBase]~~ |
<ide>
<ide> ## EntityLinker.predict {#predict tag="method"}
<ide> | 3 |
PHP | PHP | fix cs error | 929c38c5ff9e705fd5b85ca1ad5cd9986c4d4308 | <ide><path>src/Datasource/EntityTrait.php
<ide> public function set($field, $value = null, array $options = [])
<ide> $options += ['setter' => true, 'guard' => $guard];
<ide>
<ide> foreach ($field as $name => $value) {
<del> $name = (string) $name;
<add> $name = (string)$name;
<ide> if ($options['guard'] === true && !$this->isAccessible($name)) {
<ide> continue;
<ide> }
<ide><path>src/ORM/Marshaller.php
<ide> protected function _buildPropertyMap(array $data, array $options): array
<ide>
<ide> // Is a concrete column?
<ide> foreach (array_keys($data) as $prop) {
<del> $prop = (string) $prop;
<add> $prop = (string)$prop;
<ide> $columnType = $schema->getColumnType($prop);
<ide> if ($columnType) {
<ide> $map[$prop] = function ($value, $entity) use ($columnType) { | 2 |
Python | Python | add parametrize for interpolation methods | 2faf8edd635c8c700a3f5215cc747e268541b6bc | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_linear_nan_1D(self, dtype):
<ide> np.testing.assert_equal(res, np.NAN)
<ide> np.testing.assert_equal(res.dtype, arr.dtype)
<ide>
<del> TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["AllFloat"] + "O"
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_inverted_cdf(self, dtype):
<del> # METHOD 1 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="inverted_cdf")
<del> np.testing.assert_almost_equal(res, 20, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_averaged_inverted_cdf(self, dtype):
<del> # METHOD 2 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="averaged_inverted_cdf")
<del> np.testing.assert_almost_equal(res, 27.5, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_closest_observation(self, dtype):
<del> # METHOD 3 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="closest_observation")
<del> np.testing.assert_almost_equal(res, 20, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_interpolated_inverted_cdf(self, dtype):
<del> # METHOD 4 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="interpolated_inverted_cdf")
<del> np.testing.assert_almost_equal(res, 20, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_hazen(self, dtype):
<del> # METHOD 5 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="hazen")
<del> np.testing.assert_almost_equal(res, 27.5, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_weibull(self, dtype):
<del> # METHOD 6 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="weibull")
<del> np.testing.assert_almost_equal(res, 26, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_linear(self, dtype):
<del> # METHOD 7 of H&F
<del> # Test defaults
<del> assert_equal(np.percentile(range(10), 50), 4.5)
<del> # explicit interpolation_method (the default)
<del> res = np.percentile([15.0, 20.0, 35.0, 40.0, 50.0],
<del> 40,
<del> interpolation="linear")
<del> np.testing.assert_almost_equal(res, 29, 15)
<del>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_median_unbiased(self, dtype):
<del> # METHOD 8 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="median_unbiased")
<del> np.testing.assert_almost_equal(res, 27, 14)
<add> H_F_TYPE_CODES = [(int_type, np.float64)
<add> for int_type in np.typecodes["AllInteger"]
<add> ] + [(np.float16, np.float64),
<add> (np.float32, np.float64),
<add> (np.float64, np.float64),
<add> (np.float128, np.float128),
<add> (np.complex64, np.complex128),
<add> (np.complex128, np.complex128),
<add> (np.complex256, np.complex256),
<add> (np.dtype("O"), np.float64)]
<add>
<add> @pytest.mark.parametrize(["input_dtype", "expected_dtype"], H_F_TYPE_CODES)
<add> @pytest.mark.parametrize(["interpolation", "expected"],
<add> [("inverted_cdf", 20),
<add> ("averaged_inverted_cdf", 27.5),
<add> ("closest_observation", 20),
<add> ("interpolated_inverted_cdf", 20),
<add> ("hazen", 27.5),
<add> ("weibull", 26),
<add> ("linear", 29),
<add> ("median_unbiased", 27),
<add> ("normal_unbiased", 27.125),
<add> ])
<add> def test_linear_interpolation(self,
<add> interpolation,
<add> expected,
<add> input_dtype,
<add> expected_dtype):
<add> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype)
<add> actual = np.percentile(arr, 40.0, interpolation=interpolation)
<add>
<add> np.testing.assert_almost_equal(actual, expected, 14)
<add>
<add> if interpolation in ["inverted_cdf", "closest_observation"]:
<add> if input_dtype == "O":
<add> np.testing.assert_equal(np.asarray(actual).dtype, np.float64)
<add> else:
<add> np.testing.assert_equal(np.asarray(actual).dtype,
<add> np.dtype(input_dtype))
<add> else:
<add> np.testing.assert_equal(np.asarray(actual).dtype,
<add> np.dtype(expected_dtype))
<ide>
<del> @pytest.mark.parametrize("dtype", TYPE_CODES)
<del> def test_linear_normal_unbiased(self, dtype):
<del> # METHOD 9 of H&F
<del> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=dtype)
<del> res = np.percentile(
<del> arr,
<del> 40.0,
<del> interpolation="normal_unbiased")
<del> np.testing.assert_almost_equal(res, 27.125, 15)
<add> TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["AllFloat"] + "O"
<ide>
<ide> @pytest.mark.parametrize("dtype", TYPE_CODES)
<ide> def test_lower_higher(self, dtype): | 1 |
Text | Text | add sudo for related command | f7fe2f0992126d45802a376b6da760d4e2b8607c | <ide><path>docs/userguide/storagedriver/imagesandcontainers.md
<ide> single 8GB general purpose SSD EBS volume. The Docker data directory
<ide> centos latest c8a648134623 4 weeks ago 196.6 MB
<ide> ubuntu 15.04 c8be1ac8145a 7 weeks ago 131.3 MB
<ide>
<del> $ du -hs /var/lib/docker
<add> $ sudo du -hs /var/lib/docker
<ide> 2.0G /var/lib/docker
<ide>
<ide> $ time docker run --rm -v /var/lib/docker:/var/lib/docker docker/v1.10-migrator | 1 |
PHP | PHP | fix a typo | 79d214c720ab9c84e2388fb87d351933008fdc8e | <ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testUploadedFilePsr7($expected, $options)
<ide> }
<ide>
<ide> /**
<del> * Test the compareFields method with eual result.
<add> * Test the compareFields method with equal result.
<ide> *
<ide> * @return void
<ide> */ | 1 |
Ruby | Ruby | make close message detection more precise | da3c9a1e167ec4f1d819bae0296e4567c3425078 | <ide><path>Library/Homebrew/cmd/pull.rb
<ide> def pull
<ide> end
<ide>
<ide> # If this is a pull request, append a close message.
<del> unless message.include? 'Closes #'
<add> unless message.include? "Closes ##{issue}."
<ide> message += "\nCloses ##{issue}."
<ide> safe_system 'git', 'commit', '--amend', '--signoff', '-q', '-m', message
<ide> end | 1 |
Text | Text | update laracasts videos stats in readme | 230bb3a7403bd6a0c3933d75a10af93a34df7007 | <ide><path>README.md
<ide> Laravel is accessible, yet powerful, providing tools needed for large, robust ap
<ide>
<ide> Laravel has the most extensive and thorough documentation and video tutorial library of any modern web application framework. The [Laravel documentation](https://laravel.com/docs) is thorough, complete, and makes it a breeze to get started learning the framework.
<ide>
<del>If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 900 video tutorials covering a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.
<add>If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 1100 video tutorials covering a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.
<ide>
<ide> ## Contributing
<ide> | 1 |
Javascript | Javascript | move linkto docs to helper instead of linkview | 174bc158d79148dea5445db75c7ca785fd2cca6b | <ide><path>packages/ember-routing/lib/helpers/link_to.js
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> return ret.concat(resolvedPaths(linkView.parameters));
<ide> }
<ide>
<add> /**
<add> @class LinkView
<add> @namespace Ember
<add> @extends Ember.View
<add> **/
<add> var LinkView = Ember.LinkView = Ember.View.extend({
<add> tagName: 'a',
<add> namedRoute: null,
<add> currentWhen: null,
<add> title: null,
<add> activeClass: 'active',
<add> replace: false,
<add> attributeBindings: ['href', 'title'],
<add> classNameBindings: 'active',
<add>
<add> // Even though this isn't a virtual view, we want to treat it as if it is
<add> // so that you can access the parent with {{view.prop}}
<add> concreteView: Ember.computed(function() {
<add> return get(this, 'parentView');
<add> }).property('parentView'),
<add>
<add> active: Ember.computed(function() {
<add> var router = this.get('router'),
<add> params = resolvedPaths(this.parameters),
<add> currentWithIndex = this.currentWhen + '.index',
<add> isActive = router.isActive.apply(router, [this.currentWhen].concat(params)) ||
<add> router.isActive.apply(router, [currentWithIndex].concat(params));
<add>
<add> if (isActive) { return get(this, 'activeClass'); }
<add> }).property('namedRoute', 'router.url'),
<add>
<add> router: Ember.computed(function() {
<add> return this.get('controller').container.lookup('router:main');
<add> }),
<add>
<add> click: function(event) {
<add> if (!isSimpleClick(event)) { return true; }
<add>
<add> event.preventDefault();
<add> if (this.bubbles === false) { event.stopPropagation(); }
<add>
<add> var router = this.get('router');
<add>
<add> if (this.get('replace')) {
<add> router.replaceWith.apply(router, args(this, router));
<add> } else {
<add> router.transitionTo.apply(router, args(this, router));
<add> }
<add> },
<add>
<add> href: Ember.computed(function() {
<add> if (this.get('tagName') !== 'a') { return false; }
<add>
<add> var router = this.get('router');
<add> return router.generate.apply(router, args(this, router));
<add> })
<add> });
<add>
<add> LinkView.toString = function() { return "LinkView"; };
<add>
<ide> /**
<ide> The `{{linkTo}}` helper renders a link to the supplied
<ide> `routeName` passing an optionally supplied model to the
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> </a>
<ide> ```
<ide>
<del> ## Supplying a tagName
<del> By default `{{linkTo}} renders an `<a>` element. This can
<add> ### Supplying a tagName
<add> By default `{{linkTo}}` renders an `<a>` element. This can
<ide> be overridden for a single use of `{{linkTo}}` by supplying
<ide> a `tagName` option:
<ide>
<del> ```
<add> ```handlebars
<ide> {{#linkTo photoGallery tagName="li"}}
<ide> Great Hamster Photos
<ide> {{/linkTo}}
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> To override this option for your entire application, see
<ide> "Overriding Application-wide Defaults".
<ide>
<del> ## Handling `href`
<add> ### Handling `href`
<ide> `{{linkTo}}` will use your application's Router to
<ide> fill the element's `href` property with a url that
<ide> matches the path to the supplied `routeName` for your
<ide> routers's configured `Location` scheme, which defaults
<ide> to Ember.HashLocation.
<ide>
<del> ## Handling current route
<add> ### Handling current route
<ide> `{{linkTo}}` will apply a CSS class name of 'active'
<ide> when the application's current route matches
<ide> the supplied routeName. For example, if the application's
<ide> current route is 'photoGallery.recent' the following
<ide> use of `{{linkTo}}`:
<ide>
<del> ```
<add> ```handlebars
<ide> {{#linkTo photoGallery.recent}}
<ide> Great Hamster Photos from the last week
<ide> {{/linkTo}}
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> for a single use of `{{linkTo}}` by passing an `activeClass`
<ide> option:
<ide>
<del> ```
<add> ```handlebars
<ide> {{#linkTo photoGallery.recent activeClass="current-url"}}
<ide> Great Hamster Photos from the last week
<ide> {{/linkTo}}
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> To override this option for your entire application, see
<ide> "Overriding Application-wide Defaults".
<ide>
<del> ## Supplying a model
<add> ### Supplying a model
<ide> An optional model argument can be used for routes whose
<ide> paths contain dynamic segments. This argument will become
<ide> the model context of the linked route:
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> </a>
<ide> ```
<ide>
<del> ## Supplying multiple models
<add> ### Supplying multiple models
<ide> For deep-linking to route paths that contain multiple
<ide> dynamic segments, multiple model arguments can be used.
<ide> As the router transitions through the route path, each
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> </a>
<ide> ```
<ide>
<del> ## Overriding Application-wide Defaults
<add> ### Overriding Application-wide Defaults
<ide> ``{{linkTo}}`` creates an instance of Ember.LinkView
<ide> for rendering. To override options for your entire
<ide> application, reopen Ember.LinkView and supply the
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> tagName: 'li'
<ide> })
<ide> ```
<del>
<del> @class LinkView
<del> @namespace Ember
<del> @extends Ember.View
<del> **/
<del> var LinkView = Ember.LinkView = Ember.View.extend({
<del> tagName: 'a',
<del> namedRoute: null,
<del> currentWhen: null,
<del> title: null,
<del> activeClass: 'active',
<del> replace: false,
<del> attributeBindings: ['href', 'title'],
<del> classNameBindings: 'active',
<del>
<del> // Even though this isn't a virtual view, we want to treat it as if it is
<del> // so that you can access the parent with {{view.prop}}
<del> concreteView: Ember.computed(function() {
<del> return get(this, 'parentView');
<del> }).property('parentView'),
<del>
<del> active: Ember.computed(function() {
<del> var router = this.get('router'),
<del> params = resolvedPaths(this.parameters),
<del> currentWithIndex = this.currentWhen + '.index',
<del> isActive = router.isActive.apply(router, [this.currentWhen].concat(params)) ||
<del> router.isActive.apply(router, [currentWithIndex].concat(params));
<del>
<del> if (isActive) { return get(this, 'activeClass'); }
<del> }).property('namedRoute', 'router.url'),
<del>
<del> router: Ember.computed(function() {
<del> return this.get('controller').container.lookup('router:main');
<del> }),
<del>
<del> click: function(event) {
<del> if (!isSimpleClick(event)) { return true; }
<ide>
<del> event.preventDefault();
<del> if (this.bubbles === false) { event.stopPropagation(); }
<del>
<del> var router = this.get('router');
<del>
<del> if (this.get('replace')) {
<del> router.replaceWith.apply(router, args(this, router));
<del> } else {
<del> router.transitionTo.apply(router, args(this, router));
<del> }
<del> },
<del>
<del> href: Ember.computed(function() {
<del> if (this.get('tagName') !== 'a') { return false; }
<del>
<del> var router = this.get('router');
<del> return router.generate.apply(router, args(this, router));
<del> })
<del> });
<del>
<del> LinkView.toString = function() { return "LinkView"; };
<del>
<del> /**
<ide> @method linkTo
<ide> @for Ember.Handlebars.helpers
<ide> @param {String} routeName | 1 |
Javascript | Javascript | use inheritance for iterators in `iterable` | 662e76dfe834dafa1a8c519896438bfcd5e723ab | <ide><path>packages/ember-glimmer/lib/utils/iterable.js
<ide> function identity(item) {
<ide> function ensureUniqueKey(seen, key) {
<ide> let seenCount = seen[key];
<ide>
<del> if (seenCount) {
<add> if (seenCount > 0) {
<ide> seen[key]++;
<ide> return `${key}${ITERATOR_KEY_GUID}${seenCount}`;
<ide> } else {
<ide> class ArrayIterator {
<ide> return false;
<ide> }
<ide>
<add> getMemo(position) {
<add> return position;
<add> }
<add>
<add> getValue(position) {
<add> return this.array[position];
<add> }
<add>
<ide> next() {
<del> let { array, length, keyFor, position, seen } = this;
<add> let { length, keyFor, position, seen } = this;
<ide>
<ide> if (position >= length) { return null; }
<ide>
<del> let value = array[position];
<del> let memo = position;
<add> let value = this.getValue(position);
<add> let memo = this.getMemo(position);
<ide> let key = ensureUniqueKey(seen, keyFor(value, memo));
<ide>
<ide> this.position++;
<ide> class ArrayIterator {
<ide> }
<ide> }
<ide>
<del>class EmberArrayIterator {
<add>class EmberArrayIterator extends ArrayIterator {
<ide> constructor(array, keyFor) {
<del> this.array = array;
<add> super(array, keyFor);
<ide> this.length = get(array, 'length');
<del> this.keyFor = keyFor;
<del> this.position = 0;
<del> this.seen = Object.create(null);
<ide> }
<ide>
<del> isEmpty() {
<del> return this.length === 0;
<del> }
<del>
<del> next() {
<del> let { array, length, keyFor, position, seen } = this;
<del>
<del> if (position >= length) { return null; }
<del>
<del> let value = objectAt(array, position);
<del> let memo = position;
<del> let key = ensureUniqueKey(seen, keyFor(value, memo));
<del>
<del> this.position++;
<del>
<del> return { key, value, memo };
<add> getValue(position) {
<add> return objectAt(this.array, position);
<ide> }
<ide> }
<ide>
<del>class ObjectKeysIterator {
<add>class ObjectKeysIterator extends ArrayIterator {
<ide> constructor(keys, values, keyFor) {
<add> super(values, keyFor);
<ide> this.keys = keys;
<del> this.values = values;
<del> this.keyFor = keyFor;
<del> this.position = 0;
<del> this.seen = Object.create(null);
<add> this.length = keys.length;
<ide> }
<ide>
<del> isEmpty() {
<del> return this.keys.length === 0;
<add> getMemo(position) {
<add> return this.keys[position];
<ide> }
<ide>
<del> next() {
<del> let { keys, values, keyFor, position, seen } = this;
<del>
<del> if (position >= keys.length) { return null; }
<del>
<del> let value = values[position];
<del> let memo = keys[position];
<del> let key = ensureUniqueKey(seen, keyFor(value, memo));
<del>
<del> this.position++;
<del>
<del> return { key, value, memo };
<add> getValue(position) {
<add> return this.array[position];
<ide> }
<ide> }
<ide> | 1 |
Python | Python | fix import order | 4f40714169c2c676fd76be596c3dd543bad06c84 | <ide><path>tests/test_authentication.py
<ide>
<ide> from django.conf.urls import include, url
<ide> from django.contrib.auth.models import User
<add>from django.db import models
<ide> from django.http import HttpResponse
<ide> from django.test import TestCase
<ide> from django.utils import six
<del>from django.db import models
<ide>
<ide> from rest_framework import (
<ide> HTTP_HEADER_ENCODING, exceptions, permissions, renderers, status | 1 |
PHP | PHP | fix validation tests one more time | de53feb07e431077d5b78548fddc9919ef5ab09c | <ide><path>laravel/tests/cases/validator.test.php
<ide> public function testTheDateFormatRule()
<ide> $rules = array('date' => 'date_format:j-M-Y');
<ide> $this->assertTrue(Validator::make($input, $rules)->valid());
<ide>
<del> $input['date'] = '2009-02-15 15:16:17';
<del> $rules['date'] = 'date_format:Y-m-d H\\:i\\:s';
<del> $this->assertTrue(Validator::make($input, $rules)->valid());
<del>
<del> $rules['date'] = 'date_format:"Y-m-d H:i:s"';
<add> $input['date'] = '2009-02-15,15:16:17';
<add> $rules['date'] = 'date_format:"Y-m-d,H:i:s"';
<ide> $this->assertTrue(Validator::make($input, $rules)->valid());
<ide>
<ide> $input['date'] = '2009-02-15'; | 1 |
PHP | PHP | param_str | 3771406f049e0bb766152b56af1384e0ec6be574 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function bindValues($statement, $bindings)
<ide> foreach ($bindings as $key => $value) {
<ide> $statement->bindValue(
<ide> is_string($key) ? $key : $key + 1, $value,
<del> filter_var($value, FILTER_VALIDATE_FLOAT) !== false ? PDO::PARAM_INT : PDO::PARAM_STR
<add> ! is_string($value) && is_numeric($value) ? PDO::PARAM_INT : PDO::PARAM_STR
<ide> );
<ide> }
<ide> } | 1 |
Python | Python | add mongo projections to hook and transfer | 987575787d82abf5b4e68b669fdb3bcab08965e6 | <ide><path>airflow/providers/amazon/aws/transfers/mongo_to_s3.py
<ide> class MongoToS3Operator(BaseOperator):
<ide> :type mongo_collection: str
<ide> :param mongo_query: query to execute. A list including a dict of the query
<ide> :type mongo_query: Union[list, dict]
<add> :param mongo_projection: optional parameter to filter the returned fields by
<add> the query. It can be a list of fields names to include or a dictionary
<add> for excluding fields (e.g `projection={"_id": 0}`
<add> :type mongo_projection: Union[list, dict]
<ide> :param s3_bucket: reference to a specific S3 bucket to store the data
<ide> :type s3_bucket: str
<ide> :param s3_key: in which S3 key the file will be stored
<ide> def __init__(
<ide> s3_bucket: str,
<ide> s3_key: str,
<ide> mongo_db: Optional[str] = None,
<add> mongo_projection: Optional[Union[list, dict]] = None,
<ide> replace: bool = False,
<ide> allow_disk_use: bool = False,
<ide> compression: Optional[str] = None,
<ide> def __init__(
<ide> # Grab query and determine if we need to run an aggregate pipeline
<ide> self.mongo_query = mongo_query
<ide> self.is_pipeline = isinstance(self.mongo_query, list)
<add> self.mongo_projection = mongo_projection
<ide>
<ide> self.s3_bucket = s3_bucket
<ide> self.s3_key = s3_key
<ide> def execute(self, context) -> bool:
<ide> results = MongoHook(self.mongo_conn_id).find(
<ide> mongo_collection=self.mongo_collection,
<ide> query=cast(dict, self.mongo_query),
<add> projection=self.mongo_projection,
<ide> mongo_db=self.mongo_db,
<ide> )
<ide>
<ide><path>airflow/providers/mongo/hooks/mongo.py
<ide> """Hook for Mongo DB"""
<ide> from ssl import CERT_NONE
<ide> from types import TracebackType
<del>from typing import List, Optional, Type
<add>from typing import List, Optional, Type, Union
<ide>
<ide> import pymongo
<ide> from pymongo import MongoClient, ReplaceOne
<ide> def aggregate(
<ide> ) -> pymongo.command_cursor.CommandCursor:
<ide> """
<ide> Runs an aggregation pipeline and returns the results
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.aggregate
<del> https://api.mongodb.com/python/current/examples/aggregation.html
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.aggregate
<add> https://pymongo.readthedocs.io/en/stable/examples/aggregation.html
<ide> """
<ide> collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
<ide>
<ide> def find(
<ide> query: dict,
<ide> find_one: bool = False,
<ide> mongo_db: Optional[str] = None,
<add> projection: Optional[Union[list, dict]] = None,
<ide> **kwargs,
<ide> ) -> pymongo.cursor.Cursor:
<ide> """
<ide> Runs a mongo find query and returns the results
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find
<ide> """
<ide> collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
<ide>
<ide> if find_one:
<del> return collection.find_one(query, **kwargs)
<add> return collection.find_one(query, projection, **kwargs)
<ide> else:
<del> return collection.find(query, **kwargs)
<add> return collection.find(query, projection, **kwargs)
<ide>
<ide> def insert_one(
<ide> self, mongo_collection: str, doc: dict, mongo_db: Optional[str] = None, **kwargs
<ide> ) -> pymongo.results.InsertOneResult:
<ide> """
<ide> Inserts a single document into a mongo collection
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
<ide> """
<ide> collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
<ide>
<ide> def insert_many(
<ide> ) -> pymongo.results.InsertManyResult:
<ide> """
<ide> Inserts many docs into a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.insert_many
<ide> """
<ide> collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
<ide>
<ide> def update_one(
<ide> ) -> pymongo.results.UpdateResult:
<ide> """
<ide> Updates a single document in a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.update_one
<ide>
<ide> :param mongo_collection: The name of the collection to update.
<ide> :type mongo_collection: str
<ide> def update_many(
<ide> ) -> pymongo.results.UpdateResult:
<ide> """
<ide> Updates one or more documents in a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.update_many
<ide>
<ide> :param mongo_collection: The name of the collection to update.
<ide> :type mongo_collection: str
<ide> def replace_one(
<ide> ) -> pymongo.results.UpdateResult:
<ide> """
<ide> Replaces a single document in a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
<ide>
<ide> .. note::
<ide> If no ``filter_doc`` is given, it is assumed that the replacement
<ide> def replace_many(
<ide> Replaces many documents in a mongo collection.
<ide>
<ide> Uses bulk_write with multiple ReplaceOne operations
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
<ide>
<ide> .. note::
<ide> If no ``filter_docs``are given, it is assumed that all
<ide> def delete_one(
<ide> ) -> pymongo.results.DeleteResult:
<ide> """
<ide> Deletes a single document in a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.delete_one
<ide>
<ide> :param mongo_collection: The name of the collection to delete from.
<ide> :type mongo_collection: str
<ide> def delete_many(
<ide> ) -> pymongo.results.DeleteResult:
<ide> """
<ide> Deletes one or more documents in a mongo collection.
<del> https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
<add> https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
<ide>
<ide> :param mongo_collection: The name of the collection to delete from.
<ide> :type mongo_collection: str
<ide><path>tests/providers/amazon/aws/transfers/test_mongo_to_s3.py
<ide> def test_execute(self, mock_s3_hook, mock_mongo_hook):
<ide> operator.execute(None)
<ide>
<ide> mock_mongo_hook.return_value.find.assert_called_once_with(
<del> mongo_collection=MONGO_COLLECTION, query=MONGO_QUERY, mongo_db=None
<add> mongo_collection=MONGO_COLLECTION, query=MONGO_QUERY, mongo_db=None, projection=None
<ide> )
<ide>
<ide> op_stringify = self.mock_operator._stringify
<ide> def test_execute_compress(self, mock_s3_hook, mock_mongo_hook):
<ide> operator.execute(None)
<ide>
<ide> mock_mongo_hook.return_value.find.assert_called_once_with(
<del> mongo_collection=MONGO_COLLECTION, query=MONGO_QUERY, mongo_db=None
<add> mongo_collection=MONGO_COLLECTION, query=MONGO_QUERY, mongo_db=None, projection=None
<ide> )
<ide>
<ide> op_stringify = self.mock_operator._stringify
<ide><path>tests/providers/mongo/hooks/test_mongo.py
<ide> def test_find_one(self):
<ide> @unittest.skipIf(mongomock is None, 'mongomock package not present')
<ide> def test_find_many(self):
<ide> collection = mongomock.MongoClient().db.collection
<del> objs = [{'test_find_many_1': 'test_value'}, {'test_find_many_2': 'test_value'}]
<add> objs = [{'_id': 1, 'test_find_many_1': 'test_value'}, {'_id': 2, 'test_find_many_2': 'test_value'}]
<ide> collection.insert(objs)
<ide>
<del> result_objs = self.hook.find(collection, {}, find_one=False)
<add> result_objs = self.hook.find(mongo_collection=collection, query={}, projection={}, find_one=False)
<ide>
<ide> assert len(list(result_objs)) > 1
<ide>
<add> @unittest.skipIf(mongomock is None, 'mongomock package not present')
<add> def test_find_many_with_projection(self):
<add> collection = mongomock.MongoClient().db.collection
<add> objs = [
<add> {'_id': '1', 'test_find_many_1': 'test_value', 'field_3': 'a'},
<add> {'_id': '2', 'test_find_many_2': 'test_value', 'field_3': 'b'},
<add> ]
<add> collection.insert(objs)
<add>
<add> projection = {'_id': 0}
<add> result_objs = self.hook.find(
<add> mongo_collection=collection, query={}, projection=projection, find_one=False
<add> )
<add>
<add> self.assertRaises(KeyError, lambda x: x[0]['_id'], result_objs)
<add>
<ide> @unittest.skipIf(mongomock is None, 'mongomock package not present')
<ide> def test_aggregate(self):
<ide> collection = mongomock.MongoClient().db.collection | 4 |
Python | Python | use simpler dict.get() rather than try/except | b7edd463139a02ccad268bc6c9f8a17d02641421 | <ide><path>rest_framework/fields.py
<ide> def to_internal_value(self, data):
<ide> except KeyError:
<ide> self.fail('invalid_choice', input=data)
<ide>
<del> def representation_value(self, value):
<del> try:
<del> return self.choice_strings_to_values[six.text_type(value)]
<del> except KeyError:
<del> return value
<del>
<ide> def to_representation(self, value):
<ide> if value in ('', None):
<ide> return value
<del> return self.representation_value(value)
<add> return self.choice_strings_to_values.get(six.text_type(value), value)
<ide>
<ide>
<ide> class MultipleChoiceField(ChoiceField):
<ide> def to_internal_value(self, data):
<ide>
<ide> def to_representation(self, value):
<ide> return set([
<del> self.representation_value(item) for item in value
<add> self.choice_strings_to_values.get(six.text_type(item), item) for item in value
<ide> ])
<ide>
<ide> | 1 |
Javascript | Javascript | fix the total size of roundedboxbuffergeometry | 3e231ef9008bce4ad1a7629ee674e39a83a2cc1e | <ide><path>examples/jsm/geometries/RoundedBoxBufferGeometry.js
<ide> class RoundedBoxBufferGeometry extends BoxBufferGeometry {
<ide> for ( let i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
<ide>
<ide> position.fromArray( positions, i );
<del> normal.copy( position ).normalize();
<del>
<del> positions[ i + 0 ] = box.x * Math.sign( position.x ) + normal.x * radius;
<del> positions[ i + 1 ] = box.y * Math.sign( position.y ) + normal.y * radius;
<del> positions[ i + 2 ] = box.z * Math.sign( position.z ) + normal.z * radius;
<del>
<ide> normal.copy( position );
<ide> normal.x -= Math.sign( normal.x ) * halfSegmentSize;
<ide> normal.y -= Math.sign( normal.y ) * halfSegmentSize;
<ide> normal.z -= Math.sign( normal.z ) * halfSegmentSize;
<ide> normal.normalize();
<ide>
<add> positions[ i + 0 ] = box.x * Math.sign( position.x ) + normal.x * radius;
<add> positions[ i + 1 ] = box.y * Math.sign( position.y ) + normal.y * radius;
<add> positions[ i + 2 ] = box.z * Math.sign( position.z ) + normal.z * radius;
<add>
<ide> normals[ i + 0 ] = normal.x;
<ide> normals[ i + 1 ] = normal.y;
<ide> normals[ i + 2 ] = normal.z; | 1 |
Go | Go | prevent breakout in applylayer | 31d1d733037b22591e2dd2edfe6c4d2d4b8086cc | <ide><path>pkg/archive/diff.go
<ide> import (
<ide> // ApplyLayer parses a diff in the standard layer format from `layer`, and
<ide> // applies it to the directory `dest`.
<ide> func ApplyLayer(dest string, layer ArchiveReader) error {
<add> dest = filepath.Clean(dest)
<add>
<ide> // We need to be able to set any perms
<ide> oldmask, err := system.Umask(0)
<ide> if err != nil {
<ide> func ApplyLayer(dest string, layer ArchiveReader) error {
<ide>
<ide> path := filepath.Join(dest, hdr.Name)
<ide> base := filepath.Base(path)
<add>
<add> // Prevent symlink breakout
<add> if !strings.HasPrefix(path, dest) {
<add> return breakoutError(fmt.Errorf("%q is outside of %q", path, dest))
<add> }
<add>
<ide> if strings.HasPrefix(base, ".wh.") {
<ide> originalBase := base[len(".wh."):]
<ide> originalPath := filepath.Join(filepath.Dir(path), originalBase) | 1 |
Javascript | Javascript | remove the use of util.isfunction | 7fa03b54c88f930d24f2f0e2ceb0e94dc5a6ad77 | <ide><path>lib/inspector.js
<ide> if (!hasInspector)
<ide>
<ide> const EventEmitter = require('events');
<ide> const { validateString } = require('internal/validators');
<del>const util = require('util');
<ide> const { isMainThread } = require('worker_threads');
<ide>
<ide> const {
<ide> class Session extends EventEmitter {
<ide>
<ide> post(method, params, callback) {
<ide> validateString(method, 'method');
<del> if (!callback && util.isFunction(params)) {
<add> if (!callback && typeof params === 'function') {
<ide> callback = params;
<ide> params = null;
<ide> } | 1 |
PHP | PHP | implement remaining tests for dispatcherfilter | 3c86c3feb2826f078a6423e7596c02db99e6a14b | <ide><path>src/Routing/DispatcherFilter.php
<ide> * event listener with the ability to alter the request or response as needed before it is handled
<ide> * by a controller or after the response body has already been built.
<ide> *
<del> * ### Limiting middleware to specific paths
<add> * ### Limiting filters to specific paths
<ide> *
<ide> * By using the `for` option you can limit with request paths a filter is applied to.
<ide> * Both the before and after event will have the same conditions applied to them. For
<ide> * When the above middleware is connected to a dispatcher it will only fire
<ide> * its `beforeDispatch` and `afterDispatch` methods on requests that start with `/blog`.
<ide> *
<del> * ### Limiting middleware based on conditions
<add> * ### Limiting filters based on conditions
<ide> *
<ide> * In addition to simple path based matching you can use a closure to match on arbitrary request
<ide> * or response conditions. For example:
<ide><path>tests/TestCase/Routing/DispatcherFilterTest.php
<ide> public function testMatchesWithForAndWhen() {
<ide> $this->assertFalse($filter->matches($event));
<ide> }
<ide>
<del>/**
<del> * Test matching with when option.
<del> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage 'when' conditions must be a callable.
<del> * @return void
<del> */
<del> public function testMatchesWithWhenInvalid() {
<del> $this->markTestIncomplete('not done');
<del>
<del> }
<del>
<ide> /**
<ide> * Test event bindings have use condition checker
<ide> *
<ide> * @return void
<ide> */
<ide> public function testImplementedEventsMethodName() {
<del> $this->markTestIncomplete('not done');
<add> $request = new Request(['url' => '/articles/view']);
<add> $response = new Response();
<ide>
<add> $beforeEvent = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<add> $afterEvent = new Event('Dispatcher.afterDispatch', $this, compact('response', 'request'));
<add>
<add> $filter = $this->getMock('Cake\Routing\DispatcherFilter', ['beforeDispatch', 'afterDispatch']);
<add> $filter->expects($this->at(0))
<add> ->method('beforeDispatch')
<add> ->with($beforeEvent);
<add> $filter->expects($this->at(1))
<add> ->method('afterDispatch')
<add> ->with($afterEvent);
<add>
<add> $filter->handle($beforeEvent);
<add> $filter->handle($afterEvent);
<ide> }
<ide>
<ide> /**
<ide> public function testImplementedEventsMethodName() {
<ide> * @return void
<ide> */
<ide> public function testHandleAppliesFor() {
<del> $this->markTestIncomplete('not done');
<add> $request = new Request(['url' => '/articles/view']);
<add> $response = new Response();
<add>
<add> $event = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<ide>
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch'],
<add> [['for' => '/admin']]
<add> );
<add> $filter->expects($this->never())
<add> ->method('beforeDispatch');
<add>
<add> $filter->handle($event);
<ide> }
<ide>
<ide> /**
<ide> public function testHandleAppliesFor() {
<ide> * @return void
<ide> */
<ide> public function testHandleAppliesWhen() {
<del> $this->markTestIncomplete('not done');
<add> $request = new Request(['url' => '/articles/view']);
<add> $response = new Response();
<add>
<add> $event = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<add> $matcher = function() {
<add> return false;
<add> };
<add>
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch'],
<add> [['when' => $matcher]]
<add> );
<add> $filter->expects($this->never())
<add> ->method('beforeDispatch');
<ide>
<add> $filter->handle($event);
<ide> }
<ide>
<ide> } | 2 |
Text | Text | add a tip to use switch | e4b4ad532f358d634b7b2582afe823f4f1f60c82 | <ide><path>share/doc/homebrew/Tips-N'-Tricks.md
<ide> This can be useful if a package can't build against the version of something you
<ide>
<ide> And of course, you can simply `brew link $FORMULA` again afterwards!
<ide>
<add>## Activate a previously installed version of a formula
<add>
<add>```sh
<add>brew info $FORMULA
<add>brew switch $FORMULA $VERSION
<add>```
<add>
<add>Use `brew info $FORMULA` to check what versions are installed but not currently activated, then `brew switch $FORMULA $VERSION` to activate the desired version. This can be useful if you would like to switch between versions of a formula.
<add>
<ide> ## Install into Homebrew without formulas
<ide>
<ide> ```sh | 1 |
Javascript | Javascript | fix typo in test | 158809db1195e6082b71b134a56f30ffe2aa7e11 | <ide><path>packages/ember-metal/tests/accessors/get_test.js
<ide> test('warn on attempts to get a property path of undefined', function() {
<ide> }, /Cannot call get with 'aProperty.on.aPath' on an undefined object/);
<ide> });
<ide>
<del>test('warn on attemps to get a falsy property', function() {
<add>test('warn on attempts to get a falsy property', function() {
<ide> var obj = {};
<ide> expectAssertion(function() {
<ide> get(obj, null); | 1 |
Text | Text | add introduce about cli options | bc51428bf8311f307ef38085d4567d4ba3be3cb0 | <ide><path>doc/guides/writing-and-running-benchmarks.md
<ide> The `compare.js` tool will then produce a csv file with the benchmark results.
<ide> $ node benchmark/compare.js --old ./node-master --new ./node-pr-5134 string_decoder > compare-pr-5134.csv
<ide> ```
<ide>
<add>*Tips: there are some useful options of `benchmark/compare.js`. For example, if you want to compare the benchmark of a single script instead of a whole module, you can use the `--filter` option:*
<add>
<add>```console
<add> --new ./new-node-binary new node binary (required)
<add> --old ./old-node-binary old node binary (required)
<add> --runs 30 number of samples
<add> --filter pattern string to filter benchmark scripts
<add> --set variable=value set benchmark variable (can be repeated)
<add> --no-progress don't show benchmark progress indicator
<add>```
<add>
<ide> For analysing the benchmark results use the `compare.R` tool.
<ide>
<ide> ```console | 1 |
Go | Go | use json.encoder for container.todisk | cf02b369e077022335f01b2f78ebd759129de82a | <ide><path>daemon/container.go
<ide> func (container *Container) fromDisk() error {
<ide> }
<ide>
<ide> func (container *Container) toDisk() error {
<del> data, err := json.Marshal(container)
<add> pth, err := container.jsonPath()
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> pth, err := container.jsonPath()
<add> jsonSource, err := os.Create(pth)
<ide> if err != nil {
<ide> return err
<ide> }
<add> defer jsonSource.Close()
<add>
<add> enc := json.NewEncoder(jsonSource)
<ide>
<del> if err := ioutil.WriteFile(pth, data, 0666); err != nil {
<add> // Save container settings
<add> if err := enc.Encode(container); err != nil {
<ide> return err
<ide> }
<ide> | 1 |
Javascript | Javascript | reduce extra rendering in navigationcard | bb39a2e9da7ba2d89c9d5e55cc6d730a56edd7c0 | <ide><path>Examples/UIExplorer/UIExplorerExampleList.js
<ide> /**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<ide> * The examples provided by Facebook are for non-commercial testing and
<ide> * evaluation purposes only.
<ide> *
<ide> */
<ide> 'use strict';
<ide>
<add>const ListView = require('ListView');
<ide> const React = require('react');
<del>const ReactNative = require('react-native');
<add>const StyleSheet = require('StyleSheet');
<add>const Text = require('Text');
<add>const TextInput = require('TextInput');
<add>const NavigationContainer = require('NavigationContainer');
<add>const TouchableHighlight = require('TouchableHighlight');
<add>const View = require('View');
<ide> const UIExplorerActions = require('./UIExplorerActions');
<del>const {
<del> ListView,
<del> NavigationExperimental,
<del> StyleSheet,
<del> Text,
<del> TextInput,
<del> TouchableHighlight,
<del> View,
<del>} = ReactNative;
<add>
<ide> const createExamplePage = require('./createExamplePage');
<del>const {
<del> Container: NavigationContainer,
<del>} = NavigationExperimental;
<ide>
<ide> import type {
<ide> UIExplorerExample,
<del>} from './UIExplorerList.ios'
<add>} from './UIExplorerList.ios';
<ide>
<ide> const ds = new ListView.DataSource({
<ide> rowHasChanged: (r1, r2) => r1 !== r2,
<ide> class UIExplorerExampleList extends React.Component {
<ide> }
<ide>
<ide> _handleRowPress(exampleKey: string): void {
<del> this.props.onNavigate(UIExplorerActions.ExampleAction(exampleKey))
<add> this.props.onNavigate(UIExplorerActions.ExampleAction(exampleKey));
<ide> }
<ide> }
<ide>
<ide> function makeRenderable(example: any): ReactClass<any> {
<ide> UIExplorerExampleList = NavigationContainer.create(UIExplorerExampleList);
<ide> UIExplorerExampleList.makeRenderable = makeRenderable;
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> listContainer: {
<ide> flex: 1,
<ide> },
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCard.js
<ide> import type {
<ide> NavigationSceneRendererProps,
<ide> } from 'NavigationTypeDefinition';
<ide>
<add>type SceneViewProps = {
<add> sceneRenderer: NavigationSceneRenderer,
<add> sceneRendererProps: NavigationSceneRendererProps,
<add>};
<add>
<ide> type Props = NavigationSceneRendererProps & {
<ide> onComponentRef: (ref: any) => void,
<ide> panHandlers: ?NavigationPanPanHandlers,
<ide> type Props = NavigationSceneRendererProps & {
<ide>
<ide> const {PropTypes} = React;
<ide>
<add>class SceneView extends React.Component<any, SceneViewProps, any> {
<add>
<add> static propTypes = {
<add> sceneRenderer: PropTypes.func.isRequired,
<add> sceneRendererProps: NavigationPropTypes.SceneRenderer,
<add> };
<add>
<add> shouldComponentUpdate(nextProps: SceneViewProps, nextState: any): boolean {
<add> return (
<add> nextProps.sceneRendererProps.scene.navigationState !==
<add> this.props.sceneRendererProps.scene.navigationState
<add> );
<add> }
<add>
<add> render(): ?ReactElement {
<add> return this.props.sceneRenderer(this.props.sceneRendererProps);
<add> }
<add>}
<add>
<ide> /**
<ide> * Component that renders the scene as card for the <NavigationCardStack />.
<ide> */
<ide> class NavigationCard extends React.Component<any, Props, any> {
<ide> pointerEvents={pointerEvents}
<ide> ref={this.props.onComponentRef}
<ide> style={[styles.main, viewStyle]}>
<del> {renderScene(props)}
<add> <SceneView
<add> sceneRenderer={renderScene}
<add> sceneRendererProps={props}
<add> />
<ide> </Animated.View>
<ide> );
<ide> } | 2 |
PHP | PHP | convert fqcns to use statements | a60e844de0d580d85e86e2a2da6937e4e5d111c9 | <ide><path>src/Shell/CacheShell.php
<ide> namespace Cake\Shell;
<ide>
<ide> use Cake\Cache\Cache;
<add>use Cake\Cache\Engine\ApcEngine;
<add>use Cake\Cache\Engine\WincacheEngine;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide>
<ide> public function clear($prefix = null)
<ide> try {
<ide> $engine = Cache::engine($prefix);
<ide> Cache::clear(false, $prefix);
<del> if ($engine instanceof \Cake\Cache\Engine\ApcEngine) {
<add> if ($engine instanceof ApcEngine) {
<ide> $this->warn("ApcEngine detected: Cleared $prefix CLI cache successfully " .
<ide> "but $prefix web cache must be cleared separately.");
<del> } elseif ($engine instanceof \Cake\Cache\Engine\WincacheEngine) {
<add> } elseif ($engine instanceof WincacheEngine) {
<ide> $this->warn("WincacheEngine detected: Cleared $prefix CLI cache successfully " .
<ide> "but $prefix web cache must be cleared separately.");
<ide> } else { | 1 |
PHP | PHP | add support for ltree | 89b316851eeba4c9e2ea19c87d928b96696f3259 | <ide><path>src/Illuminate/Database/Console/DatabaseInspectionCommand.php
<ide> abstract class DatabaseInspectionCommand extends Command
<ide> 'geometry' => 'string',
<ide> 'geomcollection' => 'string',
<ide> 'linestring' => 'string',
<add> 'ltree' => 'string',
<ide> 'multilinestring' => 'string',
<ide> 'multipoint' => 'string',
<ide> 'multipolygon' => 'string', | 1 |
Text | Text | fix ie8 tests for videojs_no_dynamic_style. closes | 3070e738f1c63044eae24d78847466d5ece4010f | <ide><path>CHANGELOG.md
<ide> CHANGELOG
<ide> * @ricardosiri68 changed the relative sass paths ([view](https://github.com/videojs/video.js/pull/3147))
<ide> * @gkatsev added an option to keep the tooltips inside the player bounds ([view](https://github.com/videojs/video.js/pull/3149))
<ide> * @defli added currentWidth and currentHeight methods to the player ([view](https://github.com/videojs/video.js/pull/3144))
<add>* fix IE8 tests for VIDEOJS_NO_DYNAMIC_STYLE ([view](https://github.com/videojs/video.js/pull/3215))
<ide>
<ide> --------------------
<ide> | 1 |
Python | Python | remove unused variables in examples | 81422c4e6d213767dc075f20049e8fd201675029 | <ide><path>examples/contrib/run_openai_gpt.py
<ide> AdamW,
<ide> OpenAIGPTDoubleHeadsModel,
<ide> OpenAIGPTTokenizer,
<del> cached_path,
<ide> get_linear_schedule_with_warmup,
<ide> )
<ide>
<ide>
<del>ROCSTORIES_URL = "https://s3.amazonaws.com/datasets.huggingface.co/ROCStories.tar.gz"
<del>
<ide> logging.basicConfig(
<ide> format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
<ide> )
<ide> def main():
<ide> model.to(device)
<ide>
<ide> # Load and encode the datasets
<del> if not args.train_dataset and not args.eval_dataset:
<del> roc_stories = cached_path(ROCSTORIES_URL)
<del>
<ide> def tokenize_and_encode(obj):
<ide> """ Tokenize and encode a nested object """
<ide> if isinstance(obj, str):
<ide><path>examples/contrib/run_transfo_xl.py
<ide>
<ide> import torch
<ide>
<del>from transformers import TransfoXLCorpus, TransfoXLLMHeadModel, TransfoXLTokenizer
<add>from transformers import TransfoXLCorpus, TransfoXLLMHeadModel
<ide>
<ide>
<ide> logging.basicConfig(
<ide> def main():
<ide> # The pre-processing involve computing word frequencies to prepare the Adaptive input and SoftMax
<ide> # and tokenizing the dataset
<ide> # The pre-processed corpus is a convertion (using the conversion script )
<del> tokenizer = TransfoXLTokenizer.from_pretrained(args.model_name)
<ide> corpus = TransfoXLCorpus.from_pretrained(args.model_name)
<del> ntokens = len(corpus.vocab)
<ide>
<ide> va_iter = corpus.get_iterator("valid", args.batch_size, args.tgt_len, device=device, ext_len=args.ext_len)
<ide> te_iter = corpus.get_iterator("test", args.batch_size, args.tgt_len, device=device, ext_len=args.ext_len)
<ide><path>examples/run_multiple_choice.py
<ide> def train(args, train_dataset, model, tokenizer):
<ide>
<ide> global_step = 0
<ide> tr_loss, logging_loss = 0.0, 0.0
<del> best_dev_acc, best_dev_loss = 0.0, 99999999999.0
<add> best_dev_acc = 0.0
<ide> best_steps = 0
<ide> model.zero_grad()
<ide> train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0])
<ide> def train(args, train_dataset, model, tokenizer):
<ide> tb_writer.add_scalar("eval_{}".format(key), value, global_step)
<ide> if results["eval_acc"] > best_dev_acc:
<ide> best_dev_acc = results["eval_acc"]
<del> best_dev_loss = results["eval_loss"]
<ide> best_steps = global_step
<ide> if args.do_test:
<ide> results_test = evaluate(args, model, tokenizer, test=True)
<ide><path>examples/summarization/modeling_bertabs.py
<ide> def forward(
<ide> batch_size = key.size(0)
<ide> dim_per_head = self.dim_per_head
<ide> head_count = self.head_count
<del> key_len = key.size(1)
<del> query_len = query.size(1)
<ide>
<ide> def shape(x):
<ide> """ projection """
<ide> def unshape(x):
<ide>
<ide> query = shape(query)
<ide>
<del> key_len = key.size(2)
<del> query_len = query.size(2)
<del>
<ide> # 2) Calculate and scale scores.
<ide> query = query / math.sqrt(dim_per_head)
<ide> scores = torch.matmul(query, key.transpose(2, 3)) | 4 |
PHP | PHP | remove unneeded variable assignments | 334bcc1571640cf33e1354ee6e72223d4f0302ab | <ide><path>src/Cache/Engine/FileEngine.php
<ide> protected function _clearDirectory(string $path): void
<ide>
<ide> if ($file->isFile()) {
<ide> $filePath = $file->getRealPath();
<del> $file = null;
<add> unset($file);
<ide>
<ide> // phpcs:disable
<ide> @unlink($filePath);
<ide> function (SplFileInfo $current) use ($group, $prefix) {
<ide> );
<ide> foreach ($filtered as $object) {
<ide> $path = $object->getPathname();
<del> $object = null;
<add> unset($object);
<ide> // phpcs:ignore
<ide> @unlink($path);
<ide> }
<ide><path>src/Collection/CollectionTrait.php
<ide> public function transpose(): CollectionInterface
<ide> $arrayValue = $this->toList();
<ide> $length = count(current($arrayValue));
<ide> $result = [];
<del> foreach ($arrayValue as $column => $row) {
<add> foreach ($arrayValue as $row) {
<ide> if (count($row) !== $length) {
<ide> throw new LogicException('Child arrays do not have even length');
<ide> }
<ide><path>src/Console/ConsoleOptionParser.php
<ide> public function addArgument($name, array $params = [])
<ide> unset($options['index']);
<ide> $arg = new ConsoleInputArgument($options);
<ide> }
<del> foreach ($this->_args as $k => $a) {
<add> foreach ($this->_args as $a) {
<ide> if ($a->isEqualTo($arg)) {
<ide> return $this;
<ide> }
<ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _fieldsList(array $check): array
<ide> $unlocked = $this->_unlocked($check);
<ide>
<ide> if (strpos($token, ':')) {
<del> [$token, $locked] = explode(':', $token, 2);
<add> [, $locked] = explode(':', $token, 2);
<ide> }
<ide> unset($check['_Token']);
<ide>
<ide><path>src/Database/Expression/TupleComparison.php
<ide> public function traverse(Closure $callable)
<ide> return $this;
<ide> }
<ide>
<del> foreach ($value as $i => $val) {
<add> foreach ($value as $val) {
<ide> if ($this->isMulti()) {
<ide> foreach ($val as $v) {
<ide> $this->_traverseValue($v, $callable);
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function traverse(Closure $visitor)
<ide> if (!is_array($v)) {
<ide> continue;
<ide> }
<del> foreach ($v as $column => $field) {
<add> foreach ($v as $field) {
<ide> if ($field instanceof ExpressionInterface) {
<ide> $visitor($field);
<ide> $field->traverse($visitor);
<ide><path>src/Database/Schema/TableSchema.php
<ide> public function getIndex(string $name): ?array
<ide> */
<ide> public function primaryKey(): array
<ide> {
<del> foreach ($this->_constraints as $name => $data) {
<add> foreach ($this->_constraints as $data) {
<ide> if ($data['type'] === static::CONSTRAINT_PRIMARY) {
<ide> return $data['columns'];
<ide> }
<ide><path>src/Form/FormProtector.php
<ide> protected function extractFields(array $formData): array
<ide> $unlocked = urldecode($formData['_Token']['unlocked']);
<ide>
<ide> if (strpos($token, ':')) {
<del> [$token, $locked] = explode(':', $token, 2);
<add> [, $locked] = explode(':', $token, 2);
<ide> }
<ide> unset($formData['_Token']);
<ide>
<ide><path>src/Http/Client/Response.php
<ide> protected function _decodeGzipBody(string $body): string
<ide> */
<ide> protected function _parseHeaders(array $headers): void
<ide> {
<del> foreach ($headers as $key => $value) {
<add> foreach ($headers as $value) {
<ide> if (substr($value, 0, 5) === 'HTTP/') {
<ide> preg_match('/HTTP\/([\d.]+) ([0-9]+)(.*)/i', $value, $matches);
<ide> $this->protocol = $matches[1];
<ide><path>src/Http/ResponseEmitter.php
<ide> protected function emitBody(ResponseInterface $response): void
<ide> */
<ide> protected function emitBodyRange(array $range, ResponseInterface $response): void
<ide> {
<del> [$unit, $first, $last, $length] = $range;
<add> [, $first, $last] = $range;
<ide>
<ide> $body = $response->getBody();
<ide>
<ide><path>src/I18n/FrozenTime.php
<ide> public static function listTimezones($filter = null, ?string $country = null, $o
<ide> $now = time();
<ide> $before = $options['before'];
<ide> $after = $options['after'];
<del> foreach ($identifiers as $key => $tz) {
<add> foreach ($identifiers as $tz) {
<ide> $abbr = '';
<ide> if ($options['abbr']) {
<ide> $dateTimeZone = new DateTimeZone($tz);
<ide><path>src/I18n/Time.php
<ide> public static function listTimezones($filter = null, ?string $country = null, $o
<ide> $now = time();
<ide> $before = $options['before'];
<ide> $after = $options['after'];
<del> foreach ($identifiers as $key => $tz) {
<add> foreach ($identifiers as $tz) {
<ide> $abbr = '';
<ide> if ($options['abbr']) {
<ide> $dateTimeZone = new DateTimeZone($tz);
<ide><path>src/Mailer/Message.php
<ide> public function getBodyTypes(): array
<ide> return [static::MESSAGE_HTML, static::MESSAGE_TEXT];
<ide> }
<ide>
<del> return $types = [$format];
<add> return [$format];
<ide> }
<ide>
<ide> /**
<ide><path>src/ORM/Behavior.php
<ide> protected function _reflectionCache(): array
<ide>
<ide> $events = $this->implementedEvents();
<ide> $eventMethods = [];
<del> foreach ($events as $e => $binding) {
<add> foreach ($events as $binding) {
<ide> if (is_array($binding) && isset($binding['callable'])) {
<ide> /** @var string $callable */
<ide> $callable = $binding['callable'];
<ide><path>src/Routing/Route/Route.php
<ide> public function match(array $url, array $context = []): ?string
<ide>
<ide> $pass = [];
<ide> foreach ($url as $key => $value) {
<del> // keys that exist in the defaults and have different values is a match failure.
<del> $defaultExists = array_key_exists($key, $defaults);
<del>
<ide> // If the key is a routed key, it's not different yet.
<ide> if (array_key_exists($key, $keyNames)) {
<ide> continue;
<ide><path>src/TestSuite/Constraint/EventFiredWith.php
<ide> public function matches($other): bool
<ide> {
<ide> $firedEvents = [];
<ide> $list = $this->_eventManager->getEventList();
<del> if ($list === null) {
<del> $totalEvents = 0;
<del> } else {
<add> if ($list !== null) {
<ide> $totalEvents = count($list);
<ide> for ($e = 0; $e < $totalEvents; $e++) {
<ide> $firedEvents[] = $list[$e];
<ide><path>src/Utility/Xml.php
<ide> public static function build($input, array $options = [])
<ide> */
<ide> protected static function _loadXml(string $input, array $options)
<ide> {
<del> $hasDisable = function_exists('libxml_disable_entity_loader');
<ide> $internalErrors = libxml_use_internal_errors(true);
<del> if ($hasDisable && !$options['loadEntities']) {
<add> if (!$options['loadEntities']) {
<ide> libxml_disable_entity_loader(true);
<ide> }
<ide> $flags = 0;
<ide> protected static function _loadXml(string $input, array $options)
<ide> } catch (Exception $e) {
<ide> throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
<ide> } finally {
<del> if ($hasDisable && !$options['loadEntities']) {
<add> if (!$options['loadEntities']) {
<ide> libxml_disable_entity_loader(false);
<ide> }
<ide> libxml_use_internal_errors($internalErrors);
<ide> public static function loadHtml(string $input, array $options = [])
<ide> ];
<ide> $options += $defaults;
<ide>
<del> $hasDisable = function_exists('libxml_disable_entity_loader');
<ide> $internalErrors = libxml_use_internal_errors(true);
<del> if ($hasDisable && !$options['loadEntities']) {
<add> if (!$options['loadEntities']) {
<ide> libxml_disable_entity_loader(true);
<ide> }
<ide> $flags = 0;
<ide> public static function loadHtml(string $input, array $options = [])
<ide> $xml->loadHTML($input, $flags);
<ide>
<ide> if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
<del> $flags |= LIBXML_NOCDATA;
<ide> $xml = simplexml_import_dom($xml);
<ide> }
<ide>
<ide> return $xml;
<ide> } catch (Exception $e) {
<ide> throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
<ide> } finally {
<del> if ($hasDisable && !$options['loadEntities']) {
<add> if (!$options['loadEntities']) {
<ide> libxml_disable_entity_loader(false);
<ide> }
<ide> libxml_use_internal_errors($internalErrors); | 17 |
Mixed | Javascript | make use of "cannot" consistent | 9f22fda6466e835f4fb56552c4d3a9d98eb1c1d7 | <ide><path>doc/api/errors.md
<ide> To fix the error, open an issue at https://github.com/nodejs/node/issues.
<ide> <a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a>
<ide> ### `ERR_INCOMPATIBLE_OPTION_PAIR`
<ide>
<del>An option pair is incompatible with each other and can not be used at the same
<add>An option pair is incompatible with each other and cannot be used at the same
<ide> time.
<ide>
<ide> <a id="ERR_INPUT_TYPE_NOT_ALLOWED"></a>
<ide><path>lib/internal/errors.js
<ide> E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s', RangeError);
<ide> E('ERR_HTTP_TRAILER_INVALID',
<ide> 'Trailers are invalid with this transfer encoding', Error);
<ide> E('ERR_INCOMPATIBLE_OPTION_PAIR',
<del> 'Option "%s" can not be used in combination with option "%s"', TypeError);
<add> 'Option "%s" cannot be used in combination with option "%s"', TypeError);
<ide> E('ERR_INPUT_TYPE_NOT_ALLOWED', '--input-type can only be used with string ' +
<ide> 'input via --eval, --print, or STDIN', Error);
<ide> E('ERR_INSPECTOR_ALREADY_CONNECTED', '%s is already connected', Error);
<ide><path>test/parallel/test-console-tty-colors.js
<ide> check(false, false, false);
<ide> });
<ide> },
<ide> {
<del> message: 'Option "inspectOptions.color" can not be used in ' +
<add> message: 'Option "inspectOptions.color" cannot be used in ' +
<ide> 'combination with option "colorMode"',
<ide> code: 'ERR_INCOMPATIBLE_OPTION_PAIR'
<ide> }
<ide><path>test/parallel/test-crypto-keygen.js
<ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
<ide> }, {
<ide> name: 'TypeError',
<ide> code: 'ERR_INCOMPATIBLE_OPTION_PAIR',
<del> message: `Option "${opt1}" can not be used in combination with option ` +
<add> message: `Option "${opt1}" cannot be used in combination with option ` +
<ide> `"${opt2}"`
<ide> });
<ide> } | 4 |
Javascript | Javascript | add test for exec() known issue | c96457403eef895a5541429404207c1985df240f | <ide><path>test/known_issues/test-child-process-exec-stdout-data-string.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/7342
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const exec = require('child_process').exec;
<add>
<add>const expectedCalls = 2;
<add>
<add>const cb = common.mustCall((data) => {
<add> assert.strictEqual(typeof data, 'string');
<add>}, expectedCalls);
<add>
<add>const command = common.isWindows ? 'dir' : 'ls';
<add>exec(command).stdout.on('data', cb);
<add>
<add>exec('fhqwhgads').stderr.on('data', cb); | 1 |
Ruby | Ruby | use non-raising finder | fcc47bcfccc7578aa0414710eecdad006085a911 | <ide><path>activesupport/lib/active_support/current_attributes.rb
<ide> module ActiveSupport
<ide> #
<ide> # private
<ide> # def authenticate
<del> # if authenticated_user = User.find(cookies.signed[:user_id])
<add> # if authenticated_user = User.find_by(id: cookies.signed[:user_id])
<ide> # Current.user = authenticated_user
<ide> # else
<ide> # redirect_to new_session_url | 1 |
Text | Text | correct typos in back end development and apis | a481b9525cdeec478647915cb7ff94de560e468e | <ide><path>curriculum/challenges/english/05-back-end-development-and-apis/mongodb-and-mongoose/create-a-model.md
<ide> dashedName: create-a-model
<ide>
<ide> **C**RUD Part I - CREATE
<ide>
<del>First of all we need a Schema. Each schema maps to a MongoDB collection. It defines the shape of the documents within that collection. Schemas are building block for Models. They can be nested to create complex models, but in this case we'll keep things simple. A model allows you to create instances of your objects, called documents.
<add>First of all, we need a Schema. Each schema maps to a MongoDB collection. It defines the shape of the documents within that collection. Schemas are building blocks for Models. They can be nested to create complex models, but in this case, we'll keep things simple. A model allows you to create instances of your objects, called documents.
<ide>
<del>Replit is a real server, and in real servers the interactions with the database happen in handler functions. These functions are executed when some event happens (e.g. someone hits an endpoint on your API). We’ll follow the same approach in these exercises. The `done()` function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It's following the Node convention, and should be called as `done(null, data)` on success, or `done(err)` on error.
<add>Replit is a real server, and in real servers, the interactions with the database happen in handler functions. These functions are executed when some event happens (e.g. someone hits an endpoint on your API). We’ll follow the same approach in these exercises. The `done()` function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It's following the Node convention, and should be called as `done(null, data)` on success, or `done(err)` on error.
<ide>
<ide> Warning - When interacting with remote services, errors may occur!
<ide> | 1 |
Python | Python | fix torch to tf translation | a2c8e516c2fb55cf37844d434ae04b5abcfbc81b | <ide><path>src/transformers/modeling_tf_utils.py
<ide> def generate(
<ide>
<ide> # create attention mask if necessary
<ide> # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140
<del> if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):
<add> import ipdb
<add>
<add> ipdb.set_trace()
<add> if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids.numpy()):
<ide> attention_mask = tf.cast(tf.math.not_equal(input_ids, pad_token_id), dtype=tf.int32)
<ide> elif attention_mask is None:
<ide> attention_mask = tf.ones_like(input_ids) | 1 |
Javascript | Javascript | add vibration module mock | 79529a1c77e7e1b174fdbe8103a2199c9ac924ff | <ide><path>jest/setup.js
<ide> jest
<ide> '../Libraries/Utilities/verifyComponentAttributeEquivalence',
<ide> () => function () {},
<ide> )
<add> .mock('../Libraries/Vibration/Vibration', () => ({
<add> vibrate: jest.fn(),
<add> cancel: jest.fn(),
<add> }))
<ide> .mock('../Libraries/Components/View/ViewNativeComponent', () => {
<ide> const React = require('react');
<ide> const Component = class extends React.Component { | 1 |
Ruby | Ruby | remove the patch from the cache after applying it | d706bcf153ca09932b9166a4d664a33aed77d693 | <ide><path>Library/Contributions/cmd/brew-pull.rb
<ide> def tap arg
<ide> rescue ErrorDuringExecution
<ide> system 'git', 'am', '--abort'
<ide> odie 'Patch failed to apply: aborted.'
<add> ensure
<add> patchpath.unlink
<ide> end
<ide>
<ide> changed_formulae = [] | 1 |
PHP | PHP | remove 2 duplicate routecollection tests. | d25de019447e66fe44376a13dbf09956cdadd354 | <ide><path>tests/Routing/RouteCollectionTest.php
<ide> public function testRouteCollectionAddReturnsTheRoute()
<ide> $this->assertEquals($inputRoute, $outputRoute);
<ide> }
<ide>
<del> public function testRouteCollectionAddRouteChangesCount()
<del> {
<del> $this->routeCollection->add(new Route('GET', 'foo', [
<del> 'uses' => 'FooController@index',
<del> 'as' => 'foo_index',
<del> ]));
<del> $this->assertCount(1, $this->routeCollection);
<del> }
<del>
<del> public function testRouteCollectionIsCountable()
<del> {
<del> $this->routeCollection->add(new Route('GET', 'foo', [
<del> 'uses' => 'FooController@index',
<del> 'as' => 'foo_index',
<del> ]));
<del> $this->assertCount(1, $this->routeCollection);
<del> }
<del>
<ide> public function testRouteCollectionCanRetrieveByName()
<ide> {
<ide> $this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ | 1 |
Python | Python | remove legacy axis handling in tf backend | 46b691e302e896053c4fd167ca4ec688d957b245 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def gather(reference, indices):
<ide>
<ide> # ELEMENT-WISE OPERATIONS
<ide>
<del>def _normalize_axis(axis, ndim):
<del> """Converts negative axes to positive values.
<del>
<del> # Arguments
<del> axis: Integer axis (possibly negative).
<del> ndim: Rank of the tensor considered.
<del>
<del> # Returns
<del> Positive integer axis.
<del> """
<del> if isinstance(axis, tuple):
<del> axis = list(axis)
<del> if isinstance(axis, list):
<del> for i, a in enumerate(axis):
<del> if a is not None and a < 0:
<del> axis[i] = a % ndim
<del> else:
<del> if axis is not None and axis < 0:
<del> axis %= ndim
<del> return axis
<del>
<ide>
<ide> def max(x, axis=None, keepdims=False):
<ide> """Maximum value in a tensor.
<ide> def max(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with maximum values of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.reduce_max(x, axis=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def min(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with miminum values of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.reduce_min(x, axis=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def sum(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with sum of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.reduce_sum(x, axis=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def prod(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with the product of elements of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.reduce_prod(x, axis=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def cumsum(x, axis=0):
<ide> # Returns
<ide> A tensor of the cumulative sum of values of `x` along `axis`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.cumsum(x, axis=axis)
<ide>
<ide>
<ide> def cumprod(x, axis=0):
<ide> # Returns
<ide> A tensor of the cumulative product of values of `x` along `axis`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.cumprod(x, axis=axis)
<ide>
<ide>
<ide> def var(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with the variance of elements of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> if x.dtype.base_dtype == tf.bool:
<ide> x = tf.cast(x, floatx())
<ide> m = tf.reduce_mean(x, axis=axis, keep_dims=True)
<ide> def mean(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A tensor with the mean of elements of `x`.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> if x.dtype.base_dtype == tf.bool:
<ide> x = tf.cast(x, floatx())
<ide> return tf.reduce_mean(x, axis=axis, keep_dims=keepdims)
<ide> def any(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A uint8 tensor (0s and 1s).
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> x = tf.cast(x, tf.bool)
<ide> return tf.reduce_any(x, axis=axis, keep_dims=keepdims)
<ide>
<ide> def all(x, axis=None, keepdims=False):
<ide> # Returns
<ide> A uint8 tensor (0s and 1s).
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> x = tf.cast(x, tf.bool)
<ide> return tf.reduce_all(x, axis=axis, keep_dims=keepdims)
<ide>
<ide> def argmax(x, axis=-1):
<ide> # Returns
<ide> A tensor.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.argmax(x, axis)
<ide>
<ide>
<ide> def argmin(x, axis=-1):
<ide> # Returns
<ide> A tensor.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.argmin(x, axis)
<ide>
<ide>
<ide> def logsumexp(x, axis=None, keepdims=False):
<ide> # Returns
<ide> The reduced tensor.
<ide> """
<del> axis = _normalize_axis(axis, ndim(x))
<ide> return tf.reduce_logsumexp(x, axis=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def l2_normalize(x, axis):
<ide> # Returns
<ide> A tensor.
<ide> """
<del> if axis < 0:
<del> axis %= len(x.get_shape())
<ide> return tf.nn.l2_normalize(x, dim=axis)
<ide>
<ide> | 1 |
PHP | PHP | add deprecation comments (cs related) | 9ba194427c9d02edbefbcbc56ef0e02f4b4448af | <ide><path>src/Validation/Validation.php
<ide> public static function comparison($check1, $operator, $check2)
<ide> switch ($operator) {
<ide> case 'isgreater':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_GREATER'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_GREATER instead.
<ide> case static::COMPARE_GREATER:
<ide> if ($check1 > $check2) {
<ide> return true;
<ide> }
<ide> break;
<ide> case 'isless':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_LESS'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_LESS instead.
<ide> case static::COMPARE_LESS:
<ide> if ($check1 < $check2) {
<ide> return true;
<ide> }
<ide> break;
<ide> case 'greaterorequal':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_GREATER_OR_EQUAL'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_GREATER_OR_EQUAL instead.
<ide> case static::COMPARE_GREATER_OR_EQUAL:
<ide> if ($check1 >= $check2) {
<ide> return true;
<ide> }
<ide> break;
<ide> case 'lessorequal':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_LESS_OR_EQUAL'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_LESS_OR_EQUAL instead.
<ide> case static::COMPARE_LESS_OR_EQUAL:
<ide> if ($check1 <= $check2) {
<ide> return true;
<ide> }
<ide> break;
<ide> case 'equalto':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_EQUAL'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_EQUAL instead.
<ide> case static::COMPARE_EQUAL:
<ide> if ($check1 == $check2) {
<ide> return true;
<ide> }
<ide> break;
<ide> case 'notequal':
<ide> deprecationWarning(sprintf($message, $operator, 'COMPARE_NOT_EQUAL'));
<add> // @deprecated 3.6.0 Use Validation::COMPARE_NOT_EQUAL instead.
<ide> case static::COMPARE_NOT_EQUAL:
<ide> if ($check1 != $check2) {
<ide> return true; | 1 |
Text | Text | include latest version of jquery in tutorial | 580f2d829bc306ba1c7cabea8a9299bdbc2a5670 | <ide><path>docs/docs/tutorial.md
<ide> For this tutorial, we'll use prebuilt JavaScript files on a CDN. Open up your fa
<ide> <title>Hello React</title>
<ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script>
<ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<del> <script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<add> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<ide> </head>
<ide> <body>
<ide> <div id="content"></div> | 1 |
Ruby | Ruby | synchronize the lazy setters in server | 16a6603956551703e3bbd06101c568a73bcdaa52 | <ide><path>actioncable/lib/action_cable/server/base.rb
<add>require 'thread'
<add>
<ide> module ActionCable
<ide> module Server
<ide> # A singleton ActionCable::Server instance is available via ActionCable.server. It's used by the rack process that starts the cable server, but
<ide> class Base
<ide> def self.logger; config.logger; end
<ide> delegate :logger, to: :config
<ide>
<add> attr_reader :mutex
<add>
<ide> def initialize
<add> @mutex = Mutex.new
<add>
<add> @remote_connections = @stream_event_loop = @worker_pool = @channel_classes = @pubsub = nil
<ide> end
<ide>
<ide> # Called by rack to setup the server.
<ide> def disconnect(identifiers)
<ide>
<ide> # Gateway to RemoteConnections. See that class for details.
<ide> def remote_connections
<del> @remote_connections ||= RemoteConnections.new(self)
<add> @remote_connections || @mutex.synchronize { @remote_connections ||= RemoteConnections.new(self) }
<ide> end
<ide>
<ide> def stream_event_loop
<del> @stream_event_loop ||= ActionCable::Connection::StreamEventLoop.new
<add> @stream_event_loop || @mutex.synchronize { @stream_event_loop ||= ActionCable::Connection::StreamEventLoop.new }
<ide> end
<ide>
<ide> # The thread worker pool for handling all the connection work on this server. Default size is set by config.worker_pool_size.
<ide> def worker_pool
<del> @worker_pool ||= ActionCable::Server::Worker.new(max_size: config.worker_pool_size)
<add> @worker_pool || @mutex.synchronize { @worker_pool ||= ActionCable::Server::Worker.new(max_size: config.worker_pool_size) }
<ide> end
<ide>
<ide> # Requires and returns a hash of all the channel class constants keyed by name.
<ide> def channel_classes
<del> @channel_classes ||= begin
<del> config.channel_paths.each { |channel_path| require channel_path }
<del> config.channel_class_names.each_with_object({}) { |name, hash| hash[name] = name.constantize }
<add> @channel_classes || @mutex.synchronize do
<add> @channel_classes ||= begin
<add> config.channel_paths.each { |channel_path| require channel_path }
<add> config.channel_class_names.each_with_object({}) { |name, hash| hash[name] = name.constantize }
<add> end
<ide> end
<ide> end
<ide>
<ide> # Adapter used for all streams/broadcasting.
<ide> def pubsub
<del> @pubsub ||= config.pubsub_adapter.new(self)
<add> @pubsub || @mutex.synchronize { @pubsub ||= config.pubsub_adapter.new(self) }
<ide> end
<ide>
<ide> # All the identifiers applied to the connection class associated with this server.
<ide><path>actioncable/lib/action_cable/subscription_adapter/async.rb
<ide> module ActionCable
<ide> module SubscriptionAdapter
<ide> class Async < Inline # :nodoc:
<ide> private
<del> def subscriber_map
<del> @subscriber_map ||= AsyncSubscriberMap.new
<add> def new_subscriber_map
<add> AsyncSubscriberMap.new
<ide> end
<ide>
<ide> class AsyncSubscriberMap < SubscriberMap
<ide><path>actioncable/lib/action_cable/subscription_adapter/inline.rb
<ide> module ActionCable
<ide> module SubscriptionAdapter
<ide> class Inline < Base # :nodoc:
<add> def initialize(*)
<add> super
<add> @subscriber_map = nil
<add> end
<add>
<ide> def broadcast(channel, payload)
<ide> subscriber_map.broadcast(channel, payload)
<ide> end
<ide> def shutdown
<ide>
<ide> private
<ide> def subscriber_map
<del> @subscriber_map ||= SubscriberMap.new
<add> @subscriber_map || @server.mutex.synchronize { @subscriber_map ||= new_subscriber_map }
<add> end
<add>
<add> def new_subscriber_map
<add> SubscriberMap.new
<ide> end
<ide> end
<ide> end
<ide><path>actioncable/lib/action_cable/subscription_adapter/postgresql.rb
<ide> module ActionCable
<ide> module SubscriptionAdapter
<ide> class PostgreSQL < Base # :nodoc:
<add> def initialize(*)
<add> super
<add> @listener = nil
<add> end
<add>
<ide> def broadcast(channel, payload)
<ide> with_connection do |pg_conn|
<ide> pg_conn.exec("NOTIFY #{pg_conn.escape_identifier(channel)}, '#{pg_conn.escape_string(payload)}'")
<ide> def with_connection(&block) # :nodoc:
<ide>
<ide> private
<ide> def listener
<del> @listener ||= Listener.new(self)
<add> @listener || @server.mutex.synchronize { @listener ||= Listener.new(self) }
<ide> end
<ide>
<ide> class Listener < SubscriberMap
<ide><path>actioncable/lib/action_cable/subscription_adapter/redis.rb
<ide> module SubscriptionAdapter
<ide> class Redis < Base # :nodoc:
<ide> @@mutex = Mutex.new
<ide>
<add> def initialize(*)
<add> super
<add> @redis_connection_for_broadcasts = @redis_connection_for_subscriptions = nil
<add> end
<add>
<ide> def broadcast(channel, payload)
<ide> redis_connection_for_broadcasts.publish(channel, payload)
<ide> end
<ide> def shutdown
<ide> private
<ide> def redis_connection_for_subscriptions
<ide> ensure_reactor_running
<del> @redis_connection_for_subscriptions ||= EM::Hiredis.connect(@server.config.cable[:url]).tap do |redis|
<del> redis.on(:reconnect_failed) do
<del> @logger.info "[ActionCable] Redis reconnect failed."
<add> @redis_connection_for_subscriptions || @server.mutex.synchronize do
<add> @redis_connection_for_subscriptions ||= EM::Hiredis.connect(@server.config.cable[:url]).tap do |redis|
<add> redis.on(:reconnect_failed) do
<add> @logger.info "[ActionCable] Redis reconnect failed."
<add> end
<ide> end
<ide> end
<ide> end
<ide>
<ide> def redis_connection_for_broadcasts
<del> @redis_connection_for_broadcasts ||= ::Redis.new(@server.config.cable)
<add> @redis_connection_for_broadcasts || @server.mutex.synchronize do
<add> @redis_connection_for_broadcasts ||= ::Redis.new(@server.config.cable)
<add> end
<ide> end
<ide>
<ide> def ensure_reactor_running | 5 |
Ruby | Ruby | support mysql 5.7 explain | 75f453ff4cff8b9652cc8f54ee68f775341148e9 | <ide><path>activerecord/test/cases/adapters/mysql2/explain_test.rb
<ide> class ExplainTest < ActiveRecord::TestCase
<ide> def test_explain_for_one_query
<ide> explain = Developer.where(:id => 1).explain
<ide> assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
<del> assert_match %(developers | const), explain
<add> assert_match /developers |.* const/, explain
<ide> end
<ide>
<ide> def test_explain_with_eager_loading
<ide> explain = Developer.where(:id => 1).includes(:audit_logs).explain
<ide> assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
<del> assert_match %(developers | const), explain
<add> assert_match /developers |.* const/, explain
<ide> assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` IN (1)), explain
<del> assert_match %(audit_logs | ALL), explain
<add> assert_match /audit_logs |.* ALL/, explain
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | fix examples in docstring for np.flip | 3d5caa2b8cb51851f218283cd2435b00ecce5d16 | <ide><path>numpy/lib/function_base.py
<ide> def flip(m, axis):
<ide> >>> A
<ide> array([[[0, 1],
<ide> [2, 3]],
<del>
<ide> [[4, 5],
<ide> [6, 7]]])
<ide>
<ide> >>> flip(A, 0)
<ide> array([[[4, 5],
<ide> [6, 7]],
<del>
<ide> [[0, 1],
<ide> [2, 3]]])
<ide>
<ide> >>> flip(A, 1)
<ide> array([[[2, 3],
<ide> [0, 1]],
<del>
<ide> [[6, 7],
<ide> [4, 5]]])
<ide> | 1 |
Javascript | Javascript | remove unused variables | 4f14bea2c29fb9c1e1cf48da7f700c963e35f693 | <ide><path>test/unit/selector.js
<ide> test( "selectors with comma", function() {
<ide> equal( fixture.find( "h2 , div p" ).filter( "h2" ).length, 1, "has to find one <h2>" );
<ide> });
<ide>
<del>test("child and adjacent", function() {
<add>test( "child and adjacent", function() {
<ide> expect( 27 );
<ide>
<ide> var nothiddendiv;
<ide> test("child and adjacent", function() {
<ide> test("attributes", function() {
<ide> expect( 54 );
<ide>
<del> var opt, input, attrbad, div, withScript;
<add> var attrbad, div, withScript;
<ide>
<ide> t( "Find elements with a tabindex attribute", "[tabindex]", ["listWithTabIndex", "foodWithNegativeTabIndex", "linkWithTabIndex", "linkWithNegativeTabIndex", "linkWithNoHrefWithTabIndex", "linkWithNoHrefWithNegativeTabIndex"] );
<ide> | 1 |
Javascript | Javascript | use fs.realpath to get actual project directory | 828dac7d6182095bb53e90441c184c46858cbc5a | <ide><path>server/build/webpack.js
<ide> import { resolve, join, sep } from 'path'
<ide> import { createHash } from 'crypto'
<add>import { realpathSync } from 'fs'
<ide> import webpack from 'webpack'
<ide> import glob from 'glob-promise'
<ide> import WriteFilePlugin from 'write-file-webpack-plugin'
<ide> const interpolateNames = new Map(defaultPages.map((p) => {
<ide> const relativeResolve = rootModuleRelativePath(require)
<ide>
<ide> export default async function createCompiler (dir, { buildId, dev = false, quiet = false, buildDir, conf = null } = {}) {
<del> dir = resolve(dir)
<add> dir = realpathSync(resolve(dir))
<ide> const config = getConfig(dir, conf)
<ide> const defaultEntries = dev ? [
<ide> join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'), | 1 |
Ruby | Ruby | fix output of optional dependencies | f5fbb74aaf847c9589af82ceea2f388eae02e0f6 | <ide><path>Library/Homebrew/formula.rb
<ide> def opt_or_installed_prefix_keg
<ide>
<ide> # Returns a list of Dependency objects that are required at runtime.
<ide> # @private
<del> def runtime_dependencies(read_from_tab: true)
<add> def runtime_dependencies(read_from_tab: true, undeclared: true)
<ide> if read_from_tab &&
<ide> (keg = opt_or_installed_prefix_keg) &&
<ide> (tab_deps = keg.runtime_dependencies)
<ide> def runtime_dependencies(read_from_tab: true)
<ide> end.compact
<ide> end
<ide>
<add> return declared_runtime_dependencies unless undeclared
<ide> declared_runtime_dependencies | undeclared_runtime_dependencies
<ide> end
<ide>
<ide><path>Library/Homebrew/linkage_checker.rb
<ide> def check_undeclared_deps
<ide> declared_deps_names = declared_deps_full_names.map do |dep|
<ide> dep.split("/").last
<ide> end
<del> recursive_deps = formula.declared_runtime_dependencies.map do |dep|
<add> recursive_deps = formula.runtime_dependencies(undeclared: false)
<add> .map do |dep|
<ide> begin
<ide> dep.to_formula.name
<ide> rescue FormulaUnavailableError | 2 |
Go | Go | fix issues from rebase on master | 5e69b3837b26d1d1f7cd8b3c4f5b077ba642bd20 | <ide><path>networkdriver/ipallocator/allocator.go
<ide> import (
<ide> "errors"
<ide> "github.com/dotcloud/docker/networkdriver"
<ide> "github.com/dotcloud/docker/pkg/collections"
<del> "github.com/dotcloud/docker/pkg/netlink"
<ide> "net"
<ide> "sync"
<ide> )
<ide>
<del>type networkSet map[iPNet]*collections.OrderedIntSet
<add>type networkSet map[string]*collections.OrderedIntSet
<ide>
<ide> var (
<ide> ErrNoAvailableIPs = errors.New("no available ip addresses on network")
<ide> func intToIP(n int32) *net.IP {
<ide> func checkAddress(address *net.IPNet) {
<ide> key := address.String()
<ide> if _, exists := allocatedIPs[key]; !exists {
<del> allocatedIPs[key] = &iPSet{}
<del> availableIPS[key] = &iPSet{}
<add> allocatedIPs[key] = collections.NewOrderedIntSet()
<add> availableIPS[key] = collections.NewOrderedIntSet()
<ide> }
<ide> } | 1 |
Ruby | Ruby | set prefer_loading_from_api for fetch | f5696efc1620da3ee3906e6961d71181cb047f4b | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> args = fetch_args.parse
<ide>
<ide> bucket = if args.deps?
<del> args.named.to_formulae_and_casks.flat_map do |formula_or_cask|
<add> args.named.to_formulae_and_casks(prefer_loading_from_api: true).flat_map do |formula_or_cask|
<ide> case formula_or_cask
<ide> when Formula
<ide> f = formula_or_cask
<ide> def fetch
<ide> end
<ide> end
<ide> else
<del> args.named.to_formulae_and_casks
<add> args.named.to_formulae_and_casks(prefer_loading_from_api: true)
<ide> end.uniq
<ide>
<ide> puts "Fetching: #{bucket * ", "}" if bucket.size > 1 | 1 |
Javascript | Javascript | refactor the console module to be reusable | 025f53c306d91968b292051404aebb8bf2adb458 | <ide><path>lib/console.js
<ide>
<ide> var util = require('util');
<ide>
<del>exports.log = function() {
<del> process.stdout.write(util.format.apply(this, arguments) + '\n');
<add>function Console(stdout, stderr) {
<add> if (!(this instanceof Console)) {
<add> return new Console(stdout, stderr);
<add> }
<add> if (!stdout || typeof stdout.write !== 'function') {
<add> throw new TypeError('Console expects a writable stream instance');
<add> }
<add> if (!stderr) {
<add> stderr = stdout;
<add> }
<add> var prop = {
<add> writable: true,
<add> enumerable: false,
<add> configurable: true
<add> };
<add> prop.value = stdout;
<add> Object.defineProperty(this, '_stdout', prop);
<add> prop.value = stderr;
<add> Object.defineProperty(this, '_stderr', prop);
<add> prop.value = {};
<add> Object.defineProperty(this, '_times', prop);
<add>
<add> // bind the prototype functions to this Console instance
<add> Object.keys(Console.prototype).forEach(function(k) {
<add> this[k] = this[k].bind(this);
<add> }, this);
<add>}
<add>
<add>Console.prototype.log = function() {
<add> this._stdout.write(util.format.apply(this, arguments) + '\n');
<ide> };
<ide>
<ide>
<del>exports.info = exports.log;
<add>Console.prototype.info = Console.prototype.log;
<ide>
<ide>
<del>exports.warn = function() {
<del> process.stderr.write(util.format.apply(this, arguments) + '\n');
<add>Console.prototype.warn = function() {
<add> this._stderr.write(util.format.apply(this, arguments) + '\n');
<ide> };
<ide>
<ide>
<del>exports.error = exports.warn;
<add>Console.prototype.error = Console.prototype.warn;
<ide>
<ide>
<del>exports.dir = function(object) {
<del> process.stdout.write(util.inspect(object) + '\n');
<add>Console.prototype.dir = function(object) {
<add> this._stdout.write(util.inspect(object) + '\n');
<ide> };
<ide>
<ide>
<del>var times = {};
<del>exports.time = function(label) {
<del> times[label] = Date.now();
<add>Console.prototype.time = function(label) {
<add> this._times[label] = Date.now();
<ide> };
<ide>
<ide>
<del>exports.timeEnd = function(label) {
<del> var time = times[label];
<add>Console.prototype.timeEnd = function(label) {
<add> var time = this._times[label];
<ide> if (!time) {
<ide> throw new Error('No such label: ' + label);
<ide> }
<ide> var duration = Date.now() - time;
<del> exports.log('%s: %dms', label, duration);
<add> this.log('%s: %dms', label, duration);
<ide> };
<ide>
<ide>
<del>exports.trace = function(label) {
<add>Console.prototype.trace = function(label) {
<ide> // TODO probably can to do this better with V8's debug object once that is
<ide> // exposed.
<ide> var err = new Error;
<ide> err.name = 'Trace';
<ide> err.message = label || '';
<ide> Error.captureStackTrace(err, arguments.callee);
<del> console.error(err.stack);
<add> this.error(err.stack);
<ide> };
<ide>
<ide>
<del>exports.assert = function(expression) {
<add>Console.prototype.assert = function(expression) {
<ide> if (!expression) {
<ide> var arr = Array.prototype.slice.call(arguments, 1);
<ide> require('assert').ok(false, util.format.apply(this, arr));
<ide> }
<ide> };
<add>
<add>
<add>module.exports = new Console(process.stdout, process.stderr);
<add>module.exports.Console = Console;
<ide><path>test/simple/test-console-instance.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var Stream = require('stream');
<add>var Console = require('console').Console;
<add>var called = false;
<add>
<add>// ensure the Console instance doesn't write to the
<add>// process' "stdout" or "stderr" streams
<add>process.stdout.write = process.stderr.write = function() {
<add> throw new Error('write() should not be called!');
<add>};
<add>
<add>// make sure that the "Console" function exists
<add>assert.equal('function', typeof Console);
<add>
<add>// make sure that the Console constructor throws
<add>// when not given a writable stream instance
<add>assert.throws(function () {
<add> new Console();
<add>}, /Console expects a writable stream/);
<add>
<add>var out = new Stream();
<add>var err = new Stream();
<add>out.writable = err.writable = true;
<add>out.write = err.write = function(d) {};
<add>
<add>var c = new Console(out, err);
<add>
<add>out.write = err.write = function(d) {
<add> assert.equal(d, 'test\n');
<add> called = true;
<add>};
<add>
<add>assert(!called);
<add>c.log('test');
<add>assert(called);
<add>
<add>called = false;
<add>c.error('test');
<add>assert(called);
<add>
<add>out.write = function(d) {
<add> assert.equal('{ foo: 1 }\n', d);
<add> called = true;
<add>};
<add>
<add>called = false;
<add>c.dir({ foo: 1 });
<add>assert(called);
<add>
<add>// ensure that the console functions are bound to the console instance
<add>called = 0;
<add>out.write = function(d) {
<add> called++;
<add> assert.equal(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n');
<add>};
<add>[1, 2, 3].forEach(c.log);
<add>assert.equal(3, called); | 2 |
Java | Java | reduce overhead of blocking first/last/single | 7a5320f85c7000469e3b997f5810573a3967f0f9 | <ide><path>src/main/java/io/reactivex/flowables/BlockingFlowable.java
<ide>
<ide> import org.reactivestreams.*;
<ide>
<del>import io.reactivex.Flowable;
<ide> import io.reactivex.Optional;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.functions.Consumer;
<ide> public boolean isDisposed() {
<ide> }
<ide>
<ide> public Optional<T> firstOption() {
<del> return firstOption(o);
<add> T v = first(o);
<add> return v != null ? Optional.of(v) : Optional.<T>empty();
<ide> }
<ide>
<del> static <T> Optional<T> firstOption(Publisher<? extends T> o) {
<del> final AtomicReference<T> value = new AtomicReference<T>();
<del> final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
<del> final CountDownLatch cdl = new CountDownLatch(1);
<del> final SerialDisposable sd = new SerialDisposable();
<del>
<del> o.subscribe(new Subscriber<T>() {
<del> Subscription s;
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> this.s = s;
<del> sd.replace(Disposables.from(s));
<del> s.request(Long.MAX_VALUE);
<del> }
<del>
<del> @Override
<del> public void onNext(T t) {
<del> s.cancel();
<del> value.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> error.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> cdl.countDown();
<del> }
<del> });
<del>
<del> try {
<del> cdl.await();
<del> } catch (InterruptedException ex) {
<del> sd.dispose();
<del> Exceptions.propagate(ex);
<del> }
<del>
<del> Throwable e = error.get();
<del> if (e != null) {
<del> Exceptions.propagate(e);
<del> }
<del> T v = value.get();
<del> return v != null ? Optional.of(v) : Optional.<T>empty();
<add> static <T> T first(Publisher<? extends T> o) {
<add> BlockingFirstSubscriber<T> s = new BlockingFirstSubscriber<T>();
<add> o.subscribe(s);
<add> return s.blockingGet();
<ide> }
<ide>
<ide> public T first() {
<del> Optional<T> o = firstOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = first(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> throw new NoSuchElementException();
<ide> }
<ide>
<ide> public T first(T defaultValue) {
<del> Optional<T> o = firstOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = first(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> return defaultValue;
<ide> }
<ide>
<ide> public Optional<T> lastOption() {
<del> return lastOption(o);
<add> T v = last(o);
<add> return v != null ? Optional.of(v) : Optional.<T>empty();
<ide> }
<ide>
<del> static <T> Optional<T> lastOption(Publisher<? extends T> o) {
<del> final AtomicReference<T> value = new AtomicReference<T>();
<del> final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
<del> final CountDownLatch cdl = new CountDownLatch(1);
<del> final SerialDisposable sd = new SerialDisposable();
<del>
<del> o.subscribe(new Subscriber<T>() {
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> sd.replace(Disposables.from(s));
<del> s.request(Long.MAX_VALUE);
<del> }
<del>
<del> @Override
<del> public void onNext(T t) {
<del> value.lazySet(t);
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> error.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> cdl.countDown();
<del> }
<del> });
<del>
<del> try {
<del> cdl.await();
<del> } catch (InterruptedException ex) {
<del> sd.dispose();
<del> Exceptions.propagate(ex);
<del> }
<del>
<del> Throwable e = error.get();
<del> if (e != null) {
<del> Exceptions.propagate(e);
<del> }
<del> T v = value.get();
<del> return v != null ? Optional.of(v) : Optional.<T>empty();
<add> static <T> T last(Publisher<? extends T> o) {
<add> BlockingLastSubscriber<T> s = new BlockingLastSubscriber<T>();
<add> o.subscribe(s);
<add> return s.blockingGet();
<ide> }
<ide>
<ide> public T last() {
<del> Optional<T> o = lastOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = last(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> throw new NoSuchElementException();
<ide> }
<ide>
<ide> public T last(T defaultValue) {
<del> Optional<T> o = lastOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = last(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> return defaultValue;
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> public T single() {
<del> Optional<T> o = firstOption(Flowable.fromPublisher(this.o).single());
<del> if (o.isPresent()) {
<del> return o.get();
<del> }
<del> throw new NoSuchElementException();
<add> return first(new FlowableSingle<T>((Publisher<T>)this.o, null));
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> public T single(T defaultValue) {
<del> Optional<T> o = firstOption(Flowable.<T>fromPublisher(this.o).single(defaultValue));
<del> if (o.isPresent()) {
<del> return o.get();
<del> }
<del> return defaultValue;
<add> return first(new FlowableSingle<T>((Publisher<T>)this.o, defaultValue));
<ide> }
<ide>
<ide> public Iterable<T> mostRecent(T initialValue) {
<ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BlockingFirstSubscriber.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.subscribers.flowable;
<add>
<add>/**
<add> * Blocks until the upstream signals its first value or completes.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class BlockingFirstSubscriber<T> extends BlockingSingleSubscriber<T> {
<add>
<add> @Override
<add> public void onNext(T t) {
<add> if (value == null) {
<add> value = t;
<add> s.cancel();
<add> countDown();
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (value == null) {
<add> error = t;
<add> }
<add> countDown();
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BlockingLastSubscriber.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.subscribers.flowable;
<add>
<add>/**
<add> * Blocks until the upstream signals its last value or completes.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class BlockingLastSubscriber<T> extends BlockingSingleSubscriber<T> {
<add>
<add> @Override
<add> public void onNext(T t) {
<add> value = t;
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> value = null;
<add> error = t;
<add> countDown();
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BlockingSingleSubscriber.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.subscribers.flowable;
<add>
<add>import java.util.concurrent.CountDownLatch;
<add>
<add>import org.reactivestreams.*;
<add>
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.util.Exceptions;
<add>
<add>public abstract class BlockingSingleSubscriber<T> extends CountDownLatch
<add>implements Subscriber<T>, Disposable {
<add>
<add> T value;
<add> Throwable error;
<add>
<add> Subscription s;
<add>
<add> volatile boolean cancelled;
<add>
<add> public BlockingSingleSubscriber() {
<add> super(1);
<add> }
<add>
<add> @Override
<add> public final void onSubscribe(Subscription s) {
<add> this.s = s;
<add> if (!cancelled) {
<add> s.request(Long.MAX_VALUE);
<add> if (cancelled) {
<add> s.cancel();
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public final void onComplete() {
<add> countDown();
<add> }
<add>
<add> @Override
<add> public final void dispose() {
<add> cancelled = true;
<add> Subscription s = this.s;
<add> if (s != null) {
<add> s.cancel();
<add> }
<add> }
<add>
<add> @Override
<add> public final boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> /**
<add> * Block until the first value arrives and return it, otherwise
<add> * return null for an empty source and rethrow any exception.
<add> * @return the first value or null if the source is empty
<add> */
<add> public final T blockingGet() {
<add> if (getCount() != 0) {
<add> try {
<add> await();
<add> } catch (InterruptedException ex) {
<add> dispose();
<add> throw Exceptions.propagate(ex);
<add> }
<add> }
<add>
<add> Throwable e = error;
<add> if (e != null) {
<add> Exceptions.propagate(e);
<add> }
<add> return value;
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/subscribers/observable/BlockingFirstObserver.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.subscribers.observable;
<add>
<add>/**
<add> * Blocks until the upstream signals its first value or completes.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class BlockingFirstObserver<T> extends BlockingSingleObserver<T> {
<add>
<add> @Override
<add> public void onNext(T t) {
<add> if (value == null) {
<add> value = t;
<add> d.dispose();
<add> countDown();
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (value == null) {
<add> error = t;
<add> }
<add> countDown();
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/subscribers/observable/BlockingLastObserver.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.subscribers.observable;
<add>
<add>/**
<add> * Blocks until the upstream signals its last value or completes.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class BlockingLastObserver<T> extends BlockingSingleObserver<T> {
<add>
<add> @Override
<add> public void onNext(T t) {
<add> value = t;
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> value = null;
<add> error = t;
<add> countDown();
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/subscribers/observable/BlockingSingleObserver.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.subscribers.observable;
<add>
<add>import java.util.concurrent.CountDownLatch;
<add>
<add>import io.reactivex.Observer;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.util.Exceptions;
<add>
<add>public abstract class BlockingSingleObserver<T> extends CountDownLatch
<add>implements Observer<T>, Disposable {
<add>
<add> T value;
<add> Throwable error;
<add>
<add> Disposable d;
<add>
<add> volatile boolean cancelled;
<add>
<add> public BlockingSingleObserver() {
<add> super(1);
<add> }
<add>
<add> @Override
<add> public final void onSubscribe(Disposable d) {
<add> this.d = d;
<add> if (cancelled) {
<add> d.dispose();
<add> }
<add> }
<add>
<add> @Override
<add> public final void onComplete() {
<add> countDown();
<add> }
<add>
<add> @Override
<add> public final void dispose() {
<add> cancelled = true;
<add> Disposable d = this.d;
<add> if (d != null) {
<add> d.dispose();
<add> }
<add> }
<add>
<add> @Override
<add> public final boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> /**
<add> * Block until the first value arrives and return it, otherwise
<add> * return null for an empty source and rethrow any exception.
<add> * @return the first value or null if the source is empty
<add> */
<add> public final T blockingGet() {
<add> if (getCount() != 0) {
<add> try {
<add> await();
<add> } catch (InterruptedException ex) {
<add> dispose();
<add> throw Exceptions.propagate(ex);
<add> }
<add> }
<add>
<add> Throwable e = error;
<add> if (e != null) {
<add> Exceptions.propagate(e);
<add> }
<add> return value;
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/observables/BlockingObservable.java
<ide> public boolean isDisposed() {
<ide> }
<ide>
<ide> public Optional<T> firstOption() {
<del> return firstOption(o);
<add> T v = first(o);
<add> return v != null ? Optional.of(v) : Optional.<T>empty();
<ide> }
<ide>
<del> static <T> Optional<T> firstOption(Observable<? extends T> o) {
<del> final AtomicReference<T> value = new AtomicReference<T>();
<del> final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
<del> final CountDownLatch cdl = new CountDownLatch(1);
<del> final SerialDisposable sd = new SerialDisposable();
<del>
<del> o.subscribe(new Observer<T>() {
<del> Disposable s;
<del> @Override
<del> public void onSubscribe(Disposable s) {
<del> this.s = s;
<del> sd.replace(s);
<del> }
<del>
<del> @Override
<del> public void onNext(T t) {
<del> s.dispose();
<del> value.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> error.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> cdl.countDown();
<del> }
<del> });
<del>
<del> try {
<del> cdl.await();
<del> } catch (InterruptedException ex) {
<del> sd.dispose();
<del> Exceptions.propagate(ex);
<del> }
<del>
<del> Throwable e = error.get();
<del> if (e != null) {
<del> Exceptions.propagate(e);
<del> }
<del> T v = value.get();
<del> return v != null ? Optional.of(v) : Optional.<T>empty();
<add> static <T> T first(Observable<? extends T> o) {
<add> BlockingFirstObserver<T> s = new BlockingFirstObserver<T>();
<add> o.subscribe(s);
<add> return s.blockingGet();
<ide> }
<ide>
<ide> public T first() {
<del> Optional<T> o = firstOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = first(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> throw new NoSuchElementException();
<ide> }
<ide>
<ide> public T first(T defaultValue) {
<del> Optional<T> o = firstOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = first(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> return defaultValue;
<ide> }
<ide>
<ide> public Optional<T> lastOption() {
<del> return lastOption(o);
<add> T v = last(o);
<add> return v != null ? Optional.of(v) : Optional.<T>empty();
<ide> }
<ide>
<del> static <T> Optional<T> lastOption(Observable<? extends T> o) {
<del> final AtomicReference<T> value = new AtomicReference<T>();
<del> final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
<del> final CountDownLatch cdl = new CountDownLatch(1);
<del> final SerialDisposable sd = new SerialDisposable();
<del>
<del> o.subscribe(new Observer<T>() {
<del> @Override
<del> public void onSubscribe(Disposable s) {
<del> sd.replace(s);
<del> }
<del>
<del> @Override
<del> public void onNext(T t) {
<del> value.lazySet(t);
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> error.lazySet(t);
<del> cdl.countDown();
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> cdl.countDown();
<del> }
<del> });
<del>
<del> try {
<del> cdl.await();
<del> } catch (InterruptedException ex) {
<del> sd.dispose();
<del> Exceptions.propagate(ex);
<del> }
<del>
<del> Throwable e = error.get();
<del> if (e != null) {
<del> Exceptions.propagate(e);
<del> }
<del> T v = value.get();
<del> return v != null ? Optional.of(v) : Optional.<T>empty();
<add> static <T> T last(Observable<? extends T> o) {
<add> BlockingLastObserver<T> s = new BlockingLastObserver<T>();
<add> o.subscribe(s);
<add> return s.blockingGet();
<ide> }
<ide>
<ide> public T last() {
<del> Optional<T> o = lastOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = last(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> throw new NoSuchElementException();
<ide> }
<ide>
<ide> public T last(T defaultValue) {
<del> Optional<T> o = lastOption();
<del> if (o.isPresent()) {
<del> return o.get();
<add> T v = last(o);
<add> if (v != null) {
<add> return v;
<ide> }
<ide> return defaultValue;
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> public T single() {
<del> Optional<T> o = firstOption(this.o.single());
<del> if (o.isPresent()) {
<del> return o.get();
<del> }
<del> throw new NoSuchElementException();
<add> return first(new ObservableSingle<T>((Observable<T>)this.o, null));
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> public T single(T defaultValue) {
<del> @SuppressWarnings("unchecked")
<del> Optional<T> o = firstOption(((Observable<T>)this.o).single(defaultValue));
<del> if (o.isPresent()) {
<del> return o.get();
<del> }
<del> return defaultValue;
<add> return first(new ObservableSingle<T>((Observable<T>)this.o, defaultValue));
<ide> }
<ide>
<ide> public Iterable<T> mostRecent(T initialValue) { | 8 |
Mixed | Javascript | extend autoplay option for greater good | e8e4fe27451c8c45bc389ab7b431032ad0938564 | <ide><path>docs/guides/faq.md
<ide> techs/plugins made available to Video.js. For more information on media formats
<ide>
<ide> When an array of sources is available, Video.js test each source in the order given. For each source, each tech in the [`techOrder`][techorder] will be checked to see if it can play it whether directly or via source handler (such as videojs-contrib-hls). The first match will be chosen.
<ide>
<del>## Q: How to I autoplay the video?
<add>## Q: How do I autoplay a video?
<ide>
<del>Video.js supports the standard html5 `autoplay` attribute on the video element.
<del>It also supports it as an option to Video.js or as a method invocation on the player.
<ide>
<del>```html
<del><video autoplay controls class="video-js">
<del>```
<add>Due to recent changes in autoplay behavior we no longer recommend using the `autoplay` attribute
<add>on the `video` element. It's still supported by Video.js but, many browsers, including Chrome, are changing their
<add>`autoplay` attribute behavior.
<ide>
<del>```js
<del>var player = videojs('my-video', {
<del> autoplay: true
<del>});
<add>Instead we recommend using the `autoplay` option rather than the `autoplay` attribute, for more information on using that.
<add>see the [autoplay option][autoplay-option] in the Video.js options guide.
<ide>
<del>// or
<del>
<del>player.autoplay(true);
<del>```
<add>For more information on the autoplay changes see our blog post: https://blog.videojs.com/autoplay-best-practices-with-video-js/
<ide>
<ide> ### Q: How can I autoplay a video on a mobile device?
<ide>
<ide> Most mobile devices have blocked autoplaying videos until recently.
<ide> For mobile devices that don't support autoplaying, autoplay isn't supported by Video.js.
<ide> For those devices that support autoplaying, like iOS10 and Chrome for Android 53+,
<ide> you must mute the video or have a video without audio tracks to be able to play it.
<del>For example:
<ide>
<del>```html
<del><video muted autoplay playsinline>
<del>```
<add>We do not recommend doing this manually using attributes on the `video` element. Instead, you should pass the
<add>[autoplay option][autoplay-option] with a value of `'any'` or `'muted'`. See the previous link for more information
<add>on using that option.
<ide>
<del>Will make an inline, muted, autoplaying video on an iPhone with iOS10.
<add>> NOTE: At this point, the autoplay attribute and option are NOT a guarantee that your video will autoplay.
<ide>
<ide> ## Q: How can I play RTMP video in Video.js?
<ide>
<ide><path>docs/guides/options.md
<ide> Each of these options is also available as a [standard `<video>` element attribu
<ide>
<ide> ### `autoplay`
<ide>
<del>> Type: `boolean`
<add>> Type: `boolean|string`
<add>> NOTE: At this point, the autoplay attribute and option are NOT a guarantee that your video will autoplay.
<add>> NOTE2: If there is an attribute on the media element the option will be ignored.
<add>> NOTE3: You cannot pass a string value in the attribute, you must pass it in the videojs options
<add>
<add>Instead of using the `autoplay` attribute you should pass an `autoplay` option to the `videojs` function. The following values
<add>are valid:
<add>
<add>* a boolean value of `false`: the same as having no attribute on the video element, won't `autoplay`
<add>* a boolean value of `true`: the same as having attribute on the video element, will use browsers `autoplay`
<add>* a string value of `'muted'`: will mute the video element and then manually call `play()` on `loadstart`. This is likely to work.
<add>* a string value of `'play'`: will call `play()` on `loadstart`, similar to browsers `autoplay`
<add>* a string value of `'any'`: will call `play()` on `loadstart` and if the promise is rejected it will mute the video element then call `play()`.
<ide>
<del>If `true`/present as an attribute, begins playback when the player is ready.
<add>To pass the option
<add>
<add>```js
<add>var player = videojs('my-video', {
<add> autoplay: 'muted'
<add>});
<add>
<add>// or
<add>
<add>player.autoplay('muted');
<add>```
<ide>
<del>> **Note:** As of iOS 10, Apple offers `autoplay` support in Safari. For details, refer to ["New <video> Policies for iOS"][ios-10-updates].
<add>#### More info on autoplay support and changes:
<add>* See our blog post: https://blog.videojs.com/autoplay-best-practices-with-video-js/
<ide>
<ide> ### `controls`
<ide>
<ide><path>src/js/player.js
<ide> class Player extends Component {
<ide> tag.controls = false;
<ide> tag.removeAttribute('controls');
<ide>
<add> // the attribute overrides the option
<add> if (tag.hasAttribute('autoplay')) {
<add> this.options_.autoplay = true;
<add> } else {
<add> // otherwise use the setter to validate and
<add> // set the correct value.
<add> this.autoplay(this.options_.autoplay);
<add> }
<add>
<ide> /*
<ide> * Store the internal state of scrubbing
<ide> *
<ide> class Player extends Component {
<ide> // Turn off API access because we're loading a new tech that might load asynchronously
<ide> this.isReady_ = false;
<ide>
<add> // if autoplay is a string we pass false to the tech
<add> // because the player is going to handle autoplay on `loadstart`
<add> const autoplay = typeof this.autoplay() === 'string' ? false : this.autoplay();
<add>
<ide> // Grab tech-specific options from player options and add source and parent element to use.
<ide> const techOptions = {
<ide> source,
<add> autoplay,
<ide> 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
<ide> 'playerId': this.id(),
<ide> 'techId': `${this.id()}_${titleTechName}_api`,
<del> 'autoplay': this.options_.autoplay,
<ide> 'playsinline': this.options_.playsinline,
<ide> 'preload': this.options_.preload,
<ide> 'loop': this.options_.loop,
<ide> class Player extends Component {
<ide> this.hasStarted(false);
<ide> this.trigger('loadstart');
<ide> }
<add>
<add> // autoplay happens after loadstart for the browser,
<add> // so we mimic that behavior
<add> this.manualAutoplay_(this.autoplay());
<add> }
<add>
<add> /**
<add> * Handle autoplay string values, rather than the typical boolean
<add> * values that should be handled by the tech. Note that this is not
<add> * part of any specification. Valid values and what they do can be
<add> * found on the autoplay getter at Player#autoplay()
<add> */
<add> manualAutoplay_(type) {
<add> if (!this.tech_ || typeof type !== 'string') {
<add> return;
<add> }
<add>
<add> const muted = () => {
<add> const previouslyMuted = this.muted();
<add>
<add> this.muted(true);
<add>
<add> const playPromise = this.play();
<add>
<add> if (!playPromise || !playPromise.then || !playPromise.catch) {
<add> return;
<add> }
<add>
<add> return playPromise.catch((e) => {
<add> // restore old value of muted on failure
<add> this.muted(previouslyMuted);
<add> });
<add> };
<add>
<add> let promise;
<add>
<add> if (type === 'any') {
<add> promise = this.play();
<add>
<add> if (promise && promise.then && promise.catch) {
<add> promise.catch(() => {
<add> return muted();
<add> });
<add> }
<add> } else if (type === 'muted') {
<add> promise = muted();
<add> } else {
<add> promise = this.play();
<add> }
<add>
<add> return promise.then(() => {
<add> this.trigger({type: 'autoplay-success', autoplay: type});
<add> }).catch((e) => {
<add> this.trigger({type: 'autoplay-failure', autoplay: type});
<add> });
<ide> }
<ide>
<ide> /**
<ide> class Player extends Component {
<ide> }
<ide>
<ide> /**
<del> * Get or set the autoplay attribute.
<add> * Get or set the autoplay option. When this is a boolean it will
<add> * modify the attribute on the tech. When this is a string the attribute on
<add> * the tech will be removed and `Player` will handle autoplay on loadstarts.
<ide> *
<del> * @param {boolean} [value]
<del> * - true means that we should autoplay
<del> * - false means that we should not autoplay
<add> * @param {boolean|string} [value]
<add> * - true: autoplay using the browser behavior
<add> * - false: do not autoplay
<add> * - 'play': call play() on every loadstart
<add> * - 'muted': call muted() then play() on every loadstart
<add> * - 'any': call play() on every loadstart. if that fails call muted() then play().
<add> * - *: values other than those listed here will be set `autoplay` to true
<ide> *
<del> * @return {string}
<add> * @return {boolean|string}
<ide> * The current value of autoplay when getting
<ide> */
<ide> autoplay(value) {
<del> if (value !== undefined) {
<del> this.techCall_('setAutoplay', value);
<add> // getter usage
<add> if (value === undefined) {
<add> return this.options_.autoplay || false;
<add> }
<add>
<add> let techAutoplay;
<add>
<add> // if the value is a valid string set it to that
<add> if (typeof value === 'string' && (/(any|play|muted)/).test(value)) {
<ide> this.options_.autoplay = value;
<del> return;
<add> this.manualAutoplay_(value);
<add> techAutoplay = false;
<add>
<add> // any falsy value sets autoplay to false in the browser,
<add> // lets do the same
<add> } else if (!value) {
<add> this.options_.autoplay = false;
<add>
<add> // any other value (ie truthy) sets autoplay to true
<add> } else {
<add> this.options_.autoplay = true;
<add> }
<add>
<add> techAutoplay = techAutoplay || this.options_.autoplay;
<add>
<add> // if we don't have a tech then we do not queue up
<add> // a setAutoplay call on tech ready. We do this because the
<add> // autoplay option will be passed in the constructor and we
<add> // do not need to set it twice
<add> if (this.tech_) {
<add> this.techCall_('setAutoplay', techAutoplay);
<ide> }
<del> return this.techGet_('autoplay', value);
<ide> }
<ide>
<ide> /**
<ide><path>test/unit/autoplay.test.js
<add>/* eslint-env qunit */
<add>import Player from '../../src/js/player.js';
<add>import videojs from '../../src/js/video.js';
<add>import TestHelpers from './test-helpers.js';
<add>import document from 'global/document';
<add>import sinon from 'sinon';
<add>
<add>QUnit.module('autoplay', {
<add> beforeEach() {
<add> this.clock = sinon.useFakeTimers();
<add> // reset players storage
<add> for (const playerId in Player.players) {
<add> if (Player.players[playerId] !== null) {
<add> Player.players[playerId].dispose();
<add> }
<add> delete Player.players[playerId];
<add> }
<add>
<add> const videoTag = TestHelpers.makeTag();
<add> const fixture = document.getElementById('qunit-fixture');
<add>
<add> this.counts = {
<add> play: 0,
<add> muted: 0
<add> };
<add>
<add> fixture.appendChild(videoTag);
<add>
<add> // this promise fake will act right away
<add> // it will also only act on catch calls
<add> this.rejectPromise = {
<add> then(fn) {
<add> return this;
<add> },
<add> catch(fn) {
<add> fn();
<add> return this;
<add> }
<add> };
<add>
<add> this.createPlayer = (options = {}, attributes = {}, playRetval = null) => {
<add> Object.keys(attributes).forEach((a) => {
<add> videoTag.setAttribute(a, attributes[a]);
<add> });
<add>
<add> this.player = videojs(videoTag.id, videojs.mergeOptions({techOrder: ['techFaker']}, options));
<add> const oldMuted = this.player.muted;
<add>
<add> this.player.play = () => {
<add> this.counts.play++;
<add>
<add> if (playRetval) {
<add> return playRetval;
<add> }
<add> };
<add>
<add> this.player.muted = (v) => {
<add>
<add> if (typeof v !== 'undefined') {
<add> this.counts.muted++;
<add> }
<add>
<add> return oldMuted.call(this.player, v);
<add> };
<add>
<add> // we have to trigger ready so that we
<add> // are waiting for loadstart
<add> this.player.tech_.triggerReady();
<add> return this.player;
<add> };
<add> },
<add> afterEach() {
<add> this.clock.restore();
<add> this.player.dispose();
<add> }
<add>});
<add>
<add>QUnit.test('option = false no play/muted', function(assert) {
<add> this.createPlayer({autoplay: false});
<add>
<add> assert.equal(this.player.autoplay(), false, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = true no play/muted', function(assert) {
<add> this.createPlayer({autoplay: true});
<add>
<add> assert.equal(this.player.autoplay(), true, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), true, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "random" no play/muted', function(assert) {
<add> this.createPlayer({autoplay: 'random'});
<add>
<add> assert.equal(this.player.autoplay(), true, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), true, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = null, should be set to false no play/muted', function(assert) {
<add> this.createPlayer({autoplay: null});
<add>
<add> assert.equal(this.player.autoplay(), false, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('options = "play" play, no muted', function(assert) {
<add> this.createPlayer({autoplay: 'play'});
<add>
<add> assert.equal(this.player.autoplay(), 'play', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 1, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "any" play, no muted', function(assert) {
<add> this.createPlayer({autoplay: 'any'});
<add>
<add> assert.equal(this.player.autoplay(), 'any', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 1, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "muted" play and muted', function(assert) {
<add> this.createPlayer({autoplay: 'muted'});
<add>
<add> assert.equal(this.player.autoplay(), 'muted', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 1, 'play count');
<add> assert.equal(this.counts.muted, 1, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 2, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "play" play, no muted, rejection ignored', function(assert) {
<add> this.createPlayer({autoplay: 'play'}, {}, this.rejectPromise);
<add>
<add> assert.equal(this.player.autoplay(), 'play', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 1, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "any" play, no muted, rejection leads to muted then play', function(assert) {
<add> this.createPlayer({autoplay: 'any'}, {}, this.rejectPromise);
<add>
<add> assert.equal(this.player.autoplay(), 'any', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> // muted called twice here, as muted is value is restored on failure.
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 2, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 4, 'play count');
<add> assert.equal(this.counts.muted, 4, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "muted" play and muted, rejection ignored', function(assert) {
<add> this.createPlayer({autoplay: 'muted'}, {}, this.rejectPromise);
<add>
<add> assert.equal(this.player.autoplay(), 'muted', 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), false, 'tech.autoplay getter');
<add>
<add> // muted called twice here, as muted is value is restored on failure.
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 1, 'play count');
<add> assert.equal(this.counts.muted, 2, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 2, 'play count');
<add> assert.equal(this.counts.muted, 4, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "muted", attr = true, play and muted', function(assert) {
<add> this.createPlayer({autoplay: 'muted'}, {autoplay: true});
<add>
<add> assert.equal(this.player.autoplay(), true, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), true, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "play", attr = true, play only', function(assert) {
<add> this.createPlayer({autoplay: 'play'}, {autoplay: true});
<add>
<add> assert.equal(this.player.autoplay(), true, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), true, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<add>
<add>QUnit.test('option = "any", attr = true, play only', function(assert) {
<add> this.createPlayer({autoplay: 'any'}, {autoplay: true});
<add>
<add> assert.equal(this.player.autoplay(), true, 'player.autoplay getter');
<add> assert.equal(this.player.tech_.autoplay(), true, 'tech.autoplay getter');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>
<add> this.player.tech_.trigger('loadstart');
<add> assert.equal(this.counts.play, 0, 'play count');
<add> assert.equal(this.counts.muted, 0, 'muted count');
<add>});
<ide><path>test/unit/tech/tech-faker.js
<ide> class TechFaker extends Tech {
<ide>
<ide> setMuted() {}
<ide>
<del> setAutoplay() {}
<add> setAutoplay(v) {
<add> if (!v) {
<add> this.options_.autoplay = false;
<add> }
<add>
<add> this.options_.autoplay = true;
<add> }
<ide>
<ide> currentTime() {
<ide> return 0;
<ide> class TechFaker extends Tech {
<ide> return false;
<ide> }
<ide> autoplay() {
<del> return false;
<add> return this.options_.autoplay || false;
<ide> }
<ide> pause() {
<ide> return false; | 5 |
PHP | PHP | add last method | 4289e6ccb3ace1beb240390bacb6f0dbca7b2cd7 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function first()
<ide> return count($this->items) > 0 ? reset($this->items) : null;
<ide> }
<ide>
<add> /**
<add> * Get the last item from the collection
<add> *
<add> * @return mixed|null
<add> */
<add> public function last()
<add> {
<add> return count($this->items) > 0 ? end($this->items) : null;
<add> }
<add>
<ide> /**
<ide> * Execute a callback over each item.
<ide> * | 1 |
Text | Text | add metadata to report docs | f40778e97a1a324a01e266ed82d91c272715a69a | <ide><path>doc/api/report.md
<ide> # Diagnostic Report
<ide>
<add><!--introduced_in=v11.8.0-->
<add><!-- type=misc -->
<add>
<add>> Stability: 1 - Experimental
<add>
<add><!-- name=report -->
<add>
<ide> Delivers a JSON-formatted diagnostic summary, written to a file.
<ide>
<ide> The report is intended for development, test and production use, to capture | 1 |
Javascript | Javascript | add test case | 22cd80e73b2ebef3e9526f97fdb7a60e92a7d7c1 | <ide><path>test/configCases/plugins/define-plugin/index.js
<ide> it("should evaluate composed expressions (issue 5100)", function() {
<ide> } else {
<ide> require("fail");
<ide> }
<del>})
<add>});
<add>
<add>it("should follow renamings in var (issue 5215)", function() {
<add> var _process$env = process.env,
<add> TEST = _process$env.TEST,
<add> DEFINED_NESTED_KEY = _process$env.DEFINED_NESTED_KEY;
<add> TEST.should.be.eql("test");
<add> DEFINED_NESTED_KEY.should.be.eql(5);
<add>}); | 1 |
PHP | PHP | fix default values as documented | 51865846754a1bc0423c4b46a3c054c5779a7b01 | <ide><path>src/Network/Session.php
<ide> class Session
<ide> *
<ide> * @var bool
<ide> */
<del> protected $_started;
<add> protected $_started = false;
<ide>
<ide> /**
<ide> * The time in seconds the session will be valid for
<ide> *
<ide> * @var int
<ide> */
<del> protected $_lifetime;
<add> protected $_lifetime = 0;
<ide>
<ide> /**
<ide> * Whether this session is running under a CLI environment | 1 |
Javascript | Javascript | update example to use a module | f3567b257cb8709ee08250d28981e257bb6672bf | <ide><path>src/ng/window.js
<ide> * expression.
<ide> *
<ide> * @example
<del> <example>
<add> <example module="windowExample">
<ide> <file name="index.html">
<ide> <script>
<del> function Ctrl($scope, $window) {
<del> $scope.greeting = 'Hello, World!';
<del> $scope.doGreeting = function(greeting) {
<add> angular.module('windowExample', [])
<add> .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
<add> $scope.greeting = 'Hello, World!';
<add> $scope.doGreeting = function(greeting) {
<ide> $window.alert(greeting);
<del> };
<del> }
<add> };
<add> }]);
<ide> </script>
<del> <div ng-controller="Ctrl">
<add> <div ng-controller="ExampleController">
<ide> <input type="text" ng-model="greeting" />
<ide> <button ng-click="doGreeting(greeting)">ALERT</button>
<ide> </div> | 1 |
Javascript | Javascript | improve performance to instantiate errors | afce91219359654b44df29e6ec1b730e2a73a919 | <ide><path>lib/internal/assert/assertion_error.js
<ide> class AssertionError extends Error {
<ide> stackStartFn
<ide> } = options;
<ide>
<add> const limit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add>
<ide> if (message != null) {
<ide> super(String(message));
<ide> } else {
<ide> class AssertionError extends Error {
<ide> }
<ide> }
<ide>
<add> Error.stackTraceLimit = limit;
<add>
<ide> this.generatedMessage = !message;
<ide> Object.defineProperty(this, 'name', {
<ide> value: 'AssertionError [ERR_ASSERTION]', | 1 |
PHP | PHP | apply fixes from styleci | f1d20b859edb2b2868871e25bad21541b442b705 | <ide><path>src/Illuminate/Session/Store.php
<ide> protected function prepareErrorBagForSerialization()
<ide> foreach ($this->attributes['errors']->getBags() as $key => $value) {
<ide> $errors[$key] = [
<ide> 'format' => $value->getFormat(),
<del> 'messages' => $value->getMessages()
<add> 'messages' => $value->getMessages(),
<ide> ];
<ide> }
<ide> | 1 |
Javascript | Javascript | add type support to maint-template and template | 0fcd5e5775d256d7793f3a42063afecbf6b76325 | <ide><path>lib/MainTemplate.js
<ide> const {
<ide> } = require("tapable");
<ide> const Template = require("./Template");
<ide>
<add>/** @typedef {import("tapable").Hook} Hook */
<add>/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
<add>
<ide> // require function shortcuts:
<ide> // __webpack_require__.s = the module id of the entry point
<ide> // __webpack_require__.c = the module cache
<ide> const Template = require("./Template");
<ide> // __webpack_require__.nc = the script nonce
<ide>
<ide> module.exports = class MainTemplate extends Tapable {
<add> /**
<add> *
<add> * @param {any=} outputOptions output options for the MainTemplate
<add> */
<ide> constructor(outputOptions) {
<ide> super();
<add> /** @type {any?} */
<ide> this.outputOptions = outputOptions || {};
<add> /** @type {{[hookName: string]: Hook}} */
<ide> this.hooks = {
<ide> renderManifest: new SyncWaterfallHook(["result", "options"]),
<ide> modules: new SyncWaterfallHook([
<ide> module.exports = class MainTemplate extends Tapable {
<ide> hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"])
<ide> };
<ide> this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => {
<add> /** @type {string[]} */
<ide> const buf = [];
<ide> if (chunk.entryModule) {
<ide> buf.push("// Load entry module and return exports");
<ide> module.exports = class MainTemplate extends Tapable {
<ide> this.requireFn = "__webpack_require__";
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {any} options render manifest options
<add> * @returns {any[]} returns render nanifest
<add> */
<ide> getRenderManifest(options) {
<ide> const result = [];
<ide>
<ide> module.exports = class MainTemplate extends Tapable {
<ide> return result;
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {string} hash hash to be used for render call
<add> * @param {any} chunk Chunk instance
<add> * @param {any} moduleTemplate ModuleTemplate instance for render
<add> * @param {any} dependencyTemplates DependencyTemplate[]s
<add> * @return {ConcatSource} the newly generated source from rendering
<add> */
<ide> render(hash, chunk, moduleTemplate, dependencyTemplates) {
<ide> const buf = [];
<ide> buf.push(
<ide> module.exports = class MainTemplate extends Tapable {
<ide> return new ConcatSource(source, ";");
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {string} hash hash for render fn
<add> * @param {any} chunk Chunk instance for require
<add> * @param {(number|string)=} varModuleId module id
<add> * @return {any} the moduleRequire hook call return signature
<add> */
<ide> renderRequireFunctionForModule(hash, chunk, varModuleId) {
<ide> return this.hooks.moduleRequire.call(
<ide> this.requireFn,
<ide> module.exports = class MainTemplate extends Tapable {
<ide> );
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {string} hash hash for render add fn
<add> * @param {any} chunk Chunk instance for require add fn
<add> * @param {(string|number)=} varModuleId module id
<add> * @param {any} varModule Module instance
<add> * @return {any} renderAddModule call
<add> */
<ide> renderAddModule(hash, chunk, varModuleId, varModule) {
<ide> return this.hooks.addModule.call(
<ide> `modules[${varModuleId}] = ${varModule};`,
<ide> module.exports = class MainTemplate extends Tapable {
<ide> );
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {string} hash string hash
<add> * @param {number} length length
<add> * @return {any} call hook return
<add> */
<ide> renderCurrentHashCode(hash, length) {
<ide> length = length || Infinity;
<ide> return this.hooks.currentHash.call(
<ide> module.exports = class MainTemplate extends Tapable {
<ide> );
<ide> }
<ide>
<add> /**
<add> *
<add> * @param {object} options get public path options
<add> * @return {any} hook call
<add> */
<ide> getPublicPath(options) {
<ide> return this.hooks.assetPath.call(
<ide> this.outputOptions.publicPath || "",
<ide><path>lib/Template.js
<ide> class Template {
<ide>
<ide> /**
<ide> *
<del> * @param {string} str string to convert to identity
<add> * @param {string | string[]} str string to convert to identity
<ide> * @return {string} converted identity
<ide> */
<ide> static indent(str) { | 2 |
Javascript | Javascript | fix recent webxr changes | b63ffffb6bb7f2fde9160d775b25d288926f7cf5 | <ide><path>src/renderers/webxr/WebXRManager.js
<ide> import {
<ide> DepthStencilFormat,
<ide> RGBAFormat,
<ide> RGBFormat,
<add> sRGBEncoding,
<ide> UnsignedByteType,
<ide> UnsignedShortType,
<del> UnsignedInt248Type,
<add> UnsignedInt248Type
<ide> } from '../../constants.js';
<ide>
<ide> class WebXRManager extends EventDispatcher {
<ide> class WebXRManager extends EventDispatcher {
<ide>
<ide> if ( attributes.depth ) {
<ide>
<del> glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT16;
<add> glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
<ide> depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
<ide> depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
<ide>
<ide> class WebXRManager extends EventDispatcher {
<ide> stencilBuffer: attributes.stencil,
<ide> ignoreDepth: glProjLayer.ignoreDepthValues,
<ide> useRenderToTexture: hasMultisampledRenderToTexture,
<add> encoding: sRGBEncoding
<ide> } );
<ide>
<ide> } else {
<ide> class WebXRManager extends EventDispatcher {
<ide> depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
<ide> stencilBuffer: attributes.stencil,
<ide> ignoreDepth: glProjLayer.ignoreDepthValues,
<add> encoding: sRGBEncoding
<ide> } );
<ide>
<ide> } | 1 |
Python | Python | fix sequence bug | 4b74fc5418944c9f449eb88ed4b40ada280fa5ca | <ide><path>keras/engine/training.py
<ide> def generate_arrays_from_file(path):
<ide> val_enqueuer.start(workers=workers, max_queue_size=max_queue_size)
<ide> validation_generator = val_enqueuer.get()
<ide> else:
<del> validation_generator = validation_data
<add> if isinstance(validation_data, Sequence):
<add> validation_generator = iter(validation_data)
<add> else:
<add> validation_generator = validation_data
<ide> else:
<ide> if len(validation_data) == 2:
<ide> val_x, val_y = validation_data
<ide> def generate_arrays_from_file(path):
<ide> enqueuer.start(workers=workers, max_queue_size=max_queue_size)
<ide> output_generator = enqueuer.get()
<ide> else:
<del> output_generator = generator
<add> if is_sequence:
<add> output_generator = iter(generator)
<add> else:
<add> output_generator = generator
<ide>
<ide> callback_model.stop_training = False
<ide> # Construct epoch logs.
<ide> def evaluate_generator(self, generator, steps=None,
<ide> enqueuer.start(workers=workers, max_queue_size=max_queue_size)
<ide> output_generator = enqueuer.get()
<ide> else:
<del> output_generator = generator
<add> if is_sequence:
<add> output_generator = iter(generator)
<add> else:
<add> output_generator = generator
<ide>
<ide> while steps_done < steps:
<ide> generator_output = next(output_generator)
<ide> def predict_generator(self, generator, steps=None,
<ide> enqueuer.start(workers=workers, max_queue_size=max_queue_size)
<ide> output_generator = enqueuer.get()
<ide> else:
<del> output_generator = generator
<add> if is_sequence:
<add> output_generator = iter(generator)
<add> else:
<add> output_generator = generator
<ide>
<ide> if verbose == 1:
<ide> progbar = Progbar(target=steps)
<ide><path>keras/utils/data_utils.py
<ide> def on_epoch_end(self):
<ide> """
<ide> pass
<ide>
<add> def __iter__(self):
<add> """Create an infinite generator that iterate over the Sequence."""
<add> while True:
<add> for item in (self[i] for i in range(len(self))):
<add> yield item
<add>
<ide>
<ide> # Global variables to be shared across processes
<ide> _SHARED_SEQUENCES = {}
<ide><path>tests/test_multiprocessing.py
<ide> from keras.models import Sequential
<ide> from keras.layers.core import Dense
<ide> from keras.utils.test_utils import keras_test
<add>from keras.utils import Sequence
<ide>
<ide> STEPS_PER_EPOCH = 100
<ide> STEPS = 100
<ide> WORKERS = 4
<ide>
<ide>
<add>class DummySequence(Sequence):
<add> def __getitem__(self, idx):
<add> return np.zeros([10, 2]), np.ones([10])
<add>
<add> def __len__(self):
<add> return 10
<add>
<add>
<ide> @pytest.fixture
<ide> def in_tmpdir(tmpdir):
<ide> """Runs a function in a temporary directory.
<ide> def custom_generator(use_weights=False):
<ide> workers=0,
<ide> use_multiprocessing=False)
<ide>
<add> # - For Sequence
<add> model.fit_generator(DummySequence(),
<add> steps_per_epoch=STEPS_PER_EPOCH,
<add> validation_data=custom_generator(True),
<add> validation_steps=1,
<add> max_queue_size=10,
<add> workers=0,
<add> use_multiprocessing=True)
<add> model.fit_generator(DummySequence(),
<add> steps_per_epoch=STEPS_PER_EPOCH,
<add> validation_data=custom_generator(True),
<add> validation_steps=1,
<add> max_queue_size=10,
<add> workers=0,
<add> use_multiprocessing=False)
<add>
<ide> # Test invalid use cases
<ide> def invalid_generator():
<ide> while True: | 3 |
Python | Python | put nested_iter tests within a class | e6412f652aac1eebffbab839a554a988ff7e5982 | <ide><path>numpy/core/tests/test_nditer.py
<ide> def test_iter_no_broadcast():
<ide> assert_raises(ValueError, nditer, [a, b, c], [],
<ide> [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])
<ide>
<del>def test_iter_nested_iters_basic():
<del> # Test nested iteration basic usage
<del> a = arange(12).reshape(2, 3, 2)
<ide>
<del> i, j = np.nested_iters(a, [[0], [1, 2]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<add>class TestIterNested(object):
<ide>
<del> i, j = np.nested_iters(a, [[0, 1], [2]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<add> def test_basic(self):
<add> # Test nested iteration basic usage
<add> a = arange(12).reshape(2, 3, 2)
<ide>
<del> i, j = np.nested_iters(a, [[0, 2], [1]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<add> i, j = np.nested_iters(a, [[0], [1, 2]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<ide>
<del>def test_iter_nested_iters_reorder():
<del> # Test nested iteration basic usage
<del> a = arange(12).reshape(2, 3, 2)
<add> i, j = np.nested_iters(a, [[0, 1], [2]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<ide>
<del> # In 'K' order (default), it gets reordered
<del> i, j = np.nested_iters(a, [[0], [2, 1]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<add> i, j = np.nested_iters(a, [[0, 2], [1]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[1, 0], [2]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<add> def test_reorder(self):
<add> # Test nested iteration basic usage
<add> a = arange(12).reshape(2, 3, 2)
<ide>
<del> i, j = np.nested_iters(a, [[2, 0], [1]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<add> # In 'K' order (default), it gets reordered
<add> i, j = np.nested_iters(a, [[0], [2, 1]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<ide>
<del> # In 'C' order, it doesn't
<del> i, j = np.nested_iters(a, [[0], [2, 1]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]])
<add> i, j = np.nested_iters(a, [[1, 0], [2]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[1, 0], [2]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]])
<add> i, j = np.nested_iters(a, [[2, 0], [1]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[2, 0], [1]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]])
<add> # In 'C' order, it doesn't
<add> i, j = np.nested_iters(a, [[0], [2, 1]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]])
<ide>
<del>def test_iter_nested_iters_flip_axes():
<del> # Test nested iteration with negative axes
<del> a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1]
<add> i, j = np.nested_iters(a, [[1, 0], [2]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]])
<ide>
<del> # In 'K' order (default), the axes all get flipped
<del> i, j = np.nested_iters(a, [[0], [1, 2]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<add> i, j = np.nested_iters(a, [[2, 0], [1]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[0, 1], [2]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<add> def test_flip_axes(self):
<add> # Test nested iteration with negative axes
<add> a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1]
<ide>
<del> i, j = np.nested_iters(a, [[0, 2], [1]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<add> # In 'K' order (default), the axes all get flipped
<add> i, j = np.nested_iters(a, [[0], [1, 2]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
<ide>
<del> # In 'C' order, flipping axes is disabled
<del> i, j = np.nested_iters(a, [[0], [1, 2]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]])
<add> i, j = np.nested_iters(a, [[0, 1], [2]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[0, 1], [2]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]])
<add> i, j = np.nested_iters(a, [[0, 2], [1]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
<ide>
<del> i, j = np.nested_iters(a, [[0, 2], [1]], order='C')
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]])
<add> # In 'C' order, flipping axes is disabled
<add> i, j = np.nested_iters(a, [[0], [1, 2]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]])
<ide>
<del>def test_iter_nested_iters_broadcast():
<del> # Test nested iteration with broadcasting
<del> a = arange(2).reshape(2, 1)
<del> b = arange(3).reshape(1, 3)
<add> i, j = np.nested_iters(a, [[0, 1], [2]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]])
<ide>
<del> i, j = np.nested_iters([a, b], [[0], [1]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]])
<add> i, j = np.nested_iters(a, [[0, 2], [1]], order='C')
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]])
<ide>
<del> i, j = np.nested_iters([a, b], [[1], [0]])
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]])
<add> def test_broadcast(self):
<add> # Test nested iteration with broadcasting
<add> a = arange(2).reshape(2, 1)
<add> b = arange(3).reshape(1, 3)
<ide>
<del>def test_iter_nested_iters_dtype_copy():
<del> # Test nested iteration with a copy to change dtype
<add> i, j = np.nested_iters([a, b], [[0], [1]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]])
<ide>
<del> # copy
<del> a = arange(6, dtype='i4').reshape(2, 3)
<del> i, j = np.nested_iters(a, [[0], [1]],
<del> op_flags=['readonly', 'copy'],
<del> op_dtypes='f8')
<del> assert_equal(j[0].dtype, np.dtype('f8'))
<del> vals = []
<del> for x in i:
<del> vals.append([y for y in j])
<del> assert_equal(vals, [[0, 1, 2], [3, 4, 5]])
<del> vals = None
<del>
<del> # updateifcopy
<del> a = arange(6, dtype='f4').reshape(2, 3)
<del> i, j = np.nested_iters(a, [[0], [1]],
<del> op_flags=['readwrite', 'updateifcopy'],
<del> casting='same_kind',
<del> op_dtypes='f8')
<del> assert_equal(j[0].dtype, np.dtype('f8'))
<del> for x in i:
<del> for y in j:
<del> y[...] += 1
<del> assert_equal(a, [[0, 1, 2], [3, 4, 5]])
<del> i, j, x, y = (None,)*4 # force the updateifcopy
<del> assert_equal(a, [[1, 2, 3], [4, 5, 6]])
<del>
<del>def test_iter_nested_iters_dtype_buffered():
<del> # Test nested iteration with buffering to change dtype
<del>
<del> a = arange(6, dtype='f4').reshape(2, 3)
<del> i, j = np.nested_iters(a, [[0], [1]],
<del> flags=['buffered'],
<del> op_flags=['readwrite'],
<del> casting='same_kind',
<del> op_dtypes='f8')
<del> assert_equal(j[0].dtype, np.dtype('f8'))
<del> for x in i:
<del> for y in j:
<del> y[...] += 1
<del> assert_equal(a, [[1, 2, 3], [4, 5, 6]])
<add> i, j = np.nested_iters([a, b], [[1], [0]])
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]])
<add>
<add> def test_dtype_copy(self):
<add> # Test nested iteration with a copy to change dtype
<add>
<add> # copy
<add> a = arange(6, dtype='i4').reshape(2, 3)
<add> i, j = np.nested_iters(a, [[0], [1]],
<add> op_flags=['readonly', 'copy'],
<add> op_dtypes='f8')
<add> assert_equal(j[0].dtype, np.dtype('f8'))
<add> vals = []
<add> for x in i:
<add> vals.append([y for y in j])
<add> assert_equal(vals, [[0, 1, 2], [3, 4, 5]])
<add> vals = None
<add>
<add> # updateifcopy
<add> a = arange(6, dtype='f4').reshape(2, 3)
<add> i, j = np.nested_iters(a, [[0], [1]],
<add> op_flags=['readwrite', 'updateifcopy'],
<add> casting='same_kind',
<add> op_dtypes='f8')
<add> assert_equal(j[0].dtype, np.dtype('f8'))
<add> for x in i:
<add> for y in j:
<add> y[...] += 1
<add> assert_equal(a, [[0, 1, 2], [3, 4, 5]])
<add> i, j, x, y = (None,)*4 # force the updateifcopy
<add> assert_equal(a, [[1, 2, 3], [4, 5, 6]])
<add>
<add> def test_dtype_buffered(self):
<add> # Test nested iteration with buffering to change dtype
<add>
<add> a = arange(6, dtype='f4').reshape(2, 3)
<add> i, j = np.nested_iters(a, [[0], [1]],
<add> flags=['buffered'],
<add> op_flags=['readwrite'],
<add> casting='same_kind',
<add> op_dtypes='f8')
<add> assert_equal(j[0].dtype, np.dtype('f8'))
<add> for x in i:
<add> for y in j:
<add> y[...] += 1
<add> assert_equal(a, [[1, 2, 3], [4, 5, 6]])
<ide>
<ide> def test_iter_reduction_error():
<ide> | 1 |
PHP | PHP | fix each() on belongstomany relationships | 19e7b7b931544f89c875b1e94968ce70c7937533 | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function chunk($count, callable $callback)
<ide> });
<ide> }
<ide>
<add> /**
<add> * Execute a callback over each item while chunking.
<add> *
<add> * @param callable $callback
<add> * @param int $count
<add> * @return bool
<add> */
<add> public function each(callable $callback, $count = 1000)
<add> {
<add> return $this->chunk($count, function ($results) use ($callback) {
<add> foreach ($results as $key => $value) {
<add> if ($callback($value, $key) === false) {
<add> return false;
<add> }
<add> }
<add> });
<add> }
<add>
<ide> /**
<ide> * Hydrate the pivot table relationship on the models.
<ide> *
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunke
<ide> });
<ide> }
<ide>
<add> public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverEachRequest()
<add> {
<add> $user = EloquentTestUser::create(['email' => '[email protected]']);
<add> $friend = $user->friends()->create(['email' => '[email protected]']);
<add>
<add> EloquentTestUser::first()->friends()->each(function ($result) use ($user, $friend) {
<add> $this->assertEquals('[email protected]', $result->email);
<add> $this->assertEquals($user->id, $result->pivot->user_id);
<add> $this->assertEquals($friend->id, $result->pivot->friend_id);
<add> });
<add> }
<add>
<ide> public function testBasicHasManyEagerLoading()
<ide> {
<ide> $user = EloquentTestUser::create(['email' => '[email protected]']); | 2 |
Python | Python | add __repr__ for executors | 6410f0710613189c2086b4d3af4b26ba543f306a | <ide><path>airflow/executors/base_executor.py
<ide> def __init__(self, parallelism: int = PARALLELISM):
<ide> self.running: Set[TaskInstanceKey] = set()
<ide> self.event_buffer: Dict[TaskInstanceKey, EventBufferValueType] = {}
<ide>
<add> def __repr__(self):
<add> return f"{self.__class__.__name__}(parallelism={self.parallelism})"
<add>
<ide> def start(self): # pragma: no cover
<ide> """Executors may need to get things started."""
<ide> | 1 |
PHP | PHP | add helper methods for events | 638b63a7471d451251b0cd7a3914677d2715575d | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function getScannedRoutesPath()
<ide> return $this['path.storage'].'/framework/routes.scanned.php';
<ide> }
<ide>
<add> /**
<add> * Determine if the application events have been scanned.
<add> *
<add> * @return bool
<add> */
<add> public function eventsAreScanned()
<add> {
<add> return $this['files']->exists($this->getScannedEventsPath());
<add> }
<add>
<add> /**
<add> * Get the path to the scanned events file.
<add> *
<add> * @return string
<add> */
<add> public function getScannedEventsPath()
<add> {
<add> return $this['path.storage'].'/framework/events.scanned.php';
<add> }
<add>
<ide> /**
<ide> * Register the application stack.
<ide> *
<ide><path>src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php
<ide> class EventServiceProvider extends ServiceProvider {
<ide> */
<ide> public function boot(DispatcherContract $events)
<ide> {
<del> if (file_exists($scanned = $this->app['path.storage'].'/framework/events.scanned.php'))
<add> if ($this->app->eventsAreScanned())
<ide> {
<del> require $scanned;
<add> require $this->app->getScannedEventsPath();
<ide> }
<ide>
<ide> foreach ($this->listen as $event => $listeners) | 2 |
Javascript | Javascript | fix 4.0 build errors | 362514c10b3b6dd23a9fc7744a59bf342d901179 | <ide><path>lib/AbstractMethodError.js
<ide> function Message() {
<ide> this.stack = undefined;
<ide> Error.captureStackTrace(this);
<ide> /** @type {RegExpMatchArray} */
<del> const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP);
<add> const match = /** @type {*} */ (this.stack)
<add> .split("\n")[3]
<add> .match(CURRENT_METHOD_REGEXP);
<ide>
<ide> this.message = match && match[1] ? createMessage(match[1]) : createMessage();
<ide> }
<ide><path>lib/ContextModule.js
<ide> const makeSerializable = require("./util/makeSerializable");
<ide>
<ide> /**
<ide> * @callback ResolveDependenciesCallback
<del> * @param {Error=} err
<add> * @param {WebpackError=} err
<ide> * @param {ContextElementDependency[]} dependencies
<ide> */
<ide>
<ide><path>lib/MainTemplate.js
<ide> const getJavascriptModulesPlugin = memorize(() =>
<ide> class MainTemplate {
<ide> /**
<ide> *
<del> * @param {TODO=} outputOptions output options for the MainTemplate
<add> * @param {TODO|undefined} outputOptions output options for the MainTemplate
<ide> * @param {Compilation} compilation the compilation
<ide> */
<ide> constructor(outputOptions, compilation) {
<del> /** @type {TODO?} */
<add> /** @type {TODO|undefined} */
<ide> this._outputOptions = outputOptions || {};
<ide> this.hooks = Object.freeze({
<ide> renderManifest: {
<ide><path>lib/ModuleGraphConnection.js
<ide>
<ide> class ModuleGraphConnection {
<ide> /**
<del> * @param {Module=} originModule the referencing module
<del> * @param {Dependency=} dependency the referencing dependency
<add> * @param {Module|undefined} originModule the referencing module
<add> * @param {Dependency|undefined} dependency the referencing dependency
<ide> * @param {Module} module the referenced module
<ide> * @param {string=} explanation some extra detail
<ide> * @param {boolean=} weak the reference is weak
<ide><path>lib/config/normalization.js
<ide> const normalizeEcmaVersion = require("../util/normalizeEcmaVersion");
<ide> /**
<ide> * @template T
<ide> * @template R
<del> * @param {T=} value value or not
<add> * @param {T|undefined} value value or not
<ide> * @param {function(T): R} fn nested handler
<ide> * @returns {R} result value
<ide> */
<ide> const nestedConfig = (value, fn) =>
<ide> /**
<ide> * @template T
<ide> * @template R
<del> * @param {T=} value value or not
<add> * @param {T|undefined} value value or not
<ide> * @param {function(T): R} fn nested handler
<del> * @returns {R=} result value
<add> * @returns {R|undefined} result value
<ide> */
<ide> const optionalNestedConfig = (value, fn) =>
<ide> value === undefined ? undefined : fn(value);
<ide>
<ide> /**
<ide> * @template T
<ide> * @template R
<del> * @param {T[]=} value array or not
<add> * @param {T[]|undefined} value array or not
<ide> * @param {function(T[]): R[]} fn nested handler
<del> * @returns {R[]=} cloned value
<add> * @returns {R[]|undefined} cloned value
<ide> */
<ide> const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([]));
<ide>
<ide> /**
<ide> * @template T
<ide> * @template R
<del> * @param {T[]=} value array or not
<add> * @param {T[]|undefined} value array or not
<ide> * @param {function(T[]): R[]} fn nested handler
<del> * @returns {R[]=} cloned value
<add> * @returns {R[]|undefined} cloned value
<ide> */
<ide> const optionalNestedArray = (value, fn) =>
<ide> Array.isArray(value) ? fn(value) : undefined;
<ide><path>lib/library/UmdLibraryPlugin.js
<ide> const accessorToObjectAccess = accessor => {
<ide> };
<ide>
<ide> /**
<del> * @param {string=} base the path prefix
<add> * @param {string|undefined} base the path prefix
<ide> * @param {string|string[]} accessor the accessor
<ide> * @param {string=} joinWith the element separator
<ide> * @returns {string} the path
<ide><path>lib/util/fs.js
<ide> const path = require("path");
<ide>
<ide> /**
<ide> *
<del> * @param {(InputFileSystem|OutputFileSystem)=} fs a file system
<add> * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system
<ide> * @param {string} rootPath the root path
<ide> * @param {string} targetPath the target path
<ide> * @returns {string} location of targetPath relative to rootPath
<ide> const relative = (fs, rootPath, targetPath) => {
<ide> exports.relative = relative;
<ide>
<ide> /**
<del> * @param {(InputFileSystem|OutputFileSystem)=} fs a file system
<add> * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system
<ide> * @param {string} rootPath a path
<ide> * @param {string} filename a filename
<ide> * @returns {string} the joined path
<ide> const join = (fs, rootPath, filename) => {
<ide> exports.join = join;
<ide>
<ide> /**
<del> * @param {(InputFileSystem|OutputFileSystem)=} fs a file system
<add> * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system
<ide> * @param {string} absPath an absolute path
<ide> * @returns {string} the parent directory of the absolute path
<ide> */ | 7 |
Python | Python | add missing types | ef7206cd098457aef50aecde813b34f9beb76bc6 | <ide><path>libcloud/storage/types.py
<ide> class Provider(object):
<ide> S3_RGW = "s3_rgw"
<ide> S3_RGW_OUTSCALE = "s3_rgw_outscale"
<ide> MINIO = "minio"
<add> SCALEWAY = "scaleway"
<add> SCALEWAY_FR_PAR = "scaleway_fr_par"
<add> SCALEWAY_NL_AMS = "scaleway_nl_ams"
<add> SCALEWAY_PL_WAW = "scaleway_pl_waw"
<ide>
<ide> # Deperecated
<ide> CLOUDFILES_US = "cloudfiles_us" | 1 |
Javascript | Javascript | adjust failing assertions | 4afbe9103a2a2fee6518ad80c91f8cf80122fc37 | <ide><path>packages/@ember/-internals/container/tests/container_test.js
<ide> moduleFor(
<ide>
<ide> assert.throws(() => {
<ide> container.lookup('service:foo');
<del> }, /Can not call `.lookup` after the owner has been destroyed/);
<add> }, /Cannot call `.lookup` after the owner has been destroyed/);
<ide> }
<ide>
<ide> [`@test assert when calling factoryFor after destroy on a container`](assert) {
<ide> moduleFor(
<ide>
<ide> assert.throws(() => {
<ide> container.factoryFor('service:foo');
<del> }, /Can not call `.factoryFor` after the owner has been destroyed/);
<add> }, /Cannot call `.factoryFor` after the owner has been destroyed/);
<ide> }
<ide>
<ide> // this is skipped until templates and the glimmer environment do not require `OWNER` to be
<ide> moduleFor(
<ide>
<ide> assert.throws(() => {
<ide> Factory.create();
<del> }, /Can not create new instances after the owner has been destroyed \(you attempted to create service:other\)/);
<add> }, /Cannot create new instances after the owner has been destroyed \(you attempted to create service:other\)/);
<ide> }
<ide> }
<ide> ); | 1 |
PHP | PHP | fix undefined variable hosts | a2749017ef461dd4f0843bc73c826ce55a5fd63f | <ide><path>src/Illuminate/Database/Connectors/ConnectionFactory.php
<ide> protected function createPdoResolver(array $config)
<ide> protected function createPdoResolverWithHosts(array $config)
<ide> {
<ide> return function () use ($config) {
<del> foreach (Arr::shuffle($this->parseHosts($config)) as $key => $host) {
<add> foreach (Arr::shuffle($hosts = $this->parseHosts($config)) as $key => $host) {
<ide> $config['host'] = $host;
<ide>
<ide> try { | 1 |
Javascript | Javascript | add correct @restrict for all ng directives | d8987c170f98650baecae66ccc272bdbca352f64 | <ide><path>src/ng/directive/ngBind.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngBind
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
<ide><path>src/ng/directive/ngClass.js
<ide> function classDirective(name, selector) {
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngClass
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding
<ide> var ngClassDirective = classDirective('', true);
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngClassOdd
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngClassOdd` and `ngClassEven` directives work exactly as
<ide> var ngClassOddDirective = classDirective('Odd', 0);
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngClassEven
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngClassOdd` and `ngClassEven` directives work exactly as
<ide><path>src/ng/directive/ngCloak.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngCloak
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngCloak` directive is used to prevent the Angular html template from being briefly
<ide><path>src/ng/directive/ngInit.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngInit
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngInit` directive specifies initialization tasks to be executed
<ide><path>src/ng/directive/ngNonBindable.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngNonBindable
<add> * @restrict AC
<ide> * @priority 1000
<ide> *
<ide> * @description
<ide><path>src/ng/directive/ngStyle.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngStyle
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
<ide><path>src/ng/directive/ngTransclude.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:ngTransclude
<add> * @restrict AC
<ide> *
<ide> * @description
<ide> * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
<ide><path>src/ng/directive/script.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ng.directive:script
<add> * @restrict E
<ide> *
<ide> * @description
<ide> * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
<ide> * template can be used by `ngInclude`, `ngView` or directive templates.
<ide> *
<del> * @restrict E
<ide> * @param {'text/ng-template'} type must be set to `'text/ng-template'`
<ide> *
<ide> * @example | 8 |
Text | Text | update urls for rpms | 24bb36297c1457d71114d678671f77001b6936a5 | <ide><path>docs/installation/centos.md
<ide> only the package you install differs. There are two packages to choose from:
<ide> <td>6.5 and higher</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm</a>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-6/SRPMS/docker-engine-1.7.0-1.el6.src.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-6/SRPMS/docker-engine-1.7.0-1.el6.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-6/SRPMS/docker-engine-1.7.1-1.el6.src.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-6/SRPMS/docker-engine-1.7.1-1.el6.src.rpm</a>
<ide> <p>
<ide> </p>
<ide> </td>
<ide> only the package you install differs. There are two packages to choose from:
<ide> <td>7.X</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-7/RPMS/x86_64/docker-engine-1.7.0-1.el7.centos.x86_64.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-7/RPMS/x86_64/docker-engine-1.7.0-1.el7.centos.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm</a>
<ide> </p>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-7/SRPMS/docker-engine-1.7.0-1.el7.centos.src.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-7/SRPMS/docker-engine-1.7.0-1.el7.centos.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm</a>
<ide> </p>
<ide> </td>
<ide> </tr>
<ide> This procedure depicts an installation on version 6.5. If you are installing on
<ide>
<ide> 3. Download the Docker RPM to the current directory.
<ide>
<del> $ curl -O -sSL https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm
<add> $ curl -O -sSL https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm
<ide>
<ide> 4. Use `yum` to install the package.
<ide>
<del> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.0-1.el6.x86_64.rpm
<add> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-1.el6.x86_64.rpm
<ide>
<ide> 5. Start the Docker daemon.
<ide>
<ide> This procedure depicts an installation on version 6.5. If you are installing on
<ide> a8219747be10: Pull complete
<ide> 91c95931e552: Already exists
<ide> hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
<del> Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd1.7.0cf5daeb82aab55838d
<add> Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd1.7.1cf5daeb82aab55838d
<ide> Status: Downloaded newer image for hello-world:latest
<ide> Hello from Docker.
<ide> This message shows that your installation appears to be working correctly.
<ide> You can uninstall the Docker software with `yum`.
<ide>
<ide> $ yum list installed | grep docker
<ide> yum list installed | grep docker
<del> docker-engine.x86_64 1.7.0-1.el6
<del> @/docker-engine-1.7.0-1.el6.x86_64.rpm
<add> docker-engine.x86_64 1.7.1-1.el6
<add> @/docker-engine-1.7.1-1.el6.x86_64.rpm
<ide>
<ide> 2. Remove the package.
<ide>
<ide> You can uninstall the Docker software with `yum`.
<ide>
<ide> $ rm -rf /var/lib/docker
<ide>
<del>4. Locate and delete any user-created configuration files.
<ide>\ No newline at end of file
<add>4. Locate and delete any user-created configuration files.
<ide><path>docs/installation/fedora.md
<ide> only the package you install differs. Choose from these packages:
<ide> <td>Fedora 20</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-20/RPMS/x86_64/docker-engine-1.7.0-1.fc20.x86_64.rpm">
<del> docker-engine-1.7.0-1.fc20.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-20/RPMS/x86_64/docker-engine-1.7.1-1.fc20.x86_64.rpm">
<add> docker-engine-1.7.1-1.fc20.x86_64.rpm</a>
<ide> </p>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-20/SRPMS/docker-engine-1.7.0-1.fc20.src.rpm">
<del> docker-engine-1.7.0-1.fc20.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-20/SRPMS/docker-engine-1.7.1-1.fc20.src.rpm">
<add> docker-engine-1.7.1-1.fc20.src.rpm</a>
<ide> </p>
<ide> </td>
<ide> </tr>
<ide> <tr>
<ide> <td>Fedora 21</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-21/RPMS/x86_64/docker-engine-1.7.0-1.fc21.x86_64.rpm">
<del> docker-engine-1.7.0-1.fc21.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-21/RPMS/x86_64/docker-engine-1.7.1-1.fc21.x86_64.rpm">
<add> docker-engine-1.7.1-1.fc21.x86_64.rpm</a>
<ide> </p>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-21/SRPMS/docker-engine-1.7.0-1.fc21.src.rpm">
<del> docker-engine-1.7.0-1.fc21.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-21/SRPMS/docker-engine-1.7.1-1.fc21.src.rpm">
<add> docker-engine-1.7.1-1.fc21.src.rpm</a>
<ide> </p>
<ide> </td>
<ide> </tr>
<ide> <tr>
<ide> <td>Fedora 22</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-22/RPMS/x86_64/docker-engine-1.7.0-1.fc22.x86_64.rpm">
<del> docker-engine-1.7.0-1.fc22.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-22/RPMS/x86_64/docker-engine-1.7.1-1.fc22.x86_64.rpm">
<add> docker-engine-1.7.1-1.fc22.x86_64.rpm</a>
<ide> </p>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/fedora-22/SRPMS/docker-engine-1.7.0-1.fc22.src.rpm">
<del> docker-engine-1.7.0-1.fc22.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/fedora-22/SRPMS/docker-engine-1.7.1-1.fc22.src.rpm">
<add> docker-engine-1.7.1-1.fc22.src.rpm</a>
<ide> </p>
<ide> </td>
<ide> </tr>
<ide> This procedure depicts an installation on version 21. If you are installing on
<ide>
<ide> 3. Download the Docker RPM to the current directory.
<ide>
<del> $ curl -O -sSL https://url_to_package/docker-engine-1.7.0-0.1.fc21.x86_64.rpm
<add> $ curl -O -sSL https://url_to_package/docker-engine-1.7.1-0.1.fc21.x86_64.rpm
<ide>
<ide> 4. Use `yum` to install the package.
<ide>
<del> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.0-0.1.fc21.x86_64.rpm
<add> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-0.1.fc21.x86_64.rpm
<ide>
<ide> 5. Start the Docker daemon.
<ide>
<ide> You can uninstall the Docker software with `yum`.
<ide>
<ide> $ yum list installed | grep docker
<ide> yum list installed | grep docker
<del> docker-engine.x86_64 1.7.0-0.1.fc20
<del> @/docker-engine-1.7.0-0.1.fc20.el6.x86_64
<add> docker-engine.x86_64 1.7.1-0.1.fc20
<add> @/docker-engine-1.7.1-0.1.fc20.el6.x86_64
<ide>
<ide> 2. Remove the package.
<ide>
<ide><path>docs/installation/rhel.md
<ide> only the package you install differs. There are two packages to choose from:
<ide> <td>6.6 and higher</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm</a>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-6/SRPMS/docker-engine-1.7.0-1.el6.src.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-6/SRPMS/docker-engine-1.7.0-1.el6.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-6/SRPMS/docker-engine-1.7.1-1.el6.src.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-6/SRPMS/docker-engine-1.7.1-1.el6.src.rpm</a>
<ide> <p>
<ide> </p>
<ide> </td>
<ide> only the package you install differs. There are two packages to choose from:
<ide> <td>7.X</td>
<ide> <td>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-7/RPMS/x86_64/docker-engine-1.7.0-1.el7.centos.x86_64.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-7/RPMS/x86_64/docker-engine-1.7.0-1.el7.centos.x86_64.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm</a>
<ide> </p>
<ide> <p>
<del> <a href="https://get.docker.com/rpm/1.7.0/centos-7/SRPMS/docker-engine-1.7.0-1.el7.centos.src.rpm">
<del> https://get.docker.com/rpm/1.7.0/centos-7/SRPMS/docker-engine-1.7.0-1.el7.centos.src.rpm</a>
<add> <a href="https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm">
<add> https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm</a>
<ide> </p>
<ide> </td>
<ide> </tr>
<ide> This procedure depicts an installation on version 6.6. If you are installing on
<ide>
<ide> 2. Download the Docker RPM to the current directory.
<ide>
<del> $ curl -O -sSL https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm
<add> $ curl -O -sSL https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm
<ide>
<ide> 3. Use `yum` to install the package.
<ide>
<del> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.0-1.el6.x86_64.rpm
<add> $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-1.el6.x86_64.rpm
<ide>
<ide> 5. Start the Docker daemon.
<ide>
<ide> You can uninstall the Docker software with `yum`.
<ide>
<ide> $ yum list installed | grep docker
<ide> yum list installed | grep docker
<del> docker-engine.x86_64 1.7.0-0.1.el6
<del> @/docker-engine-1.7.0-0.1.el6.x86_64
<add> docker-engine.x86_64 1.7.1-0.1.el6
<add> @/docker-engine-1.7.1-0.1.el6.x86_64
<ide>
<ide> 2. Remove the package.
<ide>
<ide> You can uninstall the Docker software with `yum`.
<ide>
<ide> $ rm -rf /var/lib/docker
<ide>
<del>4. Locate and delete any user-created configuration files.
<ide>\ No newline at end of file
<add>4. Locate and delete any user-created configuration files. | 3 |
Javascript | Javascript | fix warnings in strict mode | 674d6a7d18821fcea8570b70a2454d5a1ab2d4ec | <ide><path>fonts.js
<ide> var Font = (function Font() {
<ide> };
<ide>
<ide> function createOS2Table(properties, override) {
<del> var override = override || {};
<add> override = override || {
<add> unitsPerEm: 0,
<add> yMax: 0,
<add> yMin: 0,
<add> ascent: 0,
<add> descent: 0
<add> };
<ide>
<ide> var ulUnicodeRange1 = 0;
<ide> var ulUnicodeRange2 = 0;
<ide> var Font = (function Font() {
<ide> 'OS/2': stringToArray(createOS2Table(properties)),
<ide>
<ide> // Character to glyphs mapping
<del> 'cmap': createCMapTable(charstrings.slice(), font.glyphIds),
<add> 'cmap': createCMapTable(charstrings.slice(),
<add> ('glyphIds' in font) ? font.glyphIds: null),
<ide>
<ide> // Font header
<ide> 'head': (function fontFieldsHead() {
<ide> var Type2CFF = (function type2CFF() {
<ide> if (unicode <= 0x1f || (unicode >= 127 && unicode <= 255))
<ide> unicode += kCmapGlyphOffset;
<ide>
<del> var width = isNum(mapping.width) ? mapping.width : defaultWidth;
<add> var width = ('width' in mapping) && isNum(mapping.width) ? mapping.width
<add> : defaultWidth;
<ide> properties.encoding[code] = {
<ide> unicode: unicode,
<ide> width: width
<ide><path>pdf.js
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> stroke: function canvasGraphicsStroke() {
<ide> var ctx = this.ctx;
<ide> var strokeColor = this.current.strokeColor;
<del> if (strokeColor && strokeColor.type === 'Pattern') {
<add> if (strokeColor && strokeColor.hasOwnProperty('type') &&
<add> strokeColor.type === 'Pattern') {
<ide> // for patterns, we transform to pattern space, calculate
<ide> // the pattern, call stroke, and restore to user space
<ide> ctx.save();
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> var ctx = this.ctx;
<ide> var fillColor = this.current.fillColor;
<ide>
<del> if (fillColor && fillColor.type === 'Pattern') {
<add> if (fillColor && fillColor.hasOwnProperty('type') &&
<add> fillColor.type === 'Pattern') {
<ide> ctx.save();
<ide> ctx.fillStyle = fillColor.getPattern(ctx);
<ide> ctx.fill();
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> var ctx = this.ctx;
<ide>
<ide> var fillColor = this.current.fillColor;
<del> if (fillColor && fillColor.type === 'Pattern') {
<add> if (fillColor && fillColor.hasOwnProperty('type') &&
<add> fillColor.type === 'Pattern') {
<ide> ctx.save();
<ide> ctx.fillStyle = fillColor.getPattern(ctx);
<ide> ctx.fill();
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> }
<ide>
<ide> var strokeColor = this.current.strokeColor;
<del> if (strokeColor && strokeColor.type === 'Pattern') {
<add> if (strokeColor && strokeColor.hasOwnProperty('type') &&
<add> strokeColor.type === 'Pattern') {
<ide> ctx.save();
<ide> ctx.strokeStyle = strokeColor.getPattern(ctx);
<ide> ctx.stroke();
<ide><path>web/compatibility.js
<ide>
<ide> // IE9 text/html data URI
<ide> (function checkDocumentDocumentModeCompatibility() {
<del> if (document.documentMode !== 9)
<add> if (!('documentMode' in document) || document.documentMode !== 9)
<ide> return;
<ide> // overriding the src property
<ide> var originalSrcDescriptor = Object.getOwnPropertyDescriptor(
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide>
<ide> while (sidebar.hasChildNodes())
<ide> sidebar.removeChild(sidebar.lastChild);
<del> clearInterval(sidebar._loadingInterval);
<add>
<add> if ('_loadingInterval' in sidebar)
<add> clearInterval(sidebar._loadingInterval);
<ide>
<ide> var container = document.getElementById('viewer');
<ide> while (container.hasChildNodes())
<ide> window.addEventListener('load', function webViewerLoad(evt) {
<ide> params[unescape(param[0])] = unescape(param[1]);
<ide> }
<ide>
<del> PDFView.open(params.file || kDefaultURL, parseFloat(params.scale));
<add> var scale = ('scale' in params) ? params.scale : kDefaultScale;
<add> PDFView.open(params.file || kDefaultURL, parseFloat(scale));
<ide>
<ide> if (!window.File || !window.FileReader || !window.FileList || !window.Blob)
<ide> document.getElementById('fileInput').style.display = 'none'; | 4 |
Javascript | Javascript | set exit code when installation failed | dfc23966282f4323464d8d40bdb12cded7cce35d | <ide><path>bin/webpack.js
<ide> if (!webpackCliInstalled) {
<ide> .catch(error => {
<ide> questionInterface.close();
<ide> console.error(error);
<add> process.exitCode = 1;
<ide> });
<ide> break;
<ide> } | 1 |
Javascript | Javascript | fix a typo | 9a13dd78fc6a37e5239fabd428973bdfd5a8f8a0 | <ide><path>src/Chart.Core.js
<ide> });
<ide>
<ide> // If there are no animations queued, manually kickstart a digest, for lack of a better word
<del> if(!this.animations.length){
<add> if (this.animations.length) {
<ide> helpers.requestAnimFrame(this.startDigest);
<ide> }
<ide> }, | 1 |
Python | Python | update doubly_linked_list.py (#545) | 1b19028117c88aaf49803ccd76652b68ead0b7e1 | <ide><path>data_structures/linked_list/doubly_linked_list.py
<ide> - A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
<ide> - This is an example of a double ended, doubly linked list.
<ide> - Each link references the next link and the previous one.
<del>'''
<add>- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
<add> - Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent'''
<ide> from __future__ import print_function
<ide>
<ide>
<del>class LinkedList:
<add>class LinkedList: #making main class named linked list
<ide> def __init__(self):
<ide> self.head = None
<ide> self.tail = None
<ide>
<ide> def insertHead(self, x):
<del> newLink = Link(x) #Create a new link with a value attached to it
<del> if(self.isEmpty() == True): #Set the first element added to be the tail
<add> newLink = Link(x) #Create a new link with a value attached to it
<add> if(self.isEmpty() == True): #Set the first element added to be the tail
<ide> self.tail = newLink
<ide> else:
<del> self.head.previous = newLink # newLink <-- currenthead(head)
<del> newLink.next = self.head # newLink <--> currenthead(head)
<del> self.head = newLink # newLink(head) <--> oldhead
<add> self.head.previous = newLink # newLink <-- currenthead(head)
<add> newLink.next = self.head # newLink <--> currenthead(head)
<add> self.head = newLink # newLink(head) <--> oldhead
<ide>
<ide> def deleteHead(self):
<ide> temp = self.head
<del> self.head = self.head.next # oldHead <--> 2ndElement(head)
<del> self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
<add> self.head = self.head.next # oldHead <--> 2ndElement(head)
<add> self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
<ide> if(self.head is None):
<del> self.tail = None
<add> self.tail = None #if empty linked list
<ide> return temp
<ide>
<ide> def insertTail(self, x):
<ide> newLink = Link(x)
<del> newLink.next = None # currentTail(tail) newLink -->
<del> self.tail.next = newLink # currentTail(tail) --> newLink -->
<del> newLink.previous = self.tail #currentTail(tail) <--> newLink -->
<del> self.tail = newLink # oldTail <--> newLink(tail) -->
<add> newLink.next = None # currentTail(tail) newLink -->
<add> self.tail.next = newLink # currentTail(tail) --> newLink -->
<add> newLink.previous = self.tail #currentTail(tail) <--> newLink -->
<add> self.tail = newLink # oldTail <--> newLink(tail) -->
<ide>
<ide> def deleteTail(self):
<ide> temp = self.tail
<del> self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
<del> self.tail.next = None # 2ndlast(tail) --> None
<add> self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
<add> self.tail.next = None # 2ndlast(tail) --> None
<ide> return temp
<ide>
<ide> def delete(self, x):
<ide> current = self.head
<ide>
<del> while(current.value != x): # Find the position to delete
<add> while(current.value != x): # Find the position to delete
<ide> current = current.next
<ide>
<ide> if(current == self.head):
<ide> def delete(self, x):
<ide> current.previous.next = current.next # 1 --> 3
<ide> current.next.previous = current.previous # 1 <--> 3
<ide>
<del> def isEmpty(self): #Will return True if the list is empty
<add> def isEmpty(self): #Will return True if the list is empty
<ide> return(self.head is None)
<ide>
<del> def display(self): #Prints contents of the list
<add> def display(self): #Prints contents of the list
<ide> current = self.head
<ide> while(current != None):
<ide> current.displayLink()
<ide> current = current.next
<ide> print()
<ide>
<ide> class Link:
<del> next = None #This points to the link in front of the new link
<del> previous = None #This points to the link behind the new link
<add> next = None #This points to the link in front of the new link
<add> previous = None #This points to the link behind the new link
<ide> def __init__(self, x):
<ide> self.value = x
<ide> def displayLink(self): | 1 |
Javascript | Javascript | fix lint errors | 56789aea47efa22912034d4f337f14b23be23699 | <ide><path>src/util.js
<ide> function backtrace() {
<ide> try {
<ide> throw new Error();
<ide> } catch (e) {
<del> return e.stack ? e.stack.split('\n').slice(2).join('\n') : "";
<add> return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
<ide> }
<ide> }
<ide>
<ide> function error(msg) {
<del> log("Error: " + msg);
<add> log('Error: ' + msg);
<ide> log(backtrace());
<ide> throw new Error(msg);
<ide> } | 1 |
Ruby | Ruby | use epochs in tabs | f085597cbdabab1138c96b7d928b4ae451a50e5d | <ide><path>Library/Homebrew/formula.rb
<ide> def latest_head_prefix
<ide> def head_version_outdated?(version, options={})
<ide> tab = Tab.for_keg(prefix(version))
<ide>
<add> return true if tab.version_scheme < version_scheme
<ide> return true if stable && tab.stable_version && tab.stable_version < stable.version
<ide> return true if devel && tab.devel_version && tab.devel_version < devel.version
<ide>
<ide> class << self
<ide> # Used for creating new Homebrew versions schemes. For example, if we want
<ide> # to change version scheme from one to another, then we may need to update
<ide> # `version_scheme` of this {Formula} to be able to use new version scheme.
<add> # E.g. to move from 20151020 scheme to 1.0.0 we need to increment
<add> # `version_scheme`. Without this, the prior scheme will always equate to a
<add> # higher version.
<ide> # `0` if unset.
<ide> #
<ide> # <pre>version_scheme 1</pre>
<ide><path>Library/Homebrew/tab.rb
<ide> def self.create(formula, compiler, stdlib)
<ide> "stable" => formula.stable ? formula.stable.version.to_s : nil,
<ide> "devel" => formula.devel ? formula.devel.version.to_s : nil,
<ide> "head" => formula.head ? formula.head.version.to_s : nil,
<add> "version_scheme" => formula.version_scheme,
<ide> }
<ide> }
<ide> }
<ide> def self.from_file_content(content, path)
<ide> "stable" => nil,
<ide> "devel" => nil,
<ide> "head" => nil,
<add> "version_scheme" => 0,
<ide> }
<ide> end
<ide>
<ide> def self.for_formula(f)
<ide> "stable" => f.stable ? f.stable.version.to_s : nil,
<ide> "devel" => f.devel ? f.devel.version.to_s : nil,
<ide> "head" => f.head ? f.head.version.to_s : nil,
<add> "version_scheme" => f.version_scheme,
<ide> }
<ide> }
<ide> end
<ide> def self.empty
<ide> "stable" => nil,
<ide> "devel" => nil,
<ide> "head" => nil,
<add> "version_scheme" => 0,
<ide> }
<ide> }
<ide> }
<ide> def head_version
<ide> Version.create(versions["head"]) if versions["head"]
<ide> end
<ide>
<add> def version_scheme
<add> versions["version_scheme"] || 0
<add> end
<add>
<ide> def source_modified_time
<ide> Time.at(super)
<ide> end | 2 |
Text | Text | improve the contributing to rails guide [skip ci] | 5c7b8d9f403897a5fdf2be05518a32c863915d60 | <ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> When you're happy with the code on your computer, you need to commit the changes
<ide> $ git commit -a
<ide> ```
<ide>
<del>At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.
<add>This should fire up your editor to write a commit message. When you have
<add>finished, save and close to continue.
<ide>
<del>Good commit message should be formatted according to the following example:
<add>A well-formatted and descriptive commit message is very helpful to others for
<add>understanding why the change was made, so please take the time to write it.
<add>
<add>A good commit message looks like this:
<ide>
<ide> ```
<ide> Short summary (ideally 50 characters or less)
<ide>
<del>More detailed description, if necessary. It should be wrapped to 72
<del>characters. Try to be as descriptive as you can; even if you think that the
<del>commit content is obvious, it may not be obvious to others. Add any description
<del>that is already present in relevant issues - it should not be necessary to visit
<del>a webpage to check the history.
<add>More detailed description, if necessary. It should be wrapped to
<add>72 characters. Try to be as descriptive as you can. Even if you
<add>think that the commit content is obvious, it may not be obvious
<add>to others. Add any description that is already present in the
<add>relevant issues; it should not be necessary to visit a webpage
<add>to check the history.
<add>
<add>The description section can have multiple paragraphs.
<ide>
<del>The description section can have multiple paragraphs. Code examples can be
<del>embedded by indenting them with 4 spaces:
<add>Code examples can be embedded by indenting them with 4 spaces:
<ide>
<ide> class ArticlesController
<ide> def index
<ide> embedded by indenting them with 4 spaces:
<ide>
<ide> You can also add bullet points:
<ide>
<del>- you can use dashes or asterisks
<add>- make a bullet point by starting a line with either a dash (-)
<add> or an asterisk (*)
<ide>
<del>- also, try to indent next line of a point for readability, if it's too
<del> long to fit in 72 characters
<add>- wrap lines at 72 characters, and indent any additional lines
<add> with 2 spaces for readability
<ide> ```
<ide>
<ide> TIP. Please squash your commits into a single commit when appropriate. This
<del>simplifies future cherry picks and also keeps the git log clean.
<add>simplifies future cherry picks and keeps the git log clean.
<ide>
<ide> ### Update Your Branch
<ide> | 1 |
Python | Python | remove lines with no effect | 79ec9b8079e926104b444239cc9642cb269492dc | <ide><path>examples/mnist_acgan.py
<ide> def build_discriminator():
<ide> loss=['binary_crossentropy', 'sparse_categorical_crossentropy']
<ide> )
<ide>
<del> discriminator.trainable = True
<del>
<ide> # get our mnist data, and force it to be of shape (..., 1, 28, 28) with
<ide> # range [-1, 1]
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide> def build_discriminator():
<ide> noise = np.random.uniform(-1, 1, (2 * batch_size, latent_size))
<ide> sampled_labels = np.random.randint(0, 10, 2 * batch_size)
<ide>
<del> # we want to fix the discriminator and let the generator train to
<del> # trick it
<del> discriminator.trainable = False
<del>
<add> # we want to train the genrator to trick the discriminator
<ide> # For the generator, we want all the {fake, not-fake} labels to say
<ide> # not-fake
<ide> trick = np.ones(2 * batch_size)
<ide>
<ide> epoch_gen_loss.append(combined.train_on_batch(
<ide> [noise, sampled_labels.reshape((-1, 1))], [trick, sampled_labels]))
<ide>
<del> discriminator.trainable = True
<del>
<ide> print('\nTesting for epoch {}:'.format(epoch + 1))
<ide>
<ide> # evaluate the testing loss here | 1 |
Text | Text | add talkingheadsattention to readme | 85b50c8819ac9c109283a0b25e83367db8d679c9 | <ide><path>official/nlp/modeling/layers/README.md
<ide> If `from_tensor` and `to_tensor` are the same, then this is self-attention.
<ide> * [CachedAttention](attention.py) implements an attention layer with cache used
<ide> for auto-agressive decoding.
<ide>
<add>* [TalkingHeadsAttention](talking_heads_attention.py) implements the talking
<add>heads attention, as decribed in ["Talking-Heads Attention"](https://arxiv.org/abs/2003.02436).
<add>
<ide> * [Transformer](transformer.py) implements an optionally masked transformer as
<ide> described in ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762).
<ide> | 1 |
Python | Python | add final_layer_norm to opt model | abc400b06a8ab26cd438b6e9add3aad082ffc48f | <ide><path>src/transformers/models/opt/configuration_opt.py
<ide> def __init__(
<ide> ffn_dim=3072,
<ide> max_position_embeddings=2048,
<ide> do_layer_norm_before=True,
<add> _remove_final_layer_norm=False,
<ide> word_embed_proj_dim=None,
<ide> dropout=0.1,
<ide> attention_dropout=0.0,
<ide> def __init__(
<ide> self.layerdrop = layerdrop
<ide> self.use_cache = use_cache
<ide> self.do_layer_norm_before = do_layer_norm_before
<add>
<add> # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility
<add> # with checkpoints that have been fine-tuned before transformers v4.20.1
<add> # see https://github.com/facebookresearch/metaseq/pull/164
<add> self._remove_final_layer_norm = _remove_final_layer_norm
<ide><path>src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py
<ide> def load_checkpoint(checkpoint_path):
<ide> # pop unnecessary weights
<ide> keys_to_delete = [
<ide> "decoder.version",
<del> "decoder.layer_norm.weight",
<del> "decoder.layer_norm.bias",
<ide> "decoder.output_projection.weight",
<ide> ]
<ide> for key in keys_to_delete:
<ide> def load_checkpoint(checkpoint_path):
<ide> keys_to_rename = {
<ide> "decoder.project_in_dim.weight": "decoder.project_in.weight",
<ide> "decoder.project_out_dim.weight": "decoder.project_out.weight",
<add> "decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
<add> "decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
<ide> }
<ide> for old_key, new_key in keys_to_rename.items():
<ide> if old_key in sd:
<ide><path>src/transformers/models/opt/modeling_flax_opt.py
<ide> def setup(self):
<ide> self.project_in = None
<ide> self.project_out = None
<ide>
<add> # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
<add> # with checkpoints that have been fine-tuned before transformers v4.20.1
<add> # see https://github.com/facebookresearch/metaseq/pull/164
<add> if self.config.do_layer_norm_before and not self.config._remove_final_layer_norm:
<add> self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
<add> else:
<add> self.final_layer_norm = None
<add>
<ide> self.layers = FlaxOPTDecoderLayerCollection(self.config, self.dtype)
<ide>
<ide> def __call__(
<ide> def __call__(
<ide> output_hidden_states=output_hidden_states,
<ide> )
<ide>
<add> if self.final_layer_norm is not None:
<add> hidden_state = self.final_layer_norm(hidden_state)
<add>
<ide> if self.project_out is not None:
<ide> hidden_state = self.project_out(hidden_state)
<ide>
<ide><path>src/transformers/models/opt/modeling_opt.py
<ide> def __init__(self, config: OPTConfig):
<ide> else:
<ide> self.project_in = None
<ide>
<del> self.layer_norm = None
<add> # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
<add> # with checkpoints that have been fine-tuned before transformers v4.20.1
<add> # see https://github.com/facebookresearch/metaseq/pull/164
<add> if config.do_layer_norm_before and not config._remove_final_layer_norm:
<add> self.final_layer_norm = nn.LayerNorm(config.hidden_size)
<add> else:
<add> self.final_layer_norm = None
<add>
<ide> self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)])
<ide>
<ide> self.gradient_checkpointing = False
<ide> def custom_forward(*inputs):
<ide> if output_attentions:
<ide> all_self_attns += (layer_outputs[1],)
<ide>
<add> if self.final_layer_norm is not None:
<add> hidden_states = self.final_layer_norm(hidden_states)
<add>
<ide> if self.project_out is not None:
<ide> hidden_states = self.project_out(hidden_states)
<ide>
<ide><path>src/transformers/models/opt/modeling_tf_opt.py
<ide> def __init__(self, config: OPTConfig, load_weight_prefix=None, **kwargs):
<ide> name="embed_positions",
<ide> )
<ide>
<add> # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
<add> # with checkpoints that have been fine-tuned before transformers v4.20.1
<add> # see https://github.com/facebookresearch/metaseq/pull/164
<add> if config.do_layer_norm_before and not config._remove_final_layer_norm:
<add> self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
<add> else:
<add> self.final_layer_norm = None
<add>
<ide> if config.word_embed_proj_dim != config.hidden_size:
<ide> self.project_out = tf.keras.layers.Dense(config.word_embed_proj_dim, name="project_out", use_bias=False)
<ide> self.project_in = tf.keras.layers.Dense(config.hidden_size, name="project_in", use_bias=False)
<ide> def call(
<ide> if output_attentions:
<ide> all_self_attns += (layer_self_attn,)
<ide>
<add> if self.final_layer_norm is not None:
<add> hidden_states = self.final_layer_norm(hidden_states)
<add>
<ide> if self.project_out is not None:
<ide> hidden_states = self.project_out(hidden_states)
<ide>
<ide><path>tests/models/opt/test_modeling_flax_opt.py
<ide> def test_generation_pre_attn_layer_norm(self):
<ide> model_id = "facebook/opt-125m"
<ide>
<ide> EXPECTED_OUTPUTS = [
<del> "Today is a beautiful day and I want everyone",
<del> "In the city of Rome Canaver Canaver Canaver Canaver",
<del> "Paris is the capital of France and Parisdylib",
<del> "Computers and mobile phones have taken precedence over",
<add> "Today is a beautiful day and I want to",
<add> "In the city of New York, the city",
<add> "Paris is the capital of France and the capital",
<add> "Computers and mobile phones have taken over the",
<ide> ]
<ide>
<ide> predicted_outputs = []
<ide><path>tests/models/opt/test_modeling_opt.py
<ide> def test_generation_pre_attn_layer_norm(self):
<ide> model_id = "facebook/opt-125m"
<ide>
<ide> EXPECTED_OUTPUTS = [
<del> "Today is a beautiful day and I want everyone",
<del> "In the city of Rome Canaver Canaver Canaver Canaver",
<del> "Paris is the capital of France and Parisdylib",
<del> "Computers and mobile phones have taken precedence over",
<add> "Today is a beautiful day and I want to",
<add> "In the city of New York, the city",
<add> "Paris is the capital of France and the capital",
<add> "Computers and mobile phones have taken over the",
<ide> ]
<ide>
<ide> predicted_outputs = []
<ide><path>tests/models/opt/test_modeling_tf_opt.py
<ide> def test_generation_pre_attn_layer_norm(self):
<ide> model_id = "facebook/opt-125m"
<ide>
<ide> EXPECTED_OUTPUTS = [
<del> "Today is a beautiful day and I want everyone",
<del> "In the city of Rome Canaver Canaver Canaver Canaver",
<del> "Paris is the capital of France and Parisdylib",
<del> "Computers and mobile phones have taken precedence over",
<add> "Today is a beautiful day and I want to",
<add> "In the city of New York, the city",
<add> "Paris is the capital of France and the capital",
<add> "Computers and mobile phones have taken over the",
<ide> ]
<ide>
<ide> predicted_outputs = [] | 8 |
Text | Text | change core_ext cherry picking example | fdabc1757e3d1aa928fb66a04bc015348637274c | <ide><path>guides/source/active_support_core_extensions.md
<ide> How to Load Core Extensions
<ide>
<ide> ### Stand-Alone Active Support
<ide>
<del>In order to have a near-zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.
<add>In order to have the smallest default footprint possible, Active Support loads the minimum dependencies by default. It is broken in small pieces so that only the desired extensions can be loaded. It also has some convenience entry points to load related extensions in one shot, even everything.
<ide>
<ide> Thus, after a simple require like:
<ide>
<ide> ```ruby
<ide> require "active_support"
<ide> ```
<ide>
<del>objects do not even respond to [`blank?`][Object#blank?]. Let's see how to load its definition.
<add>only the extensions required by the Active Support framework are loaded.
<ide>
<ide> #### Cherry-picking a Definition
<ide>
<del>The most lightweight way to get `blank?` is to cherry-pick the file that defines it.
<add>This example shows how to load [`Hash#with_indifferent_access`][Hash#with_indifferent_access]. This extension enables the conversion of a `Hash` into an [`ActiveSupport::HashWithIndifferentAccess`][ActiveSupport::HashWithIndifferentAccess] which permits access to the keys as either strings or symbols.
<ide>
<del>For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `blank?` the note reads:
<add>```ruby
<add>{a: 1}.with_indifferent_access["a"] # => 1
<add>```
<ide>
<del>NOTE: Defined in `active_support/core_ext/object/blank.rb`.
<add>For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `with_indifferent_access` the note reads:
<add>
<add>NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
<ide>
<ide> That means that you can require it like this:
<ide>
<ide> ```ruby
<ide> require "active_support"
<del>require "active_support/core_ext/object/blank"
<add>require "active_support/core_ext/hash/indifferent_access"
<ide> ```
<ide>
<ide> Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.
<ide>
<ide> #### Loading Grouped Core Extensions
<ide>
<del>The next level is to simply load all extensions to `Object`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
<add>The next level is to simply load all extensions to `Hash`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
<ide>
<del>Thus, to load all extensions to `Object` (including `blank?`):
<add>Thus, to load all extensions to `Hash` (including `with_indifferent_access`):
<ide>
<ide> ```ruby
<ide> require "active_support"
<del>require "active_support/core_ext/object"
<add>require "active_support/core_ext/hash"
<ide> ```
<ide>
<ide> #### Loading All Core Extensions | 1 |
Javascript | Javascript | fix jsc crash in dev | d2de60472103e1b3f2fe82ed53cce38db6334af5 | <ide><path>Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js
<ide> function deepFreezeAndThrowOnMutationInDev(object: Object) {
<ide> return;
<ide> }
<ide>
<del> for (var key in object) {
<add> var keys = Object.keys(object);
<add>
<add> for (var i = 0; i < keys.length; i++) {
<add> var key = keys[i];
<ide> if (object.hasOwnProperty(key)) {
<ide> object.__defineGetter__(key, identity.bind(null, object[key]));
<ide> object.__defineSetter__(key, throwOnImmutableMutation.bind(null, key));
<ide> function deepFreezeAndThrowOnMutationInDev(object: Object) {
<ide> Object.freeze(object);
<ide> Object.seal(object);
<ide>
<del> for (var key in object) {
<add> for (var i = 0; i < keys.length; i++) {
<add> var key = keys[i];
<ide> if (object.hasOwnProperty(key)) {
<ide> deepFreezeAndThrowOnMutationInDev(object[key]);
<ide> } | 1 |
Text | Text | fix example code for css grid article | 0a9c8830537df926aa458427c3d18f20605c4261 | <ide><path>curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-columns-with-grid-template-columns.spanish.md
<ide> localeTitle: Añadir columnas con cuadrícula-plantilla-columnas
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Simplemente crear un elemento de cuadrícula no te lleva muy lejos. También es necesario definir la estructura de la cuadrícula. Para agregar algunas columnas a la cuadrícula, use la propiedad <code>grid-template-columns</code> en un contenedor de cuadrícula como se muestra a continuación: <blockquote> .envase { <br> pantalla: rejilla; <br> rejilla-plantilla-columnas: 50px 50px; <br> } </blockquote> Esto le dará a su cuadrícula dos columnas de 50px de ancho cada una. El número de parámetros dados a la propiedad <code>grid-template-columns</code> indica el número de columnas en la cuadrícula, y el valor de cada parámetro indica el ancho de cada columna. </section>
<add><section id="description"> Simplemente crear un elemento de cuadrícula no te lleva muy lejos. También es necesario definir la estructura de la cuadrícula. Para agregar algunas columnas a la cuadrícula, use la propiedad <code>grid-template-columns</code> en un contenedor de cuadrícula como se muestra a continuación:
<add>
<add> ```html
<add>.container {
<add> display: grid;
<add> grid-template-columns: 50px 50px;
<add>}
<add>```
<add>
<add>Esto le dará a su cuadrícula dos columnas de 50px de ancho cada una. El número de parámetros dados a la propiedad <code>grid-template-columns</code> indica el número de columnas en la cuadrícula, y el valor de cada parámetro indica el ancho de cada columna. </section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> Entregue al contenedor de la cuadrícula tres columnas de <code>100px</code> ancho cada una. </section>
<add><section id="instructions"> Definir al contenedor de la cuadrícula tres columnas de <code>100px</code> de ancho cada una. </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'> | 1 |
PHP | PHP | add parentheses to referenced method name | 1a058316cbb4fd4bbe4f15544bc7dcc49cf8cda7 | <ide><path>src/Network/Request.php
<ide> public function clearDetectorCache() {
<ide> }
<ide>
<ide> /**
<del> * Worker for the public is function
<add> * Worker for the public is() function
<ide> *
<ide> * @param string|array $type The type of request you want to check. If an array
<ide> * this method will return true if the request matches any type. | 1 |
PHP | PHP | fix a number of coding standards errors | 7b407f890b2245611990d8a6621a228ede6b13f5 | <ide><path>lib/Cake/Test/TestCase/Controller/ComponentRegistryTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Controller;
<ide>
<del>use Cake\Controller\Component\CookieComponent;
<ide> use Cake\Controller\ComponentRegistry;
<add>use Cake\Controller\Component\CookieComponent;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Plugin;
<ide><path>lib/Cake/Test/TestCase/Database/QueryTest.php
<ide> public function testBind() {
<ide> ->from('comments')
<ide> ->where(['created BETWEEN :foo AND :bar'])
<ide> ->bind(':foo', '2007-03-18 10:50:00')
<del> ->bind(':bar','2007-03-18 10:52:00')
<add> ->bind(':bar', '2007-03-18 10:52:00')
<ide> ->execute();
<ide> $this->assertEquals($expected, $results->fetchAll('assoc'));
<ide> }
<ide><path>lib/Cake/Test/TestCase/ORM/BufferedResultSetTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Model\ConnectionManager;
<del>use Cake\ORM\Query;
<ide> use Cake\ORM\BufferedResultSet;
<add>use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>lib/Cake/Test/TestCase/ORM/QueryTest.php
<ide> public function testHasManyEagerLoadingDeep($strategy) {
<ide> 'author_id' => 1,
<ide> 'body' => 'First Article Body',
<ide> 'published' => 'Y',
<del> 'author' => ['id' => 1 , 'name' => 'mariano']
<add> 'author' => ['id' => 1, 'name' => 'mariano']
<ide> ],
<ide> [
<ide> 'id' => 3,
<ide><path>lib/Cake/Test/TestCase/Utility/StringTest.php
<ide> public function testInsert() {
<ide> $expected = "this is a long string with a few? params you know";
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = String::insert('update saved_urls set url = :url where id = :id', array('url' => 'http://www.testurl.com/param1:url/param2:id','id' => 1));
<add> $result = String::insert('update saved_urls set url = :url where id = :id', array('url' => 'http://www.testurl.com/param1:url/param2:id', 'id' => 1));
<ide> $expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
<ide> $this->assertEquals($expected, $result);
<ide>
<ide><path>lib/Cake/TestSuite/Fixture/FixtureInjector.php
<ide> */
<ide> namespace Cake\TestSuite\Fixture;
<ide>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\TestSuite\Fixture\FixtureManager;
<ide> use \Exception;
<ide> use \PHPUnit_Framework_AssertionFailedError;
<ide> use \PHPUnit_Framework_Test;
<ide> use \PHPUnit_Framework_TestSuite;
<ide> use \PHPUnit_Framework_TestListener;
<del>use Cake\TestSuite\TestCase;
<del>use Cake\TestSuite\Fixture\FixtureManager;
<ide>
<ide> /**
<ide> * Test listener used to inject a fixture manager in all tests that
<ide><path>lib/Cake/TestSuite/Fixture/FixtureManager.php
<ide> protected function _setupTable(TestFixture $fixture, Connection $db = null, $dro
<ide> *
<ide> * @param Cake\TestSuite\TestCase $test the test to inspect for fixture loading
<ide> * @return void
<add> * @throws Cake\Error\Exception When fixture records cannot be inserted.
<ide> */
<ide> public function load(TestCase $test) {
<ide> if (empty($test->fixtures)) {
<ide><path>lib/Cake/TestSuite/TestCase.php
<ide> protected function skipUnless($condition, $message = '') {
<ide> * @param string $model
<ide> * @param mixed $methods
<ide> * @param array $config
<del> * @throws MissingModelException
<add> * @throws Cake\Error\MissingModelException
<ide> * @return Model
<ide> */
<ide> public function getMockForModel($model, $methods = array(), $config = array()) {
<ide><path>lib/Cake/Utility/Security.php
<ide> public static function setHash($hash) {
<ide> *
<ide> * @param integer $cost Valid values are 4-31
<ide> * @return void
<add> * @throws Cake\Error\Exception When cost is invalid.
<ide> */
<ide> public static function setCost($cost) {
<ide> if ($cost < 4 || $cost > 31) {
<ide><path>lib/Cake/Utility/Time.php
<ide> public static function isThisYear($dateString, $timezone = null) {
<ide> public static function wasYesterday($dateString, $timezone = null) {
<ide> $timestamp = static::fromString($dateString, $timezone);
<ide> $yesterday = static::fromString('yesterday', $timezone);
<del> return date('Y-m-d', $timestamp) == date('Y-m-d',$yesterday);
<add> return date('Y-m-d', $timestamp) == date('Y-m-d', $yesterday);
<ide> }
<ide>
<ide> /** | 10 |
Python | Python | add tile to numpy and move repmat to matlib.py | 1ff0cd9948e79eecd2c8ec9ac9aa88c81c6b9dfc | <ide><path>numpy/lib/shape_base.py
<ide> __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack',
<ide> 'column_stack','row_stack', 'dstack','array_split','split','hsplit',
<ide> 'vsplit','dsplit','apply_over_axes','expand_dims',
<del> 'apply_along_axis', 'repmat', 'kron']
<add> 'apply_along_axis', 'tile', 'kron']
<ide>
<ide> import numpy.core.numeric as _nx
<ide> from numpy.core.numeric import asarray, zeros, newaxis, outer, \
<ide> def dsplit(ary,indices_or_sections):
<ide> raise ValueError, 'vsplit only works on arrays of 3 or more dimensions'
<ide> return split(ary,indices_or_sections,2)
<ide>
<del># should figure out how to generalize this one.
<del>def repmat(a, m, n):
<del> """Repeat a 0-d to 2-d array mxn times
<del> """
<del> a = asanyarray(a)
<del> ndim = a.ndim
<del> if ndim == 0:
<del> origrows, origcols = (1,1)
<del> elif ndim == 1:
<del> origrows, origcols = (1, a.shape[0])
<del> else:
<del> origrows, origcols = a.shape
<del> rows = origrows * m
<del> cols = origcols * n
<del> c = a.reshape(1,a.size).repeat(m, 0).reshape(rows, origcols).repeat(n,0)
<del> return c.reshape(rows, cols)
<del>
<del>
<ide> def _getwrapper(*args):
<ide> """Find the wrapper for the array with the highest priority.
<ide>
<ide> def kron(a,b):
<ide> if wrapper is not None:
<ide> result = wrapper(result)
<ide> return result
<add>
<add>def tile(A, reps):
<add> """Repeat an array the number of times given in the integer tuple, tup.
<add>
<add> If reps has length d, the result will have dimension of max(d, A.ndim).
<add> If reps is scalar it is treated as a 1-tuple.
<add>
<add> If A.ndim < d, A is promoted to be d-dimensional by prepending new axes.
<add> So a shape (3,) array is promoted to (1,3) for 2-D replication,
<add> or shape (1,1,3) for 3-D replication.
<add> If this is not the desired behavior, promote A to d-dimensions manually
<add> before calling this function.
<add>
<add> If d < A.ndim, tup is promoted to A.ndim by pre-pending 1's to it. Thus
<add> for an A.shape of (2,3,4,5), a tup of (2,2) is treated as (1,1,2,2)
<add>
<add>
<add> Examples:
<add> >>> a = array([0,1,2])
<add> >>> tile(a,2)
<add> array([0, 1, 2, 0, 1, 2])
<add> >>> tile(a,(1,2))
<add> array([[0, 1, 2, 0, 1, 2]])
<add> >>> tile(a,(2,2))
<add> array([[0, 1, 2, 0, 1, 2],
<add> [0, 1, 2, 0, 1, 2]])
<add> >>> tile(a,(2,1,2))
<add> array([[[0, 1, 2, 0, 1, 2]],
<add>
<add> [[0, 1, 2, 0, 1, 2]]])
<add>
<add> See Also:
<add> repeat
<add> """
<add> try:
<add> tup = tuple(reps)
<add> except TypeError:
<add> tup = (reps,)
<add> d = len(tup)
<add> c = _nx.array(A,copy=False,subok=True,ndmin=d)
<add> shape = list(c.shape)
<add> n = c.size
<add> if (d < A.ndim):
<add> tup = (1,)*(A.ndim-d) + tup
<add> for i, nrep in enumerate(tup):
<add> if nrep!=1:
<add> c = c.reshape(-1,n).repeat(nrep,0)
<add> dim_in = shape[i]
<add> dim_out = dim_in*nrep
<add> shape[i] = dim_out
<add> n /= dim_in
<add> return c.reshape(shape)
<add>
<ide><path>numpy/matlib.py
<ide> __version__ = N.__version__
<ide>
<ide> __all__ = N.__all__[:] # copy numpy namespace
<del>__all__ += ['rand', 'randn']
<add>__all__ += ['rand', 'randn', 'repmat']
<ide>
<ide> def empty(shape, dtype=None, order='C'):
<ide> """return an empty matrix of the given shape
<ide> def randn(*args):
<ide> args = args[0]
<ide> return asmatrix(N.random.randn(*args))
<ide>
<del>
<add>def repmat(a, m, n):
<add> """Repeat a 0-d to 2-d array mxn times
<add> """
<add> a = asanyarray(a)
<add> ndim = a.ndim
<add> if ndim == 0:
<add> origrows, origcols = (1,1)
<add> elif ndim == 1:
<add> origrows, origcols = (1, a.shape[0])
<add> else:
<add> origrows, origcols = a.shape
<add> rows = origrows * m
<add> cols = origcols * n
<add> c = a.reshape(1,a.size).repeat(m, 0).reshape(rows, origcols).repeat(n,0)
<add> return c.reshape(rows, cols) | 2 |
PHP | PHP | add connection support to validator | 2f00d46fdb502272644f9c55851df22e99935c9b | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'unique');
<ide>
<del> $table = $parameters[0];
<add> list($connection, $table) = $this->parseUniqueTable($parameters[0]);
<ide>
<ide> // The second parameter position holds the name of the column that needs to
<ide> // be verified as unique. If this parameter isn't specified we will just
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> // data store like Redis, etc. We will use it to determine uniqueness.
<ide> $verifier = $this->getPresenceVerifier();
<ide>
<add> if (! is_null($connection)) {
<add> $verifier->setConnection($connection);
<add> }
<add>
<ide> $extra = $this->getUniqueExtra($parameters);
<ide>
<ide> return $verifier->getCount(
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> ) == 0;
<ide> }
<ide>
<add> /**
<add> * Parse the connection / table for the unique rule.
<add> *
<add> * @param string $table
<add> * @return array
<add> */
<add> protected function parseUniqueTable($table)
<add> {
<add> return str_contains($table, '.') ? explode('.', $table, 2) : [null, $table];
<add> }
<add>
<ide> /**
<ide> * Get the excluded ID column and value for the unique rule.
<ide> *
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateUnique()
<ide> $v->setPresenceVerifier($mock);
<ide> $this->assertTrue($v->passes());
<ide>
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, array('email' => 'foo'), array('email' => 'Unique:connection.users'));
<add> $mock = m::mock('Illuminate\Validation\PresenceVerifierInterface');
<add> $mock->shouldReceive('setConnection')->once()->with('connection');
<add> $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, array())->andReturn(0);
<add> $v->setPresenceVerifier($mock);
<add> $this->assertTrue($v->passes());
<add>
<ide> $v = new Validator($trans, array('email' => 'foo'), array('email' => 'Unique:users,email_addr,1'));
<ide> $mock2 = m::mock('Illuminate\Validation\PresenceVerifierInterface');
<ide> $mock2->shouldReceive('getCount')->once()->with('users', 'email_addr', 'foo', '1', 'id', array())->andReturn(1); | 2 |
Javascript | Javascript | make cluster tests more time tolerant | 2853f9894fcecef5979d7ec2618c79760532253c | <ide><path>test/parallel/test-cluster-master-error.js
<ide> if (cluster.isWorker) {
<ide> existMaster = !!code;
<ide>
<ide> // Give the workers time to shut down
<del> setTimeout(checkWorkers, 200);
<add> var timeout = 200;
<add> if (common.isAix) {
<add> // AIX needs more time due to default exit performance
<add> timeout = 1000;
<add> }
<add> setTimeout(checkWorkers, timeout);
<ide>
<ide> function checkWorkers() {
<ide> // When master is dead all workers should be dead to
<ide><path>test/parallel/test-cluster-master-kill.js
<ide> if (cluster.isWorker) {
<ide> assert.equal(code, 0);
<ide>
<ide> // check worker process status
<add> var timeout = 200;
<add> if (common.isAix) {
<add> // AIX needs more time due to default exit performance
<add> timeout = 1000;
<add> }
<ide> setTimeout(function() {
<ide> alive = isAlive(pid);
<del> }, 200);
<add> }, timeout);
<ide> });
<ide>
<ide> process.once('exit', function() { | 2 |
Mixed | Javascript | use new technique to keep 3d and scrolling in sync | 914b48a7b76e291c3d1a4f34514f3a9b9243624e | <ide><path>threejs/lessons/resources/threejs-primitives.js
<ide> function main() {
<ide> return addElem(parent, 'div', className);
<ide> }
<ide>
<del> const renderFuncs = [
<add> const primRenderFuncs = [
<ide> ...[...document.querySelectorAll('[data-primitive]')].map(createPrimitiveDOM),
<ide> ...[...document.querySelectorAll('[data-primitive-diagram]')].map(createPrimitiveDiagram),
<ide> ];
<ide> function main() {
<ide>
<ide> renderer.setScissorTest(true);
<ide>
<del> renderFuncs.forEach((fn) => {
<del> fn(renderer, time);
<add> // maybe there is another way. Originally I used `position: fixed`
<add> // but the problem is if we can't render as fast as the browser
<add> // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
<add> // horrible but iOS would often been 1/2 a second or worse.
<add> // By doing it this way the canvas will scroll which means the
<add> // worse that happens is part of the shapes scrolling on don't
<add> // get drawn for a few frames but the shapes that are on the screen
<add> // scroll perfectly.
<add> //
<add> // I'm using `transform` on the voodoo that it doesn't affect
<add> // layout as much as `top` since AFAIK setting `top` is in
<add> // the flow but `transform` is not though thinking about it
<add> // the given we're `position: absolute` maybe there's no difference?
<add> const transform = `translateY(${window.scrollY}px)`;
<add> renderer.domElement.style.transform = transform;
<add>
<add> primRenderFuncs.forEach((fn) => {
<add> fn(renderer, time);
<ide> });
<ide>
<ide> requestAnimationFrame(render);
<ide><path>threejs/lessons/threejs-primitives.md
<ide> to use it](threejs-scenegraph.html).
<ide> flex: 1 1 auto;
<ide> }
<ide> #c {
<del> position: fixed;
<add> position: absolute;
<ide> top: 0;
<ide> left: 0;
<ide> width: 100vw; | 2 |
Text | Text | fix 404 links in react 18 docs | ae3e55dca471178ef0ceccfd7a6357b09f9a24cf | <ide><path>docs/advanced-features/react-18/overview.md
<ide> You can now start using React 18's new APIs like `startTransition` and `Suspense
<ide>
<ide> Streaming server-rendering (SSR) is an experimental feature in Next.js 12. When enabled, SSR will use the same [Edge Runtime](/docs/api-reference/edge-runtime.md) as [Middleware](/docs/middleware.md).
<ide>
<del>[Learn how to enable streaming in Next.js.](/docs/react-18/streaming.md)
<add>[Learn how to enable streaming in Next.js.](/docs/advanced-features/react-18/streaming.md)
<ide>
<ide> ## React Server Components (Alpha)
<ide>
<ide> Server Components are a new feature in React that let you reduce your JavaScript bundle size by separating server and client-side code. Server Components allow developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.
<ide>
<del>Server Components are still in research and development. [Learn how to try Server Components](/docs/react-18/server-components.md) as an experimental feature in Next.js.
<add>Server Components are still in research and development. [Learn how to try Server Components](/docs/advanced-features/react-18/server-components.md) as an experimental feature in Next.js. | 1 |
Text | Text | remove unsupported taps | d72bdd7efe7cfc37c7feda735bbe0aa87eb5e912 | <ide><path>docs/Interesting-Taps-and-Forks.md
<ide> Homebrew has the capability to add (and remove) multiple taps to your local inst
<ide> Your taps are Git repositories located at `$(brew --repository)/Library/Taps`.
<ide>
<ide> ## Unsupported interesting taps
<del>* [homebrew-ffmpeg/ffmpeg](https://github.com/homebrew-ffmpeg/homebrew-ffmpeg): A tap for FFmpeg with additional options, including nonfree additions.
<add>* [homebrew-ffmpeg/ffmpeg](https://github.com/homebrew-ffmpeg/homebrew-ffmpeg): A tap for FFmpeg with additional options, including nonfree additions.
<ide>
<ide> * [denji/nginx](https://github.com/denji/homebrew-nginx): A tap for NGINX modules, intended for its `nginx-full` formula which includes more module options.
<ide>
<ide> Your taps are Git repositories located at `$(brew --repository)/Library/Taps`.
<ide>
<ide> * [petere/postgresql](https://github.com/petere/homebrew-postgresql): Allows installing multiple PostgreSQL versions in parallel.
<ide>
<del>* [titanous/gnuradio](https://github.com/titanous/homebrew-gnuradio): GNU Radio and friends running on macOS.
<del>
<del>* [dunn/emacs](https://github.com/dunn/homebrew-emacs): A tap for Emacs packages.
<del>
<del>* [sidaf/pentest](https://github.com/sidaf/homebrew-pentest): Tools for penetration testing.
<del>
<ide> * [osrf/simulation](https://github.com/osrf/homebrew-simulation): Tools for robotics simulation.
<ide>
<ide> * [brewsci/bio](https://github.com/brewsci/homebrew-bio): Bioinformatics formulae. | 1 |
PHP | PHP | add a space after the comma in the $merge array | c8326460a46e563816ebfe7d9a13c475c2f0be63 | <ide><path>lib/Cake/Model/Model.php
<ide> public function __construct($id = false, $table = null, $ds = null) {
<ide> }
<ide>
<ide> if (is_subclass_of($this, 'AppModel')) {
<del> $merge = array('actsAs','findMethods');
<add> $merge = array('actsAs', 'findMethods');
<ide> $parentClass = get_parent_class($this);
<ide> if ($parentClass !== 'AppModel') {
<ide> $this->_mergeVars($merge, $parentClass); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.