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
PHP
PHP
fix paginator limit if query string exists
7718399b6c8bc3fefa39f22d4a50dda2eafb3bc5
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function limitControl(array $limits = [], $default = null, array $options <ide> $out .= $this->Form->control('limit', $options + [ <ide> 'type' => 'select', <ide> 'label' => __('View'), <del> 'value' => $default, <add> 'default' => $default, <add> 'value' => $this->_View->getRequest()->getQuery('limit'), <ide> 'options' => $limits, <ide> 'onChange' => 'this.form.submit()' <ide> ]); <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testLimitControl() <ide> ]; <ide> $this->assertHtml($expected, $out); <ide> } <add> <add> /** <add> * test the limitControl() method with defaults and query <add> * <add> * @return void <add> */ <add> public function testLimitControlQuery() <add> { <add> $out = $this->Paginator->limitControl([], 50); <add> $expected = [ <add> ['form' => ['method' => 'get', 'accept-charset' => 'utf-8', 'action' => '/']], <add> ['div' => ['class' => 'input select']], <add> ['label' => ['for' => 'limit']], <add> 'View', <add> '/label', <add> ['select' => ['name' => 'limit', 'id' => 'limit', 'onChange' => 'this.form.submit()']], <add> ['option' => ['value' => '20']], <add> '20', <add> '/option', <add> ['option' => ['value' => '50', 'selected' => 'selected']], <add> '50', <add> '/option', <add> ['option' => ['value' => '100']], <add> '100', <add> '/option', <add> '/select', <add> '/div', <add> '/form' <add> ]; <add> $this->assertHtml($expected, $out); <add> <add> $this->View->setRequest($this->View->getRequest()->withQueryParams(['limit' => '100'])); <add> $out = $this->Paginator->limitControl([], 50); <add> $expected = [ <add> ['form' => ['method' => 'get', 'accept-charset' => 'utf-8', 'action' => '/']], <add> ['div' => ['class' => 'input select']], <add> ['label' => ['for' => 'limit']], <add> 'View', <add> '/label', <add> ['select' => ['name' => 'limit', 'id' => 'limit', 'onChange' => 'this.form.submit()']], <add> ['option' => ['value' => '20']], <add> '20', <add> '/option', <add> ['option' => ['value' => '50']], <add> '50', <add> '/option', <add> ['option' => ['value' => '100', 'selected' => 'selected']], <add> '100', <add> '/option', <add> '/select', <add> '/div', <add> '/form' <add> ]; <add> $this->assertHtml($expected, $out); <add> } <ide> }
2
PHP
PHP
apply fixes from styleci
96ed7ba166f8c2ba95d433b7e22d62f011fc6046
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function take($limit) <ide> } <ide> <ide> /** <del> * Take items in the collection until the given condition is met. <del> * <del> * @param mixed $key <del> * @return static <del> */ <del> public function takeUntil($value) <del> { <del> return new static($this->lazy()->takeUntil($value)->all()); <del> } <del> <del> /** <del> * Take items in the collection while the given condition is met. <del> * <del> * @param mixed $key <del> * @return static <del> */ <del> public function takeWhile($value) <del> { <del> return new static($this->lazy()->takeWhile($value)->all()); <del> } <add> * Take items in the collection until the given condition is met. <add> * <add> * @param mixed $key <add> * @return static <add> */ <add> public function takeUntil($value) <add> { <add> return new static($this->lazy()->takeUntil($value)->all()); <add> } <add> <add> /** <add> * Take items in the collection while the given condition is met. <add> * <add> * @param mixed $key <add> * @return static <add> */ <add> public function takeWhile($value) <add> { <add> return new static($this->lazy()->takeWhile($value)->all()); <add> } <ide> <ide> /** <ide> * Transform each item in the collection using a callback. <ide><path>src/Illuminate/Collections/LazyCollection.php <ide> public function take($limit) <ide> } <ide> <ide> /** <del> * Take items in the collection until the given condition is met. <del> * <del> * @param mixed $key <del> * @return static <del> */ <del> public function takeUntil($value) <del> { <del> $callback = $this->useAsCallable($value) ? $value : $this->equality($value); <del> <del> return new static(function () use ($callback) { <del> foreach ($this as $key => $item) { <del> if ($callback($item, $key)) { <del> break; <del> } <del> <del> yield $key => $item; <del> } <del> }); <del> } <del> <del> /** <del> * Take items in the collection while the given condition is met. <del> * <del> * @param mixed $key <del> * @return static <del> */ <del> public function takeWhile($value) <del> { <del> $callback = $this->useAsCallable($value) ? $value : $this->equality($value); <del> <del> return $this->takeUntil(function ($item, $key) use ($callback) { <del> return ! $callback($item, $key); <del> }); <del> } <add> * Take items in the collection until the given condition is met. <add> * <add> * @param mixed $key <add> * @return static <add> */ <add> public function takeUntil($value) <add> { <add> $callback = $this->useAsCallable($value) ? $value : $this->equality($value); <add> <add> return new static(function () use ($callback) { <add> foreach ($this as $key => $item) { <add> if ($callback($item, $key)) { <add> break; <add> } <add> <add> yield $key => $item; <add> } <add> }); <add> } <add> <add> /** <add> * Take items in the collection while the given condition is met. <add> * <add> * @param mixed $key <add> * @return static <add> */ <add> public function takeWhile($value) <add> { <add> $callback = $this->useAsCallable($value) ? $value : $this->equality($value); <add> <add> return $this->takeUntil(function ($item, $key) use ($callback) { <add> return ! $callback($item, $key); <add> }); <add> } <ide> <ide> /** <ide> * Pass each item in the collection to the given callback, lazily.
2
Go
Go
remove defensive check of mux vars handling
389ce0aae6a303660e591ef80272322ac82854e2
<ide><path>api/server/httputils/form.go <ide> type ArchiveOptions struct { <ide> // ArchiveFormValues parses form values and turns them into ArchiveOptions. <ide> // It fails if the archive name and path are not in the request. <ide> func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions, error) { <del> if vars == nil { <del> return ArchiveOptions{}, fmt.Errorf("Missing parameter") <del> } <ide> if err := ParseForm(r); err != nil { <ide> return ArchiveOptions{}, err <ide> } <ide><path>api/server/router/local/container.go <ide> func (s *router) getContainersStats(ctx context.Context, w http.ResponseWriter, <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> stream := httputils.BoolValueOrDefault(r, "stream", true) <ide> var out io.Writer <ide> func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> // Args are validated before the stream starts because when it starts we're <ide> // sending HTTP 200 by writing an empty chunk of data to tell the client that <ide> func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> } <ide> <ide> func (s *router) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> return s.daemon.ContainerExport(vars["name"], w) <ide> } <ide> <ide> func (s *router) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> // If contentLength is -1, we can assumed chunked encoding <ide> // or more technically that the length is unknown <ide> // https://golang.org/src/pkg/net/http/request.go#L139 <ide> func (s *router) postContainersStop(ctx context.Context, w http.ResponseWriter, <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> seconds, _ := strconv.Atoi(r.Form.Get("t")) <ide> <ide> func (s *router) postContainersStop(ctx context.Context, w http.ResponseWriter, <ide> } <ide> <ide> func (s *router) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersRestart(ctx context.Context, w http.ResponseWrite <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> timeout, _ := strconv.Atoi(r.Form.Get("t")) <ide> <ide> func (s *router) postContainersRestart(ctx context.Context, w http.ResponseWrite <ide> } <ide> <ide> func (s *router) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersPause(ctx context.Context, w http.ResponseWriter, <ide> } <ide> <ide> func (s *router) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersUnpause(ctx context.Context, w http.ResponseWrite <ide> } <ide> <ide> func (s *router) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second) <ide> if err != nil { <ide> return err <ide> func (s *router) postContainersWait(ctx context.Context, w http.ResponseWriter, <ide> } <ide> <ide> func (s *router) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> changes, err := s.daemon.ContainerChanges(vars["name"]) <ide> if err != nil { <ide> return err <ide> func (s *router) getContainersChanges(ctx context.Context, w http.ResponseWriter <ide> } <ide> <ide> func (s *router) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainerRename(ctx context.Context, w http.ResponseWriter, <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> name := vars["name"] <ide> newName := r.Form.Get("name") <ide> func (s *router) deleteContainers(ctx context.Context, w http.ResponseWriter, r <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> name := vars["name"] <ide> config := &daemon.ContainerRmConfig{ <ide> func (s *router) postContainersResize(ctx context.Context, w http.ResponseWriter <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> height, err := strconv.Atoi(r.Form.Get("h")) <ide> if err != nil { <ide> func (s *router) postContainersAttach(ctx context.Context, w http.ResponseWriter <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> containerName := vars["name"] <ide> <ide> if !s.daemon.Exists(containerName) { <ide> func (s *router) wsContainersAttach(ctx context.Context, w http.ResponseWriter, <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> containerName := vars["name"] <ide> <ide> if !s.daemon.Exists(containerName) { <ide><path>api/server/router/local/copy.go <ide> import ( <ide> <ide> // postContainersCopy is deprecated in favor of getContainersArchive. <ide> func (s *router) postContainersCopy(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> if err := httputils.CheckForJSON(r); err != nil { <ide> return err <ide> } <ide><path>api/server/router/local/exec.go <ide> import ( <ide> ) <ide> <ide> func (s *router) getExecByID(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter 'id'") <del> } <del> <ide> eConfig, err := s.daemon.ContainerExecInspect(vars["id"]) <ide> if err != nil { <ide> return err <ide> func (s *router) postContainerExecResize(ctx context.Context, w http.ResponseWri <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> height, err := strconv.Atoi(r.Form.Get("h")) <ide> if err != nil { <ide> return err <ide><path>api/server/router/local/image.go <ide> func (s *router) postImagesCreate(ctx context.Context, w http.ResponseWriter, r <ide> } <ide> <ide> func (s *router) postImagesPush(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> metaHeaders := map[string][]string{} <ide> for k, v := range r.Header { <ide> if strings.HasPrefix(k, "X-Meta-") { <ide> func (s *router) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h <ide> } <ide> <ide> func (s *router) getImagesGet(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) deleteImages(ctx context.Context, w http.ResponseWriter, r *htt <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> name := vars["name"] <ide> <ide> func (s *router) deleteImages(ctx context.Context, w http.ResponseWriter, r *htt <ide> } <ide> <ide> func (s *router) getImagesByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> imageInspect, err := s.daemon.LookupImage(vars["name"]) <ide> if err != nil { <ide> return err <ide> func (s *router) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht <ide> } <ide> <ide> func (s *router) getImagesHistory(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> name := vars["name"] <ide> history, err := s.daemon.ImageHistory(name) <ide> if err != nil { <ide> func (s *router) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <del> <ide> repo := r.Form.Get("repo") <ide> tag := r.Form.Get("tag") <ide> name := vars["name"] <ide><path>api/server/router/local/inspect.go <ide> package local <ide> <ide> import ( <del> "fmt" <ide> "net/http" <ide> <ide> "github.com/docker/docker/api/server/httputils" <ide> import ( <ide> // getContainersByName inspects containers configuration and serializes it as json. <ide> func (s *router) getContainersByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> displaySize := httputils.BoolValue(r, "size") <del> if vars == nil { <del> return fmt.Errorf("Missing parameter") <del> } <ide> <ide> var json interface{} <ide> var err error <ide><path>api/server/server.go <ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc { <ide> ctx := context.Background() <ide> handlerFunc := s.handleWithGlobalMiddlewares(handler) <ide> <del> if err := handlerFunc(ctx, w, r, mux.Vars(r)); err != nil { <add> vars := mux.Vars(r) <add> if vars == nil { <add> vars = make(map[string]string) <add> } <add> <add> if err := handlerFunc(ctx, w, r, vars); err != nil { <ide> logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL.Path, utils.GetErrorMessage(err)) <ide> httputils.WriteError(w, err) <ide> }
7
Javascript
Javascript
add support for local vars in expressions
761b2ed85ad9685c35f85513e17363abf17ce6b3
<ide><path>src/service/parse.js <ide> 'use strict'; <ide> <ide> var OPERATORS = { <del> 'null':function(self){return null;}, <del> 'true':function(self){return true;}, <del> 'false':function(self){return false;}, <add> 'null':function(){return null;}, <add> 'true':function(){return true;}, <add> 'false':function(){return false;}, <ide> undefined:noop, <del> '+':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, <del> '-':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, <del> '*':function(self, a,b){return a(self)*b(self);}, <del> '/':function(self, a,b){return a(self)/b(self);}, <del> '%':function(self, a,b){return a(self)%b(self);}, <del> '^':function(self, a,b){return a(self)^b(self);}, <add> '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, <add> '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, <add> '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, <add> '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, <add> '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, <add> '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, <ide> '=':noop, <del> '==':function(self, a,b){return a(self)==b(self);}, <del> '!=':function(self, a,b){return a(self)!=b(self);}, <del> '<':function(self, a,b){return a(self)<b(self);}, <del> '>':function(self, a,b){return a(self)>b(self);}, <del> '<=':function(self, a,b){return a(self)<=b(self);}, <del> '>=':function(self, a,b){return a(self)>=b(self);}, <del> '&&':function(self, a,b){return a(self)&&b(self);}, <del> '||':function(self, a,b){return a(self)||b(self);}, <del> '&':function(self, a,b){return a(self)&b(self);}, <del>// '|':function(self, a,b){return a|b;}, <del> '|':function(self, a,b){return b(self)(self, a(self));}, <del> '!':function(self, a){return !a(self);} <add> '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, <add> '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, <add> '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, <add> '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, <add> '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, <add> '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, <add> '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, <add> '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, <add> '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, <add>// '|':function(self, locals, a,b){return a|b;}, <add> '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, <add> '!':function(self, locals, a){return !a(self, locals);} <ide> }; <ide> var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; <ide> <ide> function lex(text){ <ide> function readIdent() { <ide> var ident = "", <ide> start = index, <del> fn, lastDot, peekIndex, methodName; <add> fn, lastDot, peekIndex, methodName, getter; <ide> <ide> while (index < text.length) { <ide> var ch = text.charAt(index); <ide> function lex(text){ <ide> } <ide> <ide> fn = OPERATORS[ident]; <add> getter = getterFn(ident); <ide> tokens.push({ <ide> index:start, <ide> text:ident, <ide> json: fn, <del> fn:fn||extend(getterFn(ident), { <del> assign:function(self, value){ <del> return setter(self, ident, value); <del> } <del> }) <add> fn:fn||extend( <add> function(self, locals) { <add> return (getter(self, locals)); <add> }, <add> { <add> assign:function(self, value){ <add> return setter(self, ident, value); <add> } <add> } <add> ) <ide> }); <ide> <ide> if (methodName) { <ide> function parser(text, json, $filter){ <ide> value, <ide> tokens = lex(text), <ide> assignment = _assignment, <del> assignable = logicalOR, <ide> functionCall = _functionCall, <ide> fieldAccess = _fieldAccess, <ide> objectIndex = _objectIndex, <del> filterChain = _filterChain, <del> functionIdent = _functionIdent; <add> filterChain = _filterChain <ide> if(json){ <ide> // The extra level of aliasing is here, just in case the lexer misses something, so that <ide> // we prevent any accidental execution in JSON. <ide> assignment = logicalOR; <ide> functionCall = <ide> fieldAccess = <ide> objectIndex = <del> assignable = <ide> filterChain = <del> functionIdent = <ide> function() { throwError("is not valid json", {text:text, index:0}); }; <ide> value = primary(); <ide> } else { <ide> function parser(text, json, $filter){ <ide> } <ide> <ide> function unaryFn(fn, right) { <del> return function(self) { <del> return fn(self, right); <add> return function(self, locals) { <add> return fn(self, locals, right); <ide> }; <ide> } <ide> <ide> function binaryFn(left, fn, right) { <del> return function(self) { <del> return fn(self, left, right); <add> return function(self, locals) { <add> return fn(self, locals, left, right); <ide> }; <ide> } <ide> <ide> function parser(text, json, $filter){ <ide> // TODO(size): maybe we should not support multiple statements? <ide> return statements.length == 1 <ide> ? statements[0] <del> : function(self){ <add> : function(self, locals){ <ide> var value; <ide> for ( var i = 0; i < statements.length; i++) { <ide> var statement = statements[i]; <ide> if (statement) <del> value = statement(self); <add> value = statement(self, locals); <ide> } <ide> return value; <ide> }; <ide> function parser(text, json, $filter){ <ide> if ((token = expect(':'))) { <ide> argsFn.push(expression()); <ide> } else { <del> var fnInvoke = function(self, input){ <add> var fnInvoke = function(self, locals, input){ <ide> var args = [input]; <ide> for ( var i = 0; i < argsFn.length; i++) { <del> args.push(argsFn[i](self)); <add> args.push(argsFn[i](self, locals)); <ide> } <ide> return fn.apply(self, args); <ide> }; <ide> function parser(text, json, $filter){ <ide> text.substring(0, token.index) + "] can not be assigned to", token); <ide> } <ide> right = logicalOR(); <del> return function(self){ <del> return left.assign(self, right(self)); <add> return function(self, locals){ <add> return left.assign(self, right(self, locals), locals); <ide> }; <ide> } else { <ide> return left; <ide> function parser(text, json, $filter){ <ide> function _fieldAccess(object) { <ide> var field = expect().text; <ide> var getter = getterFn(field); <del> return extend(function(self){ <del> return getter(object(self)); <del> }, { <del> assign:function(self, value){ <del> return setter(object(self), field, value); <del> } <del> }); <add> return extend( <add> function(self, locals) { <add> return getter(object(self, locals), locals); <add> }, <add> { <add> assign:function(self, value, locals) { <add> return setter(object(self, locals), field, value); <add> } <add> } <add> ); <ide> } <ide> <ide> function _objectIndex(obj) { <ide> var indexFn = expression(); <ide> consume(']'); <ide> return extend( <del> function(self){ <del> var o = obj(self), <del> i = indexFn(self), <add> function(self, locals){ <add> var o = obj(self, locals), <add> i = indexFn(self, locals), <ide> v, p; <ide> <ide> if (!o) return undefined; <ide> function parser(text, json, $filter){ <ide> } <ide> return v; <ide> }, { <del> assign:function(self, value){ <del> return obj(self)[indexFn(self)] = value; <add> assign:function(self, value, locals){ <add> return obj(self, locals)[indexFn(self, locals)] = value; <ide> } <ide> }); <ide> } <ide> function parser(text, json, $filter){ <ide> } while (expect(',')); <ide> } <ide> consume(')'); <del> return function(self){ <add> return function(self, locals){ <ide> var args = [], <del> context = contextGetter ? contextGetter(self) : self; <add> context = contextGetter ? contextGetter(self, locals) : self; <ide> <ide> for ( var i = 0; i < argsFn.length; i++) { <del> args.push(argsFn[i](self)); <add> args.push(argsFn[i](self, locals)); <ide> } <del> var fnPtr = fn(self) || noop; <add> var fnPtr = fn(self, locals) || noop; <ide> // IE stupidity! <ide> return fnPtr.apply <ide> ? fnPtr.apply(context, args) <ide> function parser(text, json, $filter){ <ide> } while (expect(',')); <ide> } <ide> consume(']'); <del> return function(self){ <add> return function(self, locals){ <ide> var array = []; <ide> for ( var i = 0; i < elementFns.length; i++) { <del> array.push(elementFns[i](self)); <add> array.push(elementFns[i](self, locals)); <ide> } <ide> return array; <ide> }; <ide> function parser(text, json, $filter){ <ide> } while (expect(',')); <ide> } <ide> consume('}'); <del> return function(self){ <add> return function(self, locals){ <ide> var object = {}; <ide> for ( var i = 0; i < keyValues.length; i++) { <ide> var keyValue = keyValues[i]; <del> var value = keyValue.value(self); <add> var value = keyValue.value(self, locals); <ide> object[keyValue.key] = value; <ide> } <ide> return object; <ide> function getterFn(path) { <ide> if (fn) return fn; <ide> <ide> var code = 'var l, fn, p;\n'; <del> forEach(path.split('.'), function(key) { <add> forEach(path.split('.'), function(key, index) { <ide> code += 'if(!s) return s;\n' + <ide> 'l=s;\n' + <del> 's=s' + '["' + key + '"]' + ';\n' + <add> 's='+ (index <add> // we simply direference 's' on any .dot notation <add> ? 's' <add> // but if we are first then we check locals firs, and if so read it first <add> : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + <ide> 'if (s && s.then) {\n' + <ide> ' if (!("$$v" in s)) {\n' + <ide> ' p=s;\n' + <ide> function getterFn(path) { <ide> '}\n'; <ide> }); <ide> code += 'return s;'; <del> fn = Function('s', code); <add> fn = Function('s', 'k', code); <ide> fn.toString = function() { return code; }; <ide> <ide> return getterFnCache[path] = fn; <ide><path>test/service/parseSpec.js <ide> describe('parser', function() { <ide> expect(scope).toEqual({a:123}); <ide> })); <ide> }); <add> <add> <add> describe('locals', function() { <add> it('should expose local variables', inject(function($parse) { <add> expect($parse('a')({a: 0}, {a: 1})).toEqual(1); <add> expect($parse('add(a,b)')({b: 1, add: function(a, b) { return a + b; }}, {a: 2})).toEqual(3); <add> })); <add> <add> it('should expose traverse locals', inject(function($parse) { <add> expect($parse('a.b')({a: {b: 0}}, {a: {b:1}})).toEqual(1); <add> expect($parse('a.b')({a: null}, {a: {b:1}})).toEqual(1); <add> expect($parse('a.b')({a: {b: 0}}, {a: null})).toEqual(undefined); <add> })); <add> }); <ide> });
2
Python
Python
show warning if session cookie domain is ip
c3d49e29ea42d2f468bc780c15683ca197b50d02
<ide><path>flask/helpers.py <ide> def total_seconds(td): <ide> :rtype: int <ide> """ <ide> return td.days * 60 * 60 * 24 + td.seconds <add> <add>def is_ip(ip): <add> """Returns the if the string received is an IP or not. <add> <add> :param string: the string to check if it an IP or not <add> :param var_name: the name of the string that is being checked <add> <add> :returns: True if string is an IP, False if not <add> :rtype: boolean <add> """ <add> import socket <add> <add> for family in (socket.AF_INET, socket.AF_INET6): <add> try: <add> socket.inet_pton(family, ip) <add> except socket.error: <add> pass <add> else: <add> return True <add> return False <ide><path>flask/sessions.py <ide> <ide> import uuid <ide> import hashlib <add>from warnings import warn <ide> from base64 import b64encode, b64decode <ide> from datetime import datetime <ide> from werkzeug.http import http_date, parse_date <ide> from werkzeug.datastructures import CallbackDict <ide> from . import Markup, json <ide> from ._compat import iteritems, text_type <del>from .helpers import total_seconds <add>from .helpers import total_seconds, is_ip <ide> <ide> from itsdangerous import URLSafeTimedSerializer, BadSignature <ide> <ide> def open_session(self, app, request): <ide> <ide> def save_session(self, app, session, response): <ide> domain = self.get_cookie_domain(app) <add> if domain is not None: <add> if is_ip(domain): <add> warnings.warn("IP introduced in SESSION_COOKIE_DOMAIN", RuntimeWarning) <ide> path = self.get_cookie_path(app) <ide> <ide> # Delete case. If there is no session we bail early.
2
Ruby
Ruby
allow installation from urls
ea03121688a19c827f1da230ac90c37e29e77608
<ide><path>Library/Homebrew/extend/ARGV.rb <ide> def usage; <<-EOS.undent <ide> private <ide> <ide> def downcased_unique_named <del> @downcased_unique_named ||= named.map{|arg| arg.downcase}.uniq <add> # Only lowercase names, not paths or URLs <add> @downcased_unique_named ||= named.map do |arg| <add> arg.include?("/") ? arg : arg.downcase <add> end.uniq <ide> end <ide> end <ide><path>Library/Homebrew/formula.rb <ide> def detect_version <ide> class Formula <ide> include FileUtils <ide> <del> attr_reader :url, :version, :homepage, :name, :specs, :downloader <add> attr_reader :name, :path, :url, :version, :homepage, :specs, :downloader <ide> <ide> # Homebrew determines the name <del> def initialize name='__UNKNOWN__' <add> def initialize name='__UNKNOWN__', path=nil <ide> set_instance_variable 'homepage' <ide> set_instance_variable 'url' <ide> set_instance_variable 'head' <ide> def initialize name='__UNKNOWN__' <ide> @name=name <ide> validate_variable :name <ide> <add> @path=path <add> <ide> set_instance_variable 'version' <ide> @version ||= @spec_to_use.detect_version <ide> validate_variable :version if @version <ide> def installed_prefix <ide> end <ide> <ide> def path <del> self.class.path name <add> if @path.nil? <add> return self.class.path name <add> else <add> return @path <add> end <ide> end <ide> <ide> def prefix <ide> def self.aliases <ide> end <ide> <ide> def self.resolve_alias name <add> # Don't resolve paths or URLs <add> return name if name.include?("/") <add> <ide> aka = HOMEBREW_REPOSITORY+"Library/Aliases/#{name}" <ide> if aka.file? <ide> aka.realpath.basename('.rb').to_s <ide> def self.resolve_alias name <ide> end <ide> <ide> def self.factory name <add> # If an instance of Formula is passed, just return it <ide> return name if name.kind_of? Formula <del> path = Pathname.new(name) <del> if path.absolute? <del> require name <del> name = path.stem <add> <add> # If a URL is passed, download to the cache and install <add> if name =~ %r[(https?|ftp)://] <add> url = name <add> name = Pathname.new(name).basename <add> target_file = (HOMEBREW_CACHE+"Formula"+name) <add> name = name.basename(".rb").to_s <add> <add> (HOMEBREW_CACHE+"Formula").mkpath <add> FileUtils.rm target_file, :force => true <add> curl url, '-o', target_file <add> <add> require target_file <add> install_type = :from_url <ide> else <del> require self.path(name) <add> # Check if this is a name or pathname <add> path = Pathname.new(name) <add> if path.absolute? <add> # For absolute paths, just require the path <add> require name <add> name = path.stem <add> install_type = :from_path <add> else <add> # For names, map to the path and then require <add> require self.path(name) <add> install_type = :from_name <add> end <ide> end <add> <ide> begin <ide> klass_name = self.class_s(name) <ide> klass = eval(klass_name) <ide> def self.factory name <ide> puts "Double-check the name of the class in that formula." <ide> raise LoadError <ide> end <del> return klass.new(name) <add> <add> return klass.new(name) if install_type == :from_name <add> return klass.new(name, target_file) <ide> rescue LoadError <ide> raise FormulaUnavailableError.new(name) <ide> end
2
Text
Text
fix incorrect sentence
934fb7ae60edd31a3b6153bfce399ceec12b3e75
<ide><path>guide/english/javascript/assignment-operators/index.md <ide> title: Assignment Operators <ide> <ide> # Assignment Operators <ide> <del>Assignment operators, as the name suggests, assign (or re-assign) values to a variable. While there are quite a few variations on the assignment operators, they all build off of the basic assignment operator. <add>Assignment operators, as the name suggests, assign (or re-assign) values to a variable. While there are quite a few variations of assignment operators, they all build off of the basic assignment operator. <ide> <ide> ## Syntax <ide>
1
Mixed
Javascript
add cdn support with assetprefix
dec85fe6c4c5360aced57d75f9cea78ed388f2f8
<ide><path>client/index.js <ide> import mitt from 'mitt' <ide> import HeadManager from './head-manager' <ide> import { createRouter } from '../lib/router' <ide> import App from '../lib/app' <del>import evalScript from '../lib/eval-script' <ide> import { loadGetInitialProps, getURL } from '../lib/utils' <ide> import ErrorDebugComponent from '../lib/error-debug' <add>import PageLoader from '../lib/page-loader' <ide> <ide> // Polyfill Promise globally <ide> // This is needed because Webpack2's dynamic loading(common chunks) code <ide> if (!window.Promise) { <ide> <ide> const { <ide> __NEXT_DATA__: { <del> component, <del> errorComponent, <ide> props, <ide> err, <ide> pathname, <del> query <add> query, <add> buildId, <add> assetPrefix <ide> }, <ide> location <ide> } = window <ide> <del>const Component = evalScript(component).default <del>const ErrorComponent = evalScript(errorComponent).default <del>let lastAppProps <del> <del>export const router = createRouter(pathname, query, getURL(), { <del> Component, <del> ErrorComponent, <del> err <add>const pageLoader = new PageLoader(buildId, assetPrefix) <add>window.__NEXT_LOADED_PAGES__.forEach(({ route, fn }) => { <add> pageLoader.registerPage(route, fn) <ide> }) <add>delete window.__NEXT_LOADED_PAGES__ <add> <add>window.__NEXT_REGISTER_PAGE = pageLoader.registerPage.bind(pageLoader) <ide> <ide> const headManager = new HeadManager() <ide> const appContainer = document.getElementById('__next') <ide> const errorContainer = document.getElementById('__next-error') <ide> <del>export default () => { <add>let lastAppProps <add>export let router <add>export let ErrorComponent <add>let Component <add> <add>export default async () => { <add> ErrorComponent = await pageLoader.loadPage('/_error') <add> <add> try { <add> Component = await pageLoader.loadPage(pathname) <add> } catch (err) { <add> console.error(`${err.message}\n${err.stack}`) <add> Component = ErrorComponent <add> } <add> <add> router = createRouter(pathname, query, getURL(), { <add> pageLoader, <add> Component, <add> ErrorComponent, <add> err <add> }) <add> <ide> const emitter = mitt() <ide> <ide> router.subscribe(({ Component, props, hash, err }) => { <ide> export default () => { <ide> } <ide> <ide> export async function render (props) { <del> if (props.err) { <add> // There are some errors we should ignore. <add> // Next.js rendering logic knows how to handle them. <add> // These are specially 404 errors <add> if (props.err && !props.err.ignore) { <ide> await renderError(props.err) <ide> return <ide> } <ide> async function doRender ({ Component, props, hash, err, emitter }) { <ide> } <ide> <ide> if (emitter) { <del> emitter.emit('before-reactdom-render', { Component }) <add> emitter.emit('before-reactdom-render', { Component, ErrorComponent }) <ide> } <ide> <ide> Component = Component || lastAppProps.Component <ide> async function doRender ({ Component, props, hash, err, emitter }) { <ide> ReactDOM.render(createElement(App, appProps), appContainer) <ide> <ide> if (emitter) { <del> emitter.emit('after-reactdom-render', { Component }) <add> emitter.emit('after-reactdom-render', { Component, ErrorComponent }) <ide> } <ide> } <ide><path>client/next-dev.js <del>import evalScript from '../lib/eval-script' <add>import 'react-hot-loader/patch' <ide> import ReactReconciler from 'react-dom/lib/ReactReconciler' <del> <del>const { __NEXT_DATA__: { errorComponent } } = window <del>const ErrorComponent = evalScript(errorComponent).default <del> <del>require('react-hot-loader/patch') <add>import initOnDemandEntries from './on-demand-entries-client' <add>import initWebpackHMR from './webpack-hot-middleware-client' <ide> <ide> const next = window.next = require('./') <ide> <del>const emitter = next.default() <add>next.default() <add> .then((emitter) => { <add> initOnDemandEntries() <add> initWebpackHMR() <add> <add> let lastScroll <add> <add> emitter.on('before-reactdom-render', ({ Component, ErrorComponent }) => { <add> // Remember scroll when ErrorComponent is being rendered to later restore it <add> if (!lastScroll && Component === ErrorComponent) { <add> const { pageXOffset, pageYOffset } = window <add> lastScroll = { <add> x: pageXOffset, <add> y: pageYOffset <add> } <add> } <add> }) <add> <add> emitter.on('after-reactdom-render', ({ Component, ErrorComponent }) => { <add> if (lastScroll && Component !== ErrorComponent) { <add> // Restore scroll after ErrorComponent was replaced with a page component by HMR <add> const { x, y } = lastScroll <add> window.scroll(x, y) <add> lastScroll = null <add> } <add> }) <add> }) <add> .catch((err) => { <add> console.error(`${err.message}\n${err.stack}`) <add> }) <ide> <ide> // This is a patch to catch most of the errors throw inside React components. <ide> const originalMountComponent = ReactReconciler.mountComponent <ide> ReactReconciler.mountComponent = function (...args) { <ide> throw err <ide> } <ide> } <del> <del>let lastScroll <del> <del>emitter.on('before-reactdom-render', ({ Component }) => { <del> // Remember scroll when ErrorComponent is being rendered to later restore it <del> if (!lastScroll && Component === ErrorComponent) { <del> const { pageXOffset, pageYOffset } = window <del> lastScroll = { <del> x: pageXOffset, <del> y: pageYOffset <del> } <del> } <del>}) <del> <del>emitter.on('after-reactdom-render', ({ Component }) => { <del> if (lastScroll && Component !== ErrorComponent) { <del> // Restore scroll after ErrorComponent was replaced with a page component by HMR <del> const { x, y } = lastScroll <del> window.scroll(x, y) <del> lastScroll = null <del> } <del>}) <ide><path>client/next.js <ide> import next from './' <ide> <ide> next() <add> .catch((err) => { <add> console.error(`${err.message}\n${err.stack}`) <add> }) <ide><path>client/on-demand-entries-client.js <ide> import Router from '../lib/router' <ide> import fetch from 'unfetch' <ide> <del>Router.ready(() => { <del> Router.router.events.on('routeChangeComplete', ping) <del>}) <add>export default () => { <add> Router.ready(() => { <add> Router.router.events.on('routeChangeComplete', ping) <add> }) <ide> <del>async function ping () { <del> try { <del> const url = `/_next/on-demand-entries-ping?page=${Router.pathname}` <del> const res = await fetch(url) <del> const payload = await res.json() <del> if (payload.invalid) { <del> location.reload() <add> async function ping () { <add> try { <add> const url = `/_next/on-demand-entries-ping?page=${Router.pathname}` <add> const res = await fetch(url) <add> const payload = await res.json() <add> if (payload.invalid) { <add> location.reload() <add> } <add> } catch (err) { <add> console.error(`Error with on-demand-entries-ping: ${err.message}`) <ide> } <del> } catch (err) { <del> console.error(`Error with on-demand-entries-ping: ${err.message}`) <ide> } <del>} <ide> <del>async function runPinger () { <del> while (true) { <del> await new Promise((resolve) => setTimeout(resolve, 5000)) <del> await ping() <add> async function runPinger () { <add> while (true) { <add> await new Promise((resolve) => setTimeout(resolve, 5000)) <add> await ping() <add> } <ide> } <del>} <ide> <del>runPinger() <del> .catch((err) => { <del> console.error(err) <del> }) <add> runPinger() <add> .catch((err) => { <add> console.error(err) <add> }) <add>} <ide><path>client/webpack-hot-middleware-client.js <ide> import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?overlay=false&reload=true&path=/_next/webpack-hmr' <ide> import Router from '../lib/router' <ide> <del>const handlers = { <del> reload (route) { <del> if (route === '/_error') { <del> for (const r of Object.keys(Router.components)) { <del> const { err } = Router.components[r] <del> if (err) { <del> // reload all error routes <del> // which are expected to be errors of '/_error' routes <del> Router.reload(r) <add>export default () => { <add> const handlers = { <add> reload (route) { <add> if (route === '/_error') { <add> for (const r of Object.keys(Router.components)) { <add> const { err } = Router.components[r] <add> if (err) { <add> // reload all error routes <add> // which are expected to be errors of '/_error' routes <add> Router.reload(r) <add> } <ide> } <add> return <ide> } <del> return <del> } <ide> <del> if (route === '/_document') { <del> window.location.reload() <del> return <del> } <add> if (route === '/_document') { <add> window.location.reload() <add> return <add> } <ide> <del> Router.reload(route) <del> }, <add> Router.reload(route) <add> }, <ide> <del> change (route) { <del> if (route === '/_document') { <del> window.location.reload() <del> return <del> } <add> change (route) { <add> if (route === '/_document') { <add> window.location.reload() <add> return <add> } <ide> <del> const { err } = Router.components[route] || {} <del> if (err) { <del> // reload to recover from runtime errors <del> Router.reload(route) <add> const { err } = Router.components[route] || {} <add> if (err) { <add> // reload to recover from runtime errors <add> Router.reload(route) <add> } <ide> } <ide> } <del>} <ide> <del>webpackHotMiddlewareClient.subscribe((obj) => { <del> const fn = handlers[obj.action] <del> if (fn) { <del> const data = obj.data || [] <del> fn(...data) <del> } else { <del> throw new Error('Unexpected action ' + obj.action) <del> } <del>}) <add> webpackHotMiddlewareClient.subscribe((obj) => { <add> const fn = handlers[obj.action] <add> if (fn) { <add> const data = obj.data || [] <add> fn(...data) <add> } else { <add> throw new Error('Unexpected action ' + obj.action) <add> } <add> }) <add>} <ide><path>lib/error.js <ide> import HTTPStatus from 'http-status' <ide> import Head from './head' <ide> <ide> export default class Error extends React.Component { <del> static getInitialProps ({ res, jsonPageRes }) { <del> const statusCode = res ? res.statusCode : (jsonPageRes ? jsonPageRes.status : null) <add> static getInitialProps ({ res, err }) { <add> const statusCode = res ? res.statusCode : (err ? err.statusCode : null) <ide> return { statusCode } <ide> } <ide> <ide><path>lib/eval-script.js <del>/** <del> * IMPORTANT: This module is compiled *without* `use strict` <del> * so that when we `eval` a dependency below, we don't enforce <del> * `use strict` implicitly. <del> * <del> * Otherwise, modules like `d3` get `eval`d and forced into <del> * `use strict` where they don't work (at least in current versions) <del> * <del> * To see the compilation details, look at `flyfile.js` and the <del> * usage of `babel-plugin-transform-remove-strict-mode`. <del> */ <del> <del>export default function evalScript (script) { <del> const module = { exports: {} } <del> <del> eval(script) // eslint-disable-line no-eval <del> return module.exports <del>} <ide><path>lib/page-loader.js <add>/* global window, document */ <add>import mitt from 'mitt' <add> <add>const webpackModule = module <add> <add>export default class PageLoader { <add> constructor (buildId, assetPrefix) { <add> this.buildId = buildId <add> this.assetPrefix = assetPrefix <add> <add> this.pageCache = {} <add> this.pageLoadedHandlers = {} <add> this.registerEvents = mitt() <add> this.loadingRoutes = {} <add> } <add> <add> normalizeRoute (route) { <add> if (route[0] !== '/') { <add> throw new Error('Route name should start with a "/"') <add> } <add> <add> return route.replace(/index$/, '') <add> } <add> <add> loadPage (route) { <add> route = this.normalizeRoute(route) <add> <add> const cachedPage = this.pageCache[route] <add> if (cachedPage) { <add> return new Promise((resolve, reject) => { <add> if (cachedPage.error) return reject(cachedPage.error) <add> return resolve(cachedPage.page) <add> }) <add> } <add> <add> return new Promise((resolve, reject) => { <add> const fire = ({ error, page }) => { <add> this.registerEvents.off(route, fire) <add> <add> if (error) { <add> reject(error) <add> } else { <add> resolve(page) <add> } <add> } <add> <add> this.registerEvents.on(route, fire) <add> <add> // Load the script if not asked to load yet. <add> if (!this.loadingRoutes[route]) { <add> this.loadScript(route) <add> this.loadingRoutes[route] = true <add> } <add> }) <add> } <add> <add> loadScript (route) { <add> route = this.normalizeRoute(route) <add> <add> const script = document.createElement('script') <add> const url = `${this.assetPrefix}/_next/${encodeURIComponent(this.buildId)}/page${route}` <add> script.src = url <add> script.type = 'text/javascript' <add> script.onerror = () => { <add> const error = new Error(`Error when loading route: ${route}`) <add> this.registerEvents.emit(route, { error }) <add> } <add> <add> document.body.appendChild(script) <add> } <add> <add> // This method if called by the route code. <add> registerPage (route, regFn) { <add> const register = () => { <add> const { error, page } = regFn() <add> this.pageCache[route] = { error, page } <add> this.registerEvents.emit(route, { error, page }) <add> } <add> <add> // Wait for webpack to became idle if it's not. <add> // More info: https://github.com/zeit/next.js/pull/1511 <add> if (webpackModule && webpackModule.hot && webpackModule.hot.status() !== 'idle') { <add> console.log(`Waiting webpack to became "idle" to initialize the page: "${route}"`) <add> <add> const check = (status) => { <add> if (status === 'idle') { <add> webpackModule.hot.removeStatusHandler(check) <add> register() <add> } <add> } <add> webpackModule.hot.status(check) <add> } else { <add> register() <add> } <add> } <add> <add> clearCache (route) { <add> route = this.normalizeRoute(route) <add> delete this.pageCache[route] <add> delete this.loadingRoutes[route] <add> } <add>} <ide><path>lib/router/router.js <ide> import { parse, format } from 'url' <ide> import mitt from 'mitt' <del>import fetch from 'unfetch' <del>import evalScript from '../eval-script' <ide> import shallowEquals from '../shallow-equals' <ide> import PQueue from '../p-queue' <ide> import { loadGetInitialProps, getURL } from '../utils' <ide> import { _notifyBuildIdMismatch } from './' <ide> <del>const webpackModule = module <del> <ide> export default class Router { <del> constructor (pathname, query, as, { Component, ErrorComponent, err } = {}) { <add> constructor (pathname, query, as, { pageLoader, Component, ErrorComponent, err } = {}) { <ide> // represents the current component key <ide> this.route = toRoute(pathname) <ide> <ide> // set up the component cache (by route keys) <del> this.components = { [this.route]: { Component, err } } <del> <del> // contain a map of promise of fetch routes <del> this.fetchingRoutes = {} <add> this.components = {} <add> // We should not keep the cache, if there's an error <add> // Otherwise, this cause issues when when going back and <add> // come again to the errored page. <add> if (Component !== ErrorComponent) { <add> this.components[this.route] = { Component, err } <add> } <ide> <ide> // Handling Router Events <ide> this.events = mitt() <ide> <add> this.pageLoader = pageLoader <ide> this.prefetchQueue = new PQueue({ concurrency: 2 }) <ide> this.ErrorComponent = ErrorComponent <ide> this.pathname = pathname <ide> export default class Router { <ide> <ide> async reload (route) { <ide> delete this.components[route] <del> delete this.fetchingRoutes[route] <add> this.pageLoader.clearCache(route) <ide> <ide> if (route !== this.route) return <ide> <ide> export default class Router { <ide> try { <ide> routeInfo = this.components[route] <ide> if (!routeInfo) { <del> routeInfo = await this.fetchComponent(route, as) <add> routeInfo = { Component: await this.fetchComponent(route, as) } <ide> } <ide> <del> const { Component, err, jsonPageRes } = routeInfo <del> const ctx = { err, pathname, query, jsonPageRes } <add> const { Component } = routeInfo <add> const ctx = { pathname, query } <ide> routeInfo.props = await this.getInitialProps(Component, ctx) <ide> <ide> this.components[route] = routeInfo <ide> export default class Router { <ide> return { error: err } <ide> } <ide> <add> if (err.buildIdMismatched) { <add> // Now we need to reload the page or do the action asked by the user <add> _notifyBuildIdMismatch(as) <add> // We also need to cancel this current route change. <add> // We do it like this. <add> err.cancelled = true <add> return { error: err } <add> } <add> <add> if (err.statusCode === 404) { <add> // Indicate main error display logic to <add> // ignore rendering this error as a runtime error. <add> err.ignore = true <add> } <add> <ide> const Component = this.ErrorComponent <ide> routeInfo = { Component, err } <ide> const ctx = { err, pathname, query } <ide> routeInfo.props = await this.getInitialProps(Component, ctx) <ide> <ide> routeInfo.error = err <del> console.error(err) <ide> } <ide> <ide> return routeInfo <ide> export default class Router { <ide> cancelled = true <ide> } <ide> <del> const jsonPageRes = await this.fetchRoute(route) <del> let jsonData <del> // We can call .json() only once for a response. <del> // That's why we need to keep a copy of data if we already parsed it. <del> if (jsonPageRes.data) { <del> jsonData = jsonPageRes.data <del> } else { <del> jsonData = jsonPageRes.data = await jsonPageRes.json() <del> } <del> <del> if (jsonData.buildIdMismatch) { <del> _notifyBuildIdMismatch(as) <del> <del> const error = Error('Abort due to BUILD_ID mismatch') <del> error.cancelled = true <del> throw error <del> } <del> <del> const newData = { <del> ...await loadComponent(jsonData), <del> jsonPageRes <del> } <add> const Component = await this.fetchRoute(route) <ide> <ide> if (cancelled) { <ide> const error = new Error(`Abort fetching component for route: "${route}"`) <ide> export default class Router { <ide> this.componentLoadCancel = null <ide> } <ide> <del> return newData <add> return Component <ide> } <ide> <ide> async getInitialProps (Component, ctx) { <ide> export default class Router { <ide> return props <ide> } <ide> <del> fetchRoute (route) { <del> let promise = this.fetchingRoutes[route] <del> if (!promise) { <del> promise = this.fetchingRoutes[route] = this.doFetchRoute(route) <del> } <del> <del> return promise <del> } <del> <del> doFetchRoute (route) { <del> const { buildId } = window.__NEXT_DATA__ <del> const url = `/_next/${encodeURIComponent(buildId)}/pages${route}` <del> <del> return fetch(url, { <del> method: 'GET', <del> credentials: 'same-origin', <del> headers: { 'Accept': 'application/json' } <del> }) <add> async fetchRoute (route) { <add> return await this.pageLoader.loadPage(route) <ide> } <ide> <ide> abortComponentLoad (as) { <ide> export default class Router { <ide> function toRoute (path) { <ide> return path.replace(/\/$/, '') || '/' <ide> } <del> <del>async function loadComponent (jsonData) { <del> if (webpackModule && webpackModule.hot && webpackModule.hot.status() !== 'idle') { <del> await new Promise((resolve) => { <del> const check = (status) => { <del> if (status === 'idle') { <del> webpackModule.hot.removeStatusHandler(check) <del> resolve() <del> } <del> } <del> webpackModule.hot.status(check) <del> }) <del> } <del> <del> const module = evalScript(jsonData.component) <del> const Component = module.default || module <del> <del> return { Component, err: jsonData.err } <del>} <ide><path>readme.md <ide> Next.js is a minimalistic framework for server-rendered React applications. <ide> - [Custom configuration](#custom-configuration) <ide> - [Customizing webpack config](#customizing-webpack-config) <ide> - [Customizing babel config](#customizing-babel-config) <add> - [CDN support with Asset Prefix](#cdn-support-with-asset-prefix) <ide> - [Production deployment](#production-deployment) <ide> - [FAQ](#faq) <ide> - [Contributing](#contributing) <ide> Here's an example `.babelrc` file: <ide> } <ide> ``` <ide> <add>### CDN support with Asset Prefix <add> <add>To set up a CDN, you can set up the `assetPrefix` setting and configure your CDN's origin to resolve to the domain that Next.js is hosted on. <add> <add>```js <add>const isProd = process.NODE_ENV === 'production' <add>module.exports = { <add> // You may only need to add assetPrefix in the production. <add> assetPrefix: isProd ? 'https://cdn.mydomain.com' : '' <add>} <add>``` <add> <add>Note: Next.js will automatically use that prefix the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration). <add> <ide> ## Production deployment <ide> <ide> To deploy, instead of running `next`, you want to build for production usage ahead of time. Therefore, building and starting are separate commands: <ide><path>server/build/plugins/json-pages-plugin.js <del>export default class JsonPagesPlugin { <del> apply (compiler) { <del> compiler.plugin('after-compile', (compilation, callback) => { <del> const pages = Object <del> .keys(compilation.assets) <del> .filter((filename) => /^bundles[/\\]pages.*\.js$/.test(filename)) <del> <del> pages.forEach((pageName) => { <del> const page = compilation.assets[pageName] <del> delete compilation.assets[pageName] <del> <del> const content = page.source() <del> const newContent = JSON.stringify({ component: content }) <del> <del> compilation.assets[`${pageName}on`] = { <del> source: () => newContent, <del> size: () => newContent.length <del> } <del> }) <del> <del> callback() <del> }) <del> } <del>} <ide><path>server/build/plugins/pages-plugin.js <add>export default class PagesPlugin { <add> apply (compiler) { <add> const isBundledPage = /^bundles[/\\]pages.*\.js$/ <add> const matchRouteName = /^bundles[/\\]pages[/\\](.*)\.js$/ <add> <add> compiler.plugin('after-compile', (compilation, callback) => { <add> const pages = Object <add> .keys(compilation.namedChunks) <add> .map(key => compilation.namedChunks[key]) <add> .filter(chunk => isBundledPage.test(chunk.name)) <add> <add> pages.forEach((chunk) => { <add> const page = compilation.assets[chunk.name] <add> const pageName = matchRouteName.exec(chunk.name)[1] <add> const routeName = `/${pageName.replace(/[/\\]?index$/, '')}` <add> <add> const content = page.source() <add> const newContent = ` <add> window.__NEXT_REGISTER_PAGE('${routeName}', function() { <add> var comp = ${content} <add> return { page: comp.default } <add> }) <add> ` <add> // Replace the exisiting chunk with the new content <add> compilation.assets[chunk.name] = { <add> source: () => newContent, <add> size: () => newContent.length <add> } <add> }) <add> callback() <add> }) <add> } <add>} <ide><path>server/build/webpack.js <ide> import WriteFilePlugin from 'write-file-webpack-plugin' <ide> import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin' <ide> import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin' <ide> import UnlinkFilePlugin from './plugins/unlink-file-plugin' <del>import JsonPagesPlugin from './plugins/json-pages-plugin' <add>import PagesPlugin from './plugins/pages-plugin' <ide> import CombineAssetsPlugin from './plugins/combine-assets-plugin' <ide> import getConfig from '../config' <ide> import * as babelCore from 'babel-core' <ide> export default async function createCompiler (dir, { dev = false, quiet = false, <ide> new webpack.DefinePlugin({ <ide> 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production') <ide> }), <del> new JsonPagesPlugin(), <add> new PagesPlugin(), <ide> new CaseSensitivePathPlugin() <ide> ] <ide> <ide><path>server/config.js <ide> const cache = new Map() <ide> const defaultConfig = { <ide> webpack: null, <ide> poweredByHeader: true, <del> distDir: '.next' <add> distDir: '.next', <add> assetPrefix: '' <ide> } <ide> <ide> export default function getConfig (dir) { <ide><path>server/document.js <ide> export class Head extends Component { <ide> _documentProps: PropTypes.any <ide> } <ide> <add> getChunkPreloadLink (filename) { <add> const { __NEXT_DATA__ } = this.context._documentProps <add> let { buildStats, assetPrefix } = __NEXT_DATA__ <add> const hash = buildStats ? buildStats[filename].hash : '-' <add> <add> return ( <add> <link <add> key={filename} <add> rel='preload' <add> href={`${assetPrefix}/_next/${hash}/${filename}`} <add> as='script' <add> /> <add> ) <add> } <add> <add> getPreloadMainLinks () { <add> const { dev } = this.context._documentProps <add> if (dev) { <add> return [ <add> this.getChunkPreloadLink('manifest.js'), <add> this.getChunkPreloadLink('commons.js'), <add> this.getChunkPreloadLink('main.js') <add> ] <add> } <add> <add> // In the production mode, we have a single asset with all the JS content. <add> return [ <add> this.getChunkPreloadLink('app.js') <add> ] <add> } <add> <ide> render () { <del> const { head, styles } = this.context._documentProps <add> const { head, styles, __NEXT_DATA__ } = this.context._documentProps <add> const { pathname, buildId, assetPrefix } = __NEXT_DATA__ <add> <ide> return <head> <add> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page${pathname}`} as='script' /> <add> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page/_error`} as='script' /> <add> {this.getPreloadMainLinks()} <ide> {(head || []).map((h, i) => React.cloneElement(h, { key: i }))} <ide> {styles || null} <ide> {this.props.children} <ide> export class NextScript extends Component { <ide> <ide> getChunkScript (filename, additionalProps = {}) { <ide> const { __NEXT_DATA__ } = this.context._documentProps <del> let { buildStats } = __NEXT_DATA__ <add> let { buildStats, assetPrefix } = __NEXT_DATA__ <ide> const hash = buildStats ? buildStats[filename].hash : '-' <ide> <ide> return ( <ide> <script <ide> type='text/javascript' <del> src={`/_next/${hash}/${filename}`} <add> src={`${assetPrefix}/_next/${hash}/${filename}`} <ide> {...additionalProps} <ide> /> <ide> ) <ide> export class NextScript extends Component { <ide> <ide> render () { <ide> const { staticMarkup, __NEXT_DATA__ } = this.context._documentProps <add> const { pathname, buildId, assetPrefix } = __NEXT_DATA__ <ide> <ide> return <div> <ide> {staticMarkup ? null : <script dangerouslySetInnerHTML={{ <del> __html: `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}; module={};` <add> __html: ` <add> __NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)} <add> module={} <add> __NEXT_LOADED_PAGES__ = [] <add> <add> __NEXT_REGISTER_PAGE = function (route, fn) { <add> __NEXT_LOADED_PAGES__.push({ route: route, fn: fn }) <add> } <add> ` <ide> }} />} <add> <script async type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page${pathname}`} /> <add> <script async type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page/_error`} /> <ide> {staticMarkup ? null : this.getScripts()} <ide> </div> <ide> } <ide><path>server/hot-reloader.js <ide> import onDemandEntryHandler from './on-demand-entry-handler' <ide> import isWindowsBash from 'is-windows-bash' <ide> import webpack from './build/webpack' <ide> import clean from './build/clean' <del>import readPage from './read-page' <ide> import getConfig from './config' <ide> <ide> export default class HotReloader { <ide> export default class HotReloader { <ide> <ide> function deleteCache (path) { <ide> delete require.cache[path] <del> delete readPage.cache[path] <ide> } <ide> <ide> function diff (a, b) { <ide><path>server/index.js <ide> import http, { STATUS_CODES } from 'http' <ide> import { <ide> renderToHTML, <ide> renderErrorToHTML, <del> renderJSON, <del> renderErrorJSON, <ide> sendHTML, <del> serveStatic <add> serveStatic, <add> renderScript, <add> renderScriptError <ide> } from './render' <ide> import Router from './router' <ide> import HotReloader from './hot-reloader' <ide> export default class Server { <ide> dir: this.dir, <ide> hotReloader: this.hotReloader, <ide> buildStats: this.buildStats, <del> buildId: this.buildId <add> buildId: this.buildId, <add> assetPrefix: this.config.assetPrefix.replace(/\/$/, '') <ide> } <ide> <ide> this.defineRoutes() <ide> export default class Server { <ide> await this.serveStatic(req, res, p) <ide> }, <ide> <del> '/_next/:buildId/pages/:path*': async (req, res, params) => { <add> '/_next/:buildId/page/_error': async (req, res, params) => { <ide> if (!this.handleBuildId(params.buildId, res)) { <del> res.setHeader('Content-Type', 'application/json') <del> res.end(JSON.stringify({ buildIdMismatch: true })) <del> return <add> const error = new Error('INVALID_BUILD_ID') <add> const customFields = { buildIdMismatched: true } <add> <add> return await renderScriptError(req, res, '/_error', error, customFields, this.renderOpts) <add> } <add> <add> const p = join(this.dir, '.next/bundles/pages/_error.js') <add> await this.serveStatic(req, res, p) <add> }, <add> <add> '/_next/:buildId/page/:path*': async (req, res, params) => { <add> const paths = params.path || [''] <add> const page = `/${paths.join('/')}` <add> <add> if (!this.handleBuildId(params.buildId, res)) { <add> const error = new Error('INVALID_BUILD_ID') <add> const customFields = { buildIdMismatched: true } <add> <add> return await renderScriptError(req, res, page, error, customFields, this.renderOpts) <ide> } <ide> <del> const paths = params.path || ['index'] <del> const pathname = `/${paths.join('/')}` <add> if (this.dev) { <add> try { <add> await this.hotReloader.ensurePage(page) <add> } catch (error) { <add> return await renderScriptError(req, res, page, error, {}, this.renderOpts) <add> } <add> <add> const compilationErr = this.getCompilationError(page) <add> if (compilationErr) { <add> const customFields = { statusCode: 500 } <add> return await renderScriptError(req, res, page, compilationErr, customFields, this.renderOpts) <add> } <add> } <ide> <del> await this.renderJSON(req, res, pathname) <add> await renderScript(req, res, page, this.renderOpts) <ide> }, <ide> <ide> '/_next/:path+': async (req, res, params) => { <ide> export default class Server { <ide> return this.renderError(null, req, res, pathname, query) <ide> } <ide> <del> async renderJSON (req, res, page) { <del> if (this.dev) { <del> const compilationErr = this.getCompilationError(page) <del> if (compilationErr) { <del> return this.renderErrorJSON(compilationErr, req, res) <del> } <del> } <del> <del> try { <del> return await renderJSON(req, res, page, this.renderOpts) <del> } catch (err) { <del> if (err.code === 'ENOENT') { <del> res.statusCode = 404 <del> return this.renderErrorJSON(null, req, res) <del> } else { <del> if (!this.quiet) console.error(err) <del> res.statusCode = 500 <del> return this.renderErrorJSON(err, req, res) <del> } <del> } <del> } <del> <del> async renderErrorJSON (err, req, res) { <del> if (this.dev) { <del> const compilationErr = this.getCompilationError('/_error') <del> if (compilationErr) { <del> res.statusCode = 500 <del> return renderErrorJSON(compilationErr, req, res, this.renderOpts) <del> } <del> } <del> <del> return renderErrorJSON(err, req, res, this.renderOpts) <del> } <del> <ide> async serveStatic (req, res, path) { <ide> try { <ide> return await serveStatic(req, res, path) <ide><path>server/read-page.js <del>import fs from 'mz/fs' <del>import resolve from './resolve' <del> <del>/** <del> * resolve a JSON page like `require.resolve`, <del> * and read and cache the file content <del> */ <del> <del>async function readPage (path) { <del> const f = await resolve(path) <del> if (cache.hasOwnProperty(f)) { <del> return cache[f] <del> } <del> <del> const source = await fs.readFile(f, 'utf8') <del> const { component } = JSON.parse(source) <del> <del> cache[f] = component <del> return component <del>} <del> <del>export default readPage <del>export const cache = {} <del> <del>readPage.cache = cache <ide><path>server/render.js <ide> import send from 'send' <ide> import requireModule from './require' <ide> import getConfig from './config' <ide> import resolvePath from './resolve' <del>import readPage from './read-page' <ide> import { Router } from '../lib/router' <ide> import { loadGetInitialProps } from '../lib/utils' <ide> import Head, { defaultHead } from '../lib/head' <ide> async function doRender (req, res, pathname, query, { <ide> buildId, <ide> buildStats, <ide> hotReloader, <add> assetPrefix, <ide> dir = process.cwd(), <ide> dev = false, <ide> staticMarkup = false <ide> async function doRender (req, res, pathname, query, { <ide> Component = Component.default || Component <ide> Document = Document.default || Document <ide> const ctx = { err, req, res, pathname, query } <del> <del> const [ <del> props, <del> component, <del> errorComponent <del> ] = await Promise.all([ <del> loadGetInitialProps(Component, ctx), <del> readPage(join(dir, dist, 'bundles', 'pages', page)), <del> readPage(join(dir, dist, 'bundles', 'pages', '_error')) <del> ]) <add> const props = await loadGetInitialProps(Component, ctx) <ide> <ide> // the response might be finshed on the getinitialprops call <ide> if (res.finished) return <ide> async function doRender (req, res, pathname, query, { <ide> <ide> const doc = createElement(Document, { <ide> __NEXT_DATA__: { <del> component, <del> errorComponent, <ide> props, <ide> pathname, <ide> query, <ide> buildId, <ide> buildStats, <add> assetPrefix, <ide> err: (err && dev) ? errorToJSON(err) : null <ide> }, <ide> dev, <ide> async function doRender (req, res, pathname, query, { <ide> return '<!DOCTYPE html>' + renderToStaticMarkup(doc) <ide> } <ide> <del>export async function renderJSON (req, res, page, { dir = process.cwd(), hotReloader } = {}) { <del> const dist = getConfig(dir).distDir <del> await ensurePage(page, { dir, hotReloader }) <del> const pagePath = await resolvePath(join(dir, dist, 'bundles', 'pages', page)) <del> return serveStatic(req, res, pagePath) <add>export async function renderScript (req, res, page, opts) { <add> try { <add> const path = join(opts.dir, '.next', 'bundles', 'pages', page) <add> const realPath = await resolvePath(path) <add> await serveStatic(req, res, realPath) <add> } catch (err) { <add> if (err.code === 'ENOENT') { <add> renderScriptError(req, res, page, err, {}, opts) <add> return <add> } <add> <add> throw err <add> } <ide> } <ide> <del>export async function renderErrorJSON (err, req, res, { dir = process.cwd(), dev = false } = {}) { <del> const dist = getConfig(dir).distDir <del> const component = await readPage(join(dir, dist, 'bundles', 'pages', '_error')) <add>export async function renderScriptError (req, res, page, error, customFields, opts) { <add> if (error.code === 'ENOENT') { <add> res.setHeader('Content-Type', 'text/javascript') <add> res.end(` <add> window.__NEXT_REGISTER_PAGE('${page}', function() { <add> var error = new Error('Page not exists: ${page}') <add> error.statusCode = 404 <add> <add> return { error: error } <add> }) <add> `) <add> return <add> } <ide> <del> sendJSON(res, { <del> component, <del> err: err && dev ? errorToJSON(err) : null <del> }, req.method) <add> res.setHeader('Content-Type', 'text/javascript') <add> const errorJson = { <add> ...errorToJSON(error), <add> ...customFields <add> } <add> <add> res.end(` <add> window.__NEXT_REGISTER_PAGE('${page}', function() { <add> var error = ${JSON.stringify(errorJson)} <add> return { error: error } <add> }) <add> `) <ide> } <ide> <ide> export function sendHTML (res, html, method) { <ide><path>test/integration/ondemand/test/index.test.js <ide> describe('On Demand Entries', () => { <ide> }) <ide> <ide> it('should compile pages for JSON page requests', async () => { <del> const pageContent = await renderViaHTTP(context.appPort, '/_next/-/pages/about') <add> const pageContent = await renderViaHTTP(context.appPort, '/_next/-/page/about') <ide> expect(pageContent.includes('About Page')).toBeTruthy() <ide> }) <ide> <ide> it('should dispose inactive pages', async () => { <ide> await renderViaHTTP(context.appPort, '/_next/-/pages/about') <del> const aboutPagePath = resolve(__dirname, '../.next/bundles/pages/about.json') <add> const aboutPagePath = resolve(__dirname, '../.next/bundles/pages/about.js') <ide> expect(existsSync(aboutPagePath)).toBeTruthy() <ide> <ide> // Wait maximum of jasmine.DEFAULT_TIMEOUT_INTERVAL checking <ide><path>test/integration/production/pages/about.js <add>export default () => ( <add> <div className='about-page'>About Page</div> <add>) <ide><path>test/integration/production/pages/index.js <add>import Link from 'next/link' <add> <ide> export default () => ( <del> <div>Hello World</div> <add> <div> <add> <Link href='/about'><a>About Page</a></Link> <add> <p>Hello World</p> <add> </div> <ide> ) <ide><path>test/integration/production/test/index.test.js <ide> /* global jasmine, describe, it, expect, beforeAll, afterAll */ <ide> <del>import fetch from 'node-fetch' <ide> import { join } from 'path' <ide> import { <ide> nextServer, <ide> import { <ide> stopApp, <ide> renderViaHTTP <ide> } from 'next-test-utils' <add>import webdriver from 'next-webdriver' <ide> <ide> const appDir = join(__dirname, '../') <ide> let appPort <ide> describe('Production Usage', () => { <ide> }) <ide> }) <ide> <del> describe('JSON pages', () => { <del> describe('when asked for a normal page', () => { <del> it('should serve the normal page', async () => { <del> const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages` <del> const res = await fetch(url, { compress: false }) <del> expect(res.headers.get('Content-Encoding')).toBeNull() <add> describe('With navigation', () => { <add> it('should navigate via client side', async () => { <add> const browser = await webdriver(appPort, '/') <add> const text = await browser <add> .elementByCss('a').click() <add> .waitForElementByCss('.about-page') <add> .elementByCss('div').text() <ide> <del> const page = await res.json() <del> expect(page.component).toBeDefined() <del> }) <del> }) <del> <del> describe('when asked for a page with an unknown encoding', () => { <del> it('should serve the normal page', async () => { <del> const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages` <del> const res = await fetch(url, { <del> compress: false, <del> headers: { <del> 'Accept-Encoding': 'br' <del> } <del> }) <del> expect(res.headers.get('Content-Encoding')).toBeNull() <del> <del> const page = await res.json() <del> expect(page.component).toBeDefined() <del> }) <add> expect(text).toBe('About Page') <add> browser.close() <ide> }) <ide> }) <ide> }) <ide><path>test/unit/router.test.js <ide> /* global describe, it, expect */ <ide> import Router from '../../dist/lib/router/router' <ide> <add>class PageLoader { <add> constructor (options = {}) { <add> this.options = options <add> this.loaded = {} <add> } <add> <add> loadPage (route) { <add> this.loaded[route] = true <add> <add> if (this.options.delay) { <add> return new Promise((resolve) => setTimeout(resolve, this.options.delay)) <add> } <add> } <add>} <add> <ide> describe('Router', () => { <ide> const request = { clone: () => null } <ide> describe('.prefetch()', () => { <ide> it('should prefetch a given page', async () => { <del> const router = new Router('/', {}) <del> const promise = Promise.resolve(request) <del> const route = 'routex' <del> router.doFetchRoute = (r) => { <del> expect(r).toBe(route) <del> return promise <del> } <add> const pageLoader = new PageLoader() <add> const router = new Router('/', {}, '/', { pageLoader }) <add> const route = '/routex' <ide> await router.prefetch(route) <ide> <del> expect(router.fetchingRoutes[route]).toBe(promise) <del> }) <del> <del> it('should stop if it\'s prefetching already', async () => { <del> const router = new Router('/', {}) <del> const route = 'routex' <del> router.fetchingRoutes[route] = Promise.resolve(request) <del> router.doFetchRoute = () => { throw new Error('Should not happen') } <del> await router.prefetch(route) <add> expect(pageLoader.loaded['/routex']).toBeTruthy() <ide> }) <ide> <ide> it('should only run two jobs at a time', async () => { <del> const router = new Router('/', {}) <del> let count = 0 <del> <del> router.doFetchRoute = () => { <del> count++ <del> return new Promise((resolve) => {}) <del> } <add> // delay loading pages for an hour <add> const pageLoader = new PageLoader({ delay: 1000 * 3600 }) <add> const router = new Router('/', {}, '/', { pageLoader }) <ide> <ide> router.prefetch('route1') <ide> router.prefetch('route2') <ide> router.prefetch('route3') <ide> router.prefetch('route4') <ide> <add> // Wait for a bit <ide> await new Promise((resolve) => setTimeout(resolve, 50)) <ide> <del> expect(count).toBe(2) <del> expect(Object.keys(router.fetchingRoutes)).toEqual(['route1', 'route2']) <add> expect(Object.keys(pageLoader.loaded).length).toBe(2) <add> expect(Object.keys(pageLoader.loaded)).toEqual(['route1', 'route2']) <ide> }) <ide> <ide> it('should run all the jobs', async () => { <del> const router = new Router('/', {}) <add> const pageLoader = new PageLoader() <add> const router = new Router('/', {}, '/', { pageLoader }) <ide> const routes = ['route1', 'route2', 'route3', 'route4'] <ide> <ide> router.doFetchRoute = () => Promise.resolve(request) <ide> describe('Router', () => { <ide> await router.prefetch(routes[2]) <ide> await router.prefetch(routes[3]) <ide> <del> expect(Object.keys(router.fetchingRoutes)).toEqual(routes) <add> expect(Object.keys(pageLoader.loaded)).toEqual(routes) <ide> }) <ide> }) <ide> })
24
Python
Python
fix dtype getter
a1344dbfb97c18fc4c23568f39d6631fba05c218
<ide><path>src/transformers/modeling_utils.py <ide> def get_first_parameter_dtype(parameter: Union[nn.Module, GenerationMixin, "Modu <ide> try: <ide> return next(parameter.parameters()).dtype <ide> except StopIteration: <del> # For nn.DataParallel compatibility in PyTorch 1.5 <add> # For nn.DataParallel compatibility in PyTorch > 1.5 <ide> <ide> def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: <ide> tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] <ide> def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: <ide> <ide> def get_parameter_dtype(parameter: Union[nn.Module, GenerationMixin, "ModuleUtilsMixin"]): <ide> """ <del> Returns the first found floating dtype in parameters if there is one, otherwise returns the first dtype it found. <add> Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found. <ide> """ <del> try: <del> for t in parameter.parameters(): <del> if t.is_floating_point(): <del> return t.dtype <del> # if no floating dtype was found return whatever the first dtype is <del> else: <del> return next(parameter.parameters()).dtype <add> last_dtype = None <add> for t in parameter.parameters(): <add> last_dtype = t.dtype <add> if t.is_floating_point(): <add> return t.dtype <ide> <del> except StopIteration: <del> # For nn.DataParallel compatibility in PyTorch 1.5 <add> if last_dtype is not None: <add> # if no floating dtype was found return whatever the first dtype is <add> return last_dtype <ide> <add> else: <add> # For nn.DataParallel compatibility in PyTorch > 1.5 <ide> def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: <ide> tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] <ide> return tuples <ide> <ide> gen = parameter._named_members(get_members_fn=find_tensor_attributes) <add> last_tuple = None <ide> for tuple in gen: <add> last_tuple = tuple <ide> if tuple[1].is_floating_point(): <ide> return tuple[1].dtype <del> # fallback to any dtype the model has even if not floating <del> else: <del> first_tuple = next(gen) <del> return first_tuple[1].dtype <add> <add> # fallback to the last dtype <add> return last_tuple[1].dtype <ide> <ide> <ide> def get_state_dict_float_dtype(state_dict):
1
Javascript
Javascript
remove dead code from dompropertyoperations
0a2ed64450fcafecbbe502d4bb812843085e3918
<ide><path>packages/react-dom/src/client/DOMPropertyOperations.js <ide> export function setValueForProperty(node, name, value) { <ide> ); <ide> return; <ide> } <del> <del> if (__DEV__) { <del> var payload = {}; <del> payload[name] = value; <del> } <ide> } <ide> <ide> export function setValueForAttribute(node, name, value) { <ide> export function setValueForAttribute(node, name, value) { <ide> } else { <ide> node.setAttribute(name, '' + value); <ide> } <del> <del> if (__DEV__) { <del> var payload = {}; <del> payload[name] = value; <del> } <ide> } <ide> <ide> /**
1
Javascript
Javascript
make _.js work in strict mode
4f1397ef3ceaead952bc80fc23918e503a7915ac
<ide><path>vendor/underscore.js <ide> return this._wrapped; <ide> }; <ide> <del>})(); <add>// fix for 'use strict' - need an explicit `this` <add>}).call(this || window);
1
Text
Text
unlock the timers api
c76f737ebc945c59e602b810381136bede427cd3
<ide><path>doc/api/timers.md <ide> # Timers <ide> <del>> Stability: 3 - Locked <add>> Stability: 2 - Stable <ide> <ide> The `timer` module exposes a global API for scheduling functions to <ide> be called at some future period of time. Because the timer functions are
1
Text
Text
remove duplicate flags
da9bbf9acc867bb8dc2e6980a9f7c508fdd740bb
<ide><path>research/deeplab/g3doc/cityscapes.md <ide> python deeplab/train.py \ <ide> --train_crop_size=769 \ <ide> --train_batch_size=1 \ <ide> --dataset="cityscapes" \ <del> --train_split="train" \ <ide> --tf_initial_checkpoints=${PATH_TO_INITIAL_CHECKPOINT} \ <ide> --train_logdir=${PATH_TO_TRAIN_DIR} \ <ide> --dataset_dir=${PATH_TO_DATASET} <ide> python deeplab/eval.py \ <ide> --eval_crop_size=1025 \ <ide> --eval_crop_size=2049 \ <ide> --dataset="cityscapes" \ <del> --eval_split="val" \ <ide> --checkpoint_dir=${PATH_TO_CHECKPOINT} \ <ide> --eval_logdir=${PATH_TO_EVAL_DIR} \ <ide> --dataset_dir=${PATH_TO_DATASET} <ide> python deeplab/vis.py \ <ide> --vis_crop_size=1025 \ <ide> --vis_crop_size=2049 \ <ide> --dataset="cityscapes" \ <del> --vis_split="val" \ <ide> --colormap_type="cityscapes" \ <ide> --checkpoint_dir=${PATH_TO_CHECKPOINT} \ <ide> --vis_logdir=${PATH_TO_VIS_DIR} \ <ide><path>research/deeplab/g3doc/pascal.md <ide> python deeplab/train.py \ <ide> --train_crop_size=513 \ <ide> --train_batch_size=1 \ <ide> --dataset="pascal_voc_seg" \ <del> --train_split="train" \ <ide> --tf_initial_checkpoints=${PATH_TO_INITIAL_CHECKPOINT} \ <ide> --train_logdir=${PATH_TO_TRAIN_DIR} \ <ide> --dataset_dir=${PATH_TO_DATASET} <ide> python deeplab/eval.py \ <ide> --eval_crop_size=513 \ <ide> --eval_crop_size=513 \ <ide> --dataset="pascal_voc_seg" \ <del> --eval_split="val" \ <ide> --checkpoint_dir=${PATH_TO_CHECKPOINT} \ <ide> --eval_logdir=${PATH_TO_EVAL_DIR} \ <ide> --dataset_dir=${PATH_TO_DATASET} <ide> python deeplab/vis.py \ <ide> --vis_crop_size=513 \ <ide> --vis_crop_size=513 \ <ide> --dataset="pascal_voc_seg" \ <del> --vis_split="val" \ <ide> --checkpoint_dir=${PATH_TO_CHECKPOINT} \ <ide> --vis_logdir=${PATH_TO_VIS_DIR} \ <ide> --dataset_dir=${PATH_TO_DATASET}
2
PHP
PHP
remove un-needed method
6d3d1919873cabde40f2943d800dacf884d371fc
<ide><path>src/Illuminate/Routing/Controllers/Controller.php <ide> public function getControllerFilters() <ide> return $this->filters; <ide> } <ide> <del> /** <del> * Handle calls to missing methods on the controller. <del> * <del> * @param array $parameters <del> * @return mixed <del> */ <del> public function missingMethod($parameters) <del> { <del> throw new NotFoundHttpException; <del> } <del> <ide> /** <ide> * Handle calls to missing methods on the controller. <ide> *
1
Go
Go
remove v1 code not related to searching
3f7c62f6f6ddca1cd2f875cf0924549d9c5a4827
<ide><path>registry/errors.go <ide> import ( <ide> "github.com/docker/docker/errdefs" <ide> ) <ide> <del>type notFoundError string <del> <del>func (e notFoundError) Error() string { <del> return string(e) <del>} <del> <del>func (notFoundError) NotFound() {} <del> <ide> func translateV2AuthError(err error) error { <ide> switch e := err.(type) { <ide> case *url.Error: <ide><path>registry/registry_test.go <ide> package registry // import "github.com/docker/docker/registry" <ide> <ide> import ( <del> "fmt" <ide> "net/http" <ide> "net/http/httputil" <del> "net/url" <ide> "os" <ide> "strings" <ide> "testing" <ide> import ( <ide> "gotest.tools/v3/skip" <ide> ) <ide> <del>var ( <del> token = []string{"fake-token"} <del>) <del> <del>const ( <del> imageID = "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d" <del> REPO = "foo42/bar" <del>) <del> <ide> func spawnTestRegistrySession(t *testing.T) *Session { <ide> authConfig := &types.AuthConfig{} <ide> endpoint, err := NewV1Endpoint(makeIndex("/v1/"), "", nil) <ide> func spawnTestRegistrySession(t *testing.T) *Session { <ide> // Because we know that the client's transport is an `*authTransport` we simply cast it, <ide> // in order to set the internal cached token to the fake token, and thus send that fake token <ide> // upon every subsequent requests. <del> r.client.Transport.(*authTransport).token = token <add> r.client.Transport.(*authTransport).token = []string{"fake-token"} <ide> return r <ide> } <ide> <ide> func TestEndpoint(t *testing.T) { <ide> } <ide> } <ide> <del>func TestGetRemoteHistory(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> hist, err := r.GetRemoteHistory(imageID, makeURL("/v1/")) <del> if err != nil { <del> t.Fatal(err) <del> } <del> assertEqual(t, len(hist), 2, "Expected 2 images in history") <del> assertEqual(t, hist[0], imageID, "Expected "+imageID+"as first ancestry") <del> assertEqual(t, hist[1], "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", <del> "Unexpected second ancestry") <del>} <del> <del>func TestLookupRemoteImage(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> err := r.LookupRemoteImage(imageID, makeURL("/v1/")) <del> assertEqual(t, err, nil, "Expected error of remote lookup to nil") <del> if err := r.LookupRemoteImage("abcdef", makeURL("/v1/")); err == nil { <del> t.Fatal("Expected error of remote lookup to not nil") <del> } <del>} <del> <del>func TestGetRemoteImageJSON(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> json, size, err := r.GetRemoteImageJSON(imageID, makeURL("/v1/")) <del> if err != nil { <del> t.Fatal(err) <del> } <del> assertEqual(t, size, int64(154), "Expected size 154") <del> if len(json) == 0 { <del> t.Fatal("Expected non-empty json") <del> } <del> <del> _, _, err = r.GetRemoteImageJSON("abcdef", makeURL("/v1/")) <del> if err == nil { <del> t.Fatal("Expected image not found error") <del> } <del>} <del> <del>func TestGetRemoteImageLayer(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> data, err := r.GetRemoteImageLayer(imageID, makeURL("/v1/"), 0) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if data == nil { <del> t.Fatal("Expected non-nil data result") <del> } <del> <del> _, err = r.GetRemoteImageLayer("abcdef", makeURL("/v1/"), 0) <del> if err == nil { <del> t.Fatal("Expected image not found error") <del> } <del>} <del> <del>func TestGetRemoteTag(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> repoRef, err := reference.ParseNormalizedNamed(REPO) <del> if err != nil { <del> t.Fatal(err) <del> } <del> tag, err := r.GetRemoteTag([]string{makeURL("/v1/")}, repoRef, "test") <del> if err != nil { <del> t.Fatal(err) <del> } <del> assertEqual(t, tag, imageID, "Expected tag test to map to "+imageID) <del> <del> bazRef, err := reference.ParseNormalizedNamed("foo42/baz") <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, err = r.GetRemoteTag([]string{makeURL("/v1/")}, bazRef, "foo") <del> if err != ErrRepoNotFound { <del> t.Fatal("Expected ErrRepoNotFound error when fetching tag for bogus repo") <del> } <del>} <del> <del>func TestGetRemoteTags(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> repoRef, err := reference.ParseNormalizedNamed(REPO) <del> if err != nil { <del> t.Fatal(err) <del> } <del> tags, err := r.GetRemoteTags([]string{makeURL("/v1/")}, repoRef) <del> if err != nil { <del> t.Fatal(err) <del> } <del> assertEqual(t, len(tags), 2, "Expected two tags") <del> assertEqual(t, tags["latest"], imageID, "Expected tag latest to map to "+imageID) <del> assertEqual(t, tags["test"], imageID, "Expected tag test to map to "+imageID) <del> <del> bazRef, err := reference.ParseNormalizedNamed("foo42/baz") <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, err = r.GetRemoteTags([]string{makeURL("/v1/")}, bazRef) <del> if err != ErrRepoNotFound { <del> t.Fatal("Expected ErrRepoNotFound error when fetching tags for bogus repo") <del> } <del>} <del> <del>func TestGetRepositoryData(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> parsedURL, err := url.Parse(makeURL("/v1/")) <del> if err != nil { <del> t.Fatal(err) <del> } <del> host := "http://" + parsedURL.Host + "/v1/" <del> repoRef, err := reference.ParseNormalizedNamed(REPO) <del> if err != nil { <del> t.Fatal(err) <del> } <del> data, err := r.GetRepositoryData(repoRef) <del> if err != nil { <del> t.Fatal(err) <del> } <del> assertEqual(t, len(data.ImgList), 2, "Expected 2 images in ImgList") <del> assertEqual(t, len(data.Endpoints), 2, <del> fmt.Sprintf("Expected 2 endpoints in Endpoints, found %d instead", len(data.Endpoints))) <del> assertEqual(t, data.Endpoints[0], host, <del> fmt.Sprintf("Expected first endpoint to be %s but found %s instead", host, data.Endpoints[0])) <del> assertEqual(t, data.Endpoints[1], "http://test.example.com/v1/", <del> fmt.Sprintf("Expected first endpoint to be http://test.example.com/v1/ but found %s instead", data.Endpoints[1])) <del> <del>} <del> <del>func TestPushImageJSONRegistry(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> imgData := &ImgData{ <del> ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", <del> Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37", <del> } <del> <del> err := r.PushImageJSONRegistry(imgData, []byte{0x42, 0xdf, 0x0}, makeURL("/v1/")) <del> if err != nil { <del> t.Fatal(err) <del> } <del>} <del> <del>func TestPushImageLayerRegistry(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> layer := strings.NewReader("") <del> _, _, err := r.PushImageLayerRegistry(imageID, layer, makeURL("/v1/"), []byte{}) <del> if err != nil { <del> t.Fatal(err) <del> } <del>} <del> <ide> func TestParseRepositoryInfo(t *testing.T) { <ide> type staticRepositoryInfo struct { <ide> Index *registrytypes.IndexInfo <ide> func TestMirrorEndpointLookup(t *testing.T) { <ide> } <ide> } <ide> <del>func TestPushRegistryTag(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> repoRef, err := reference.ParseNormalizedNamed(REPO) <del> if err != nil { <del> t.Fatal(err) <del> } <del> err = r.PushRegistryTag(repoRef, imageID, "stable", makeURL("/v1/")) <del> if err != nil { <del> t.Fatal(err) <del> } <del>} <del> <del>func TestPushImageJSONIndex(t *testing.T) { <del> r := spawnTestRegistrySession(t) <del> imgData := []*ImgData{ <del> { <del> ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", <del> Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37", <del> }, <del> { <del> ID: "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", <del> Checksum: "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2", <del> }, <del> } <del> repoRef, err := reference.ParseNormalizedNamed(REPO) <del> if err != nil { <del> t.Fatal(err) <del> } <del> repoData, err := r.PushImageJSONIndex(repoRef, imgData, false, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if repoData == nil { <del> t.Fatal("Expected RepositoryData object") <del> } <del> repoData, err = r.PushImageJSONIndex(repoRef, imgData, true, []string{r.indexEndpoint.String()}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if repoData == nil { <del> t.Fatal("Expected RepositoryData object") <del> } <del>} <del> <ide> func TestSearchRepositories(t *testing.T) { <ide> r := spawnTestRegistrySession(t) <ide> results, err := r.SearchRepositories("fakequery", 25) <ide><path>registry/session.go <ide> package registry // import "github.com/docker/docker/registry" <ide> <ide> import ( <del> "bytes" <del> "crypto/sha256" <del> <ide> // this is required for some certificates <ide> _ "crypto/sha512" <del> "encoding/hex" <ide> "encoding/json" <ide> "fmt" <del> "io" <del> "io/ioutil" <ide> "net/http" <ide> "net/http/cookiejar" <ide> "net/url" <del> "strconv" <ide> "strings" <ide> "sync" <ide> <del> "github.com/docker/distribution/reference" <del> "github.com/docker/distribution/registry/api/errcode" <ide> "github.com/docker/docker/api/types" <ide> registrytypes "github.com/docker/docker/api/types/registry" <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/stringid" <del> "github.com/docker/docker/pkg/tarsum" <del> "github.com/docker/docker/registry/resumable" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <del>var ( <del> // ErrRepoNotFound is returned if the repository didn't exist on the <del> // remote side <del> ErrRepoNotFound notFoundError = "Repository not found" <del>) <del> <ide> // A Session is used to communicate with a V1 registry <ide> type Session struct { <ide> indexEndpoint *V1Endpoint <ide> func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1E <ide> return newSession(client, authConfig, endpoint), nil <ide> } <ide> <del>// ID returns this registry session's ID. <del>func (r *Session) ID() string { <del> return r.id <del>} <del> <del>// GetRemoteHistory retrieves the history of a given image from the registry. <del>// It returns a list of the parent's JSON files (including the requested image). <del>func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) { <del> res, err := r.client.Get(registry + "images/" + imgID + "/ancestry") <del> if err != nil { <del> return nil, err <del> } <del> defer res.Body.Close() <del> if res.StatusCode != http.StatusOK { <del> if res.StatusCode == http.StatusUnauthorized { <del> return nil, errcode.ErrorCodeUnauthorized.WithArgs() <del> } <del> return nil, newJSONError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res) <del> } <del> <del> var history []string <del> if err := json.NewDecoder(res.Body).Decode(&history); err != nil { <del> return nil, fmt.Errorf("Error while reading the http response: %v", err) <del> } <del> <del> logrus.Debugf("Ancestry: %v", history) <del> return history, nil <del>} <del> <del>// LookupRemoteImage checks if an image exists in the registry <del>func (r *Session) LookupRemoteImage(imgID, registry string) error { <del> res, err := r.client.Get(registry + "images/" + imgID + "/json") <del> if err != nil { <del> return err <del> } <del> res.Body.Close() <del> if res.StatusCode != http.StatusOK { <del> return newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) <del> } <del> return nil <del>} <del> <del>// GetRemoteImageJSON retrieves an image's JSON metadata from the registry. <del>func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) { <del> res, err := r.client.Get(registry + "images/" + imgID + "/json") <del> if err != nil { <del> return nil, -1, fmt.Errorf("Failed to download json: %s", err) <del> } <del> defer res.Body.Close() <del> if res.StatusCode != http.StatusOK { <del> return nil, -1, newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) <del> } <del> // if the size header is not present, then set it to '-1' <del> imageSize := int64(-1) <del> if hdr := res.Header.Get("X-Docker-Size"); hdr != "" { <del> imageSize, err = strconv.ParseInt(hdr, 10, 64) <del> if err != nil { <del> return nil, -1, err <del> } <del> } <del> <del> jsonString, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString) <del> } <del> return jsonString, imageSize, nil <del>} <del> <del>// GetRemoteImageLayer retrieves an image layer from the registry <del>func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) { <del> var ( <del> statusCode = 0 <del> res *http.Response <del> err error <del> imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) <del> ) <del> <del> req, err := http.NewRequest(http.MethodGet, imageURL, nil) <del> if err != nil { <del> return nil, fmt.Errorf("Error while getting from the server: %v", err) <del> } <del> <del> res, err = r.client.Do(req) <del> if err != nil { <del> logrus.Debugf("Error contacting registry %s: %v", registry, err) <del> // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515 <del> if res != nil { <del> if res.Body != nil { <del> res.Body.Close() <del> } <del> statusCode = res.StatusCode <del> } <del> return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", <del> statusCode, imgID) <del> } <del> <del> if res.StatusCode != http.StatusOK { <del> res.Body.Close() <del> return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", <del> res.StatusCode, imgID) <del> } <del> <del> if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { <del> logrus.Debug("server supports resume") <del> return resumable.NewRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil <del> } <del> logrus.Debug("server doesn't support resume") <del> return res.Body, nil <del>} <del> <del>// GetRemoteTag retrieves the tag named in the askedTag argument from the given <del>// repository. It queries each of the registries supplied in the registries <del>// argument, and returns data from the first one that answers the query <del>// successfully. <del>func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) { <del> repository := reference.Path(repositoryRef) <del> <del> if strings.Count(repository, "/") == 0 { <del> // This will be removed once the registry supports auto-resolution on <del> // the "library" namespace <del> repository = "library/" + repository <del> } <del> for _, host := range registries { <del> endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag) <del> res, err := r.client.Get(endpoint) <del> if err != nil { <del> return "", err <del> } <del> <del> logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) <del> defer res.Body.Close() <del> <del> if res.StatusCode == 404 { <del> return "", ErrRepoNotFound <del> } <del> if res.StatusCode != http.StatusOK { <del> continue <del> } <del> <del> var tagID string <del> if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil { <del> return "", err <del> } <del> return tagID, nil <del> } <del> return "", fmt.Errorf("Could not reach any registry endpoint") <del>} <del> <del>// GetRemoteTags retrieves all tags from the given repository. It queries each <del>// of the registries supplied in the registries argument, and returns data from <del>// the first one that answers the query successfully. It returns a map with <del>// tag names as the keys and image IDs as the values. <del>func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) { <del> repository := reference.Path(repositoryRef) <del> <del> if strings.Count(repository, "/") == 0 { <del> // This will be removed once the registry supports auto-resolution on <del> // the "library" namespace <del> repository = "library/" + repository <del> } <del> for _, host := range registries { <del> endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository) <del> res, err := r.client.Get(endpoint) <del> if err != nil { <del> return nil, err <del> } <del> <del> logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) <del> defer res.Body.Close() <del> <del> if res.StatusCode == 404 { <del> return nil, ErrRepoNotFound <del> } <del> if res.StatusCode != http.StatusOK { <del> continue <del> } <del> <del> result := make(map[string]string) <del> if err := json.NewDecoder(res.Body).Decode(&result); err != nil { <del> return nil, err <del> } <del> return result, nil <del> } <del> return nil, fmt.Errorf("Could not reach any registry endpoint") <del>} <del> <del>func buildEndpointsList(headers []string, indexEp string) ([]string, error) { <del> var endpoints []string <del> parsedURL, err := url.Parse(indexEp) <del> if err != nil { <del> return nil, err <del> } <del> var urlScheme = parsedURL.Scheme <del> // The registry's URL scheme has to match the Index' <del> for _, ep := range headers { <del> epList := strings.Split(ep, ",") <del> for _, epListElement := range epList { <del> endpoints = append( <del> endpoints, <del> fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement))) <del> } <del> } <del> return endpoints, nil <del>} <del> <del>// GetRepositoryData returns lists of images and endpoints for the repository <del>func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) { <del> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), reference.Path(name)) <del> <del> logrus.Debugf("[registry] Calling GET %s", repositoryTarget) <del> <del> req, err := http.NewRequest(http.MethodGet, repositoryTarget, nil) <del> if err != nil { <del> return nil, err <del> } <del> // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests <del> req.Header.Set("X-Docker-Token", "true") <del> res, err := r.client.Do(req) <del> if err != nil { <del> // check if the error is because of i/o timeout <del> // and return a non-obtuse error message for users <del> // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout" <del> // was a top search on the docker user forum <del> if isTimeout(err) { <del> return nil, fmt.Errorf("network timed out while trying to connect to %s. You may want to check your internet connection or if you are behind a proxy", repositoryTarget) <del> } <del> return nil, fmt.Errorf("Error while pulling image: %v", err) <del> } <del> defer res.Body.Close() <del> if res.StatusCode == http.StatusUnauthorized { <del> return nil, errcode.ErrorCodeUnauthorized.WithArgs() <del> } <del> // TODO: Right now we're ignoring checksums in the response body. <del> // In the future, we need to use them to check image validity. <del> if res.StatusCode == 404 { <del> return nil, newJSONError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res) <del> } else if res.StatusCode != http.StatusOK { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> logrus.Debugf("Error reading response body: %s", err) <del> } <del> return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, reference.Path(name), errBody), res) <del> } <del> <del> var endpoints []string <del> if res.Header.Get("X-Docker-Endpoints") != "" { <del> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) <del> if err != nil { <del> return nil, err <del> } <del> } else { <del> // Assume the endpoint is on the same host <del> endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host)) <del> } <del> <del> remoteChecksums := []*ImgData{} <del> if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil { <del> return nil, err <del> } <del> <del> // Forge a better object from the retrieved data <del> imgsData := make(map[string]*ImgData, len(remoteChecksums)) <del> for _, elem := range remoteChecksums { <del> imgsData[elem.ID] = elem <del> } <del> <del> return &RepositoryData{ <del> ImgList: imgsData, <del> Endpoints: endpoints, <del> }, nil <del>} <del> <del>// PushImageChecksumRegistry uploads checksums for an image <del>func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error { <del> u := registry + "images/" + imgData.ID + "/checksum" <del> <del> logrus.Debugf("[registry] Calling PUT %s", u) <del> <del> req, err := http.NewRequest(http.MethodPut, u, nil) <del> if err != nil { <del> return err <del> } <del> req.Header.Set("X-Docker-Checksum", imgData.Checksum) <del> req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload) <del> <del> res, err := r.client.Do(req) <del> if err != nil { <del> return fmt.Errorf("Failed to upload metadata: %v", err) <del> } <del> defer res.Body.Close() <del> if len(res.Cookies()) > 0 { <del> r.client.Jar.SetCookies(req.URL, res.Cookies()) <del> } <del> if res.StatusCode != http.StatusOK { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err) <del> } <del> var jsonBody map[string]string <del> if err := json.Unmarshal(errBody, &jsonBody); err != nil { <del> errBody = []byte(err.Error()) <del> } else if jsonBody["error"] == "Image already exists" { <del> return ErrAlreadyExists <del> } <del> return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody) <del> } <del> return nil <del>} <del> <del>// PushImageJSONRegistry pushes JSON metadata for a local image to the registry <del>func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error { <del> <del> u := registry + "images/" + imgData.ID + "/json" <del> <del> logrus.Debugf("[registry] Calling PUT %s", u) <del> <del> req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(jsonRaw)) <del> if err != nil { <del> return err <del> } <del> req.Header.Add("Content-type", "application/json") <del> <del> res, err := r.client.Do(req) <del> if err != nil { <del> return fmt.Errorf("Failed to upload metadata: %s", err) <del> } <del> defer res.Body.Close() <del> if res.StatusCode == http.StatusUnauthorized && strings.HasPrefix(registry, "http://") { <del> return newJSONError("HTTP code 401, Docker will not send auth headers over HTTP.", res) <del> } <del> if res.StatusCode != http.StatusOK { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) <del> } <del> var jsonBody map[string]string <del> if err := json.Unmarshal(errBody, &jsonBody); err != nil { <del> errBody = []byte(err.Error()) <del> } else if jsonBody["error"] == "Image already exists" { <del> return ErrAlreadyExists <del> } <del> return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res) <del> } <del> return nil <del>} <del> <del>// PushImageLayerRegistry sends the checksum of an image layer to the registry <del>func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) { <del> u := registry + "images/" + imgID + "/layer" <del> <del> logrus.Debugf("[registry] Calling PUT %s", u) <del> <del> tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0) <del> if err != nil { <del> return "", "", err <del> } <del> h := sha256.New() <del> h.Write(jsonRaw) <del> h.Write([]byte{'\n'}) <del> checksumLayer := io.TeeReader(tarsumLayer, h) <del> <del> req, err := http.NewRequest(http.MethodPut, u, checksumLayer) <del> if err != nil { <del> return "", "", err <del> } <del> req.Header.Add("Content-Type", "application/octet-stream") <del> req.ContentLength = -1 <del> req.TransferEncoding = []string{"chunked"} <del> res, err := r.client.Do(req) <del> if err != nil { <del> return "", "", fmt.Errorf("Failed to upload layer: %v", err) <del> } <del> if rc, ok := layer.(io.Closer); ok { <del> if err := rc.Close(); err != nil { <del> return "", "", err <del> } <del> } <del> defer res.Body.Close() <del> <del> if res.StatusCode != http.StatusOK { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> return "", "", newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) <del> } <del> return "", "", newJSONError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res) <del> } <del> <del> checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil)) <del> return tarsumLayer.Sum(jsonRaw), checksumPayload, nil <del>} <del> <del>// PushRegistryTag pushes a tag on the registry. <del>// Remote has the format '<user>/<repo> <del>func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error { <del> // "jsonify" the string <del> revision = "\"" + revision + "\"" <del> path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag) <del> <del> req, err := http.NewRequest(http.MethodPut, registry+path, strings.NewReader(revision)) <del> if err != nil { <del> return err <del> } <del> req.Header.Add("Content-type", "application/json") <del> req.ContentLength = int64(len(revision)) <del> res, err := r.client.Do(req) <del> if err != nil { <del> return err <del> } <del> res.Body.Close() <del> if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { <del> return newJSONError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res) <del> } <del> return nil <del>} <del> <del>// PushImageJSONIndex uploads an image list to the repository <del>func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) { <del> cleanImgList := []*ImgData{} <del> if validate { <del> for _, elem := range imgList { <del> if elem.Checksum != "" { <del> cleanImgList = append(cleanImgList, elem) <del> } <del> } <del> } else { <del> cleanImgList = imgList <del> } <del> <del> imgListJSON, err := json.Marshal(cleanImgList) <del> if err != nil { <del> return nil, err <del> } <del> var suffix string <del> if validate { <del> suffix = "images" <del> } <del> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), reference.Path(remote), suffix) <del> logrus.Debugf("[registry] PUT %s", u) <del> logrus.Debugf("Image list pushed to index:\n%s", imgListJSON) <del> headers := map[string][]string{ <del> "Content-type": {"application/json"}, <del> // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests <del> "X-Docker-Token": {"true"}, <del> } <del> if validate { <del> headers["X-Docker-Endpoints"] = regs <del> } <del> <del> // Redirect if necessary <del> var res *http.Response <del> for { <del> if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil { <del> return nil, err <del> } <del> if !shouldRedirect(res) { <del> break <del> } <del> res.Body.Close() <del> u = res.Header.Get("Location") <del> logrus.Debugf("Redirected to %s", u) <del> } <del> defer res.Body.Close() <del> <del> if res.StatusCode == http.StatusUnauthorized { <del> return nil, errcode.ErrorCodeUnauthorized.WithArgs() <del> } <del> <del> var tokens, endpoints []string <del> if !validate { <del> if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> logrus.Debugf("Error reading response body: %s", err) <del> } <del> return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, reference.Path(remote), errBody), res) <del> } <del> tokens = res.Header["X-Docker-Token"] <del> logrus.Debugf("Auth token: %v", tokens) <del> <del> if res.Header.Get("X-Docker-Endpoints") == "" { <del> return nil, fmt.Errorf("Index response didn't contain any endpoints") <del> } <del> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) <del> if err != nil { <del> return nil, err <del> } <del> } else { <del> if res.StatusCode != http.StatusNoContent { <del> errBody, err := ioutil.ReadAll(res.Body) <del> if err != nil { <del> logrus.Debugf("Error reading response body: %s", err) <del> } <del> return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, reference.Path(remote), errBody), res) <del> } <del> } <del> <del> return &RepositoryData{ <del> Endpoints: endpoints, <del> }, nil <del>} <del> <del>func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) { <del> req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(body)) <del> if err != nil { <del> return nil, err <del> } <del> req.ContentLength = int64(len(body)) <del> for k, v := range headers { <del> req.Header[k] = v <del> } <del> response, err := r.client.Do(req) <del> if err != nil { <del> return nil, err <del> } <del> return response, nil <del>} <del> <del>func shouldRedirect(response *http.Response) bool { <del> return response.StatusCode >= 300 && response.StatusCode < 400 <del>} <del> <ide> // SearchRepositories performs a search against the remote repository <ide> func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) { <ide> if limit < 1 || limit > 100 { <ide> func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.Sea <ide> } <ide> defer res.Body.Close() <ide> if res.StatusCode != http.StatusOK { <del> return nil, newJSONError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) <add> return nil, &jsonmessage.JSONError{ <add> Message: fmt.Sprintf("Unexpected status code %d", res.StatusCode), <add> Code: res.StatusCode, <add> } <ide> } <ide> result := new(registrytypes.SearchResults) <ide> return result, errors.Wrap(json.NewDecoder(res.Body).Decode(result), "error decoding registry search results") <ide> } <del> <del>func isTimeout(err error) bool { <del> type timeout interface { <del> Timeout() bool <del> } <del> e := err <del> switch urlErr := err.(type) { <del> case *url.Error: <del> e = urlErr.Err <del> } <del> t, ok := e.(timeout) <del> return ok && t.Timeout() <del>} <del> <del>func newJSONError(msg string, res *http.Response) error { <del> return &jsonmessage.JSONError{ <del> Message: msg, <del> Code: res.StatusCode, <del> } <del>}
3
Mixed
Javascript
provide access to $xhr header defaults
c5f3a413bc00acf9ac1046fb15b454096a8890c6
<ide><path>CHANGELOG.md <ide> - New [ng:disabled], [ng:selected], [ng:checked], [ng:multiple] and [ng:readonly] directives. <ide> - Added support for string representation of month and day in [date] filter. <ide> - Added support for `prepend()` to [jqLite]. <add>- Added support for configurable HTTP header defaults for the [$xhr] service. <ide> <ide> <ide> ### Bug Fixes <ide><path>src/Browser.js <ide> var XHR = window.XMLHttpRequest || function () { <ide> throw new Error("This browser does not support XMLHttpRequest."); <ide> }; <ide> <del>// default xhr headers <del>var XHR_HEADERS = { <del> DEFAULT: { <del> "Accept": "application/json, text/plain, */*", <del> "X-Requested-With": "XMLHttpRequest" <del> }, <del> POST: {'Content-Type': 'application/x-www-form-urlencoded'} <del>}; <ide> <ide> /** <ide> * @private <ide> function Browser(window, document, body, XHR, $log) { <ide> } else { <ide> var xhr = new XHR(); <ide> xhr.open(method, url, true); <del> forEach(extend({}, XHR_HEADERS.DEFAULT, XHR_HEADERS[uppercase(method)] || {}, headers || {}), <del> function(value, key) { <add> forEach(headers, function(value, key) { <ide> if (value) xhr.setRequestHeader(key, value); <ide> }); <ide> xhr.onreadystatechange = function() { <ide><path>src/service/xhr.js <ide> * and process it in application specific way, or resume normal execution by calling the <ide> * request callback method. <ide> * <add> * # HTTP Headers <add> * The $xhr service will automatically add certain http headers to all requests. These defaults can <add> * be fully configured by accessing the `$xhr.defaults.headers` configuration object, which <add> * currently contains this default configuration: <add> * <add> * - `$xhr.defaults.headers.common` (headers that are common for all requests): <add> * - `Accept: application/json, text/plain, *\/*` <add> * - `X-Requested-With: XMLHttpRequest` <add> * - `$xhr.defaults.headers.post` (header defaults for HTTP POST requests): <add> * - `Content-Type: application/x-www-form-urlencoded` <add> * <add> * To add or overwrite these defaults, simple add or remove a property from this configuration <add> * object. To add headers for an HTTP method other than POST, simple create a new object with name <add> * equal to the lowercased http method name, e.g. `$xhr.defaults.headers.get['My-Header']='value'`. <add> * <add> * <ide> * # Security Considerations <ide> * When designing web applications your design needs to consider security threats from <ide> * {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx <ide> </doc:example> <ide> */ <ide> angularServiceInject('$xhr', function($browser, $error, $log, $updateView){ <del> return function(method, url, post, callback){ <add> <add> var xhrHeaderDefaults = { <add> common: { <add> "Accept": "application/json, text/plain, */*", <add> "X-Requested-With": "XMLHttpRequest" <add> }, <add> post: {'Content-Type': 'application/x-www-form-urlencoded'}, <add> get: {}, // all these empty properties are needed so that client apps can just do: <add> head: {}, // $xhr.defaults.headers.head.foo="bar" without having to create head object <add> put: {}, // it also means that if we add a header for these methods in the future, it <add> 'delete': {}, // won't be easily silently lost due to an object assignment. <add> patch: {} <add> }; <add> <add> function xhr(method, url, post, callback){ <ide> if (isFunction(post)) { <ide> callback = post; <ide> post = null; <ide> angularServiceInject('$xhr', function($browser, $error, $log, $updateView){ <ide> } finally { <ide> $updateView(); <ide> } <del> }, { <del> 'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN'] <del> }); <add> }, extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, <add> xhrHeaderDefaults.common, <add> xhrHeaderDefaults[lowercase(method)])); <ide> }; <add> <add> xhr.defaults = {headers: xhrHeaderDefaults}; <add> <add> return xhr; <ide> }, ['$browser', '$xhr.error', '$log', '$updateView']); <ide><path>test/BrowserSpecs.js <ide> describe('browser', function(){ <ide> }); <ide> }); <ide> <del> it('should set headers for all requests', function(){ <del> var code, response, headers = {}; <del> browser.xhr('GET', 'URL', 'POST', function(c,r){ <del> code = c; <del> response = r; <del> }, {'X-header': 'value'}); <del> <del> expect(xhr.method).toEqual('GET'); <del> expect(xhr.url).toEqual('URL'); <del> expect(xhr.post).toEqual('POST'); <del> expect(xhr.headers).toEqual({ <del> "Accept": "application/json, text/plain, */*", <del> "X-Requested-With": "XMLHttpRequest", <del> "X-header":"value" <del> }); <del> <del> xhr.status = 202; <del> xhr.responseText = 'RESPONSE'; <del> xhr.readyState = 4; <del> xhr.onreadystatechange(); <del> <del> expect(code).toEqual(202); <del> expect(response).toEqual('RESPONSE'); <del> }); <del> <ide> it('should normalize IE\'s 1223 status code into 204', function() { <ide> var callback = jasmine.createSpy('XHR'); <ide> <ide> describe('browser', function(){ <ide> expect(callback.argsForCall[0][0]).toEqual(204); <ide> }); <ide> <del> it('should not set Content-type header for GET requests', function() { <del> browser.xhr('GET', 'URL', 'POST-DATA', function(c, r) {}); <del> <del> expect(xhr.headers['Content-Type']).not.toBeDefined(); <del> }); <del> <del> it('should set Content-type header for POST requests', function() { <del> browser.xhr('POST', 'URL', 'POST-DATA', function(c, r) {}); <add> it('should set only the requested headers', function() { <add> var code, response, headers = {}; <add> browser.xhr('POST', 'URL', null, function(c,r){ <add> code = c; <add> response = r; <add> }, {'X-header1': 'value1', 'X-header2': 'value2'}); <ide> <del> expect(xhr.headers['Content-Type']).toBeDefined(); <del> expect(xhr.headers['Content-Type']).toEqual('application/x-www-form-urlencoded'); <del> }); <add> expect(xhr.method).toEqual('POST'); <add> expect(xhr.url).toEqual('URL'); <add> expect(xhr.post).toEqual(''); <add> expect(xhr.headers).toEqual({ <add> "X-header1":"value1", <add> "X-header2":"value2" <add> }); <ide> <del> it('should set default headers for custom methods', function() { <del> browser.xhr('CUSTOM', 'URL', 'POST-DATA', function(c, r) {}); <add> xhr.status = 202; <add> xhr.responseText = 'RESPONSE'; <add> xhr.readyState = 4; <add> xhr.onreadystatechange(); <ide> <del> expect(xhr.headers['Accept']).toEqual('application/json, text/plain, */*'); <del> expect(xhr.headers['X-Requested-With']).toEqual('XMLHttpRequest'); <add> expect(code).toEqual(202); <add> expect(response).toEqual('RESPONSE'); <ide> }); <ide> }); <ide> <ide><path>test/service/xhrSpec.js <ide> describe('$xhr', function() { <ide> expect(response).toEqual([1, 'abc', {foo:'bar'}]); <ide> }); <ide> <add> <add> describe('http headers', function() { <add> <add> describe('default headers', function() { <add> <add> it('should set default headers for GET request', function(){ <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest'}). <add> respond(234, 'OK'); <add> <add> $xhr('GET', 'URL', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> <add> it('should set default headers for POST request', function(){ <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest', <add> 'Content-Type': 'application/x-www-form-urlencoded'}). <add> respond(200, 'OK'); <add> <add> $xhr('POST', 'URL', 'xx', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> <add> it('should set default headers for custom HTTP method', function(){ <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expect('FOO', 'URL', '', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest'}). <add> respond(200, 'OK'); <add> <add> $xhr('FOO', 'URL', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> <add> describe('custom headers', function() { <add> <add> it('should allow appending a new header to the common defaults', function() { <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest', <add> 'Custom-Header': 'value'}). <add> respond(200, 'OK'); <add> <add> $xhr.defaults.headers.common['Custom-Header'] = 'value'; <add> $xhr('GET', 'URL', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> callback.reset(); <add> <add> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest', <add> 'Content-Type': 'application/x-www-form-urlencoded', <add> 'Custom-Header': 'value'}). <add> respond(200, 'OK'); <add> <add> $xhr('POST', 'URL', 'xx', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> <add> it('should allow appending a new header to a method specific defaults', function() { <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest', <add> 'Content-Type': 'application/json'}). <add> respond(200, 'OK'); <add> <add> $xhr.defaults.headers.get['Content-Type'] = 'application/json'; <add> $xhr('GET', 'URL', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> callback.reset(); <add> <add> $browserXhr.expectPOST('URL', 'x', {'Accept': 'application/json, text/plain, */*', <add> 'X-Requested-With': 'XMLHttpRequest', <add> 'Content-Type': 'application/x-www-form-urlencoded'}). <add> respond(200, 'OK'); <add> <add> $xhr('POST', 'URL', 'x', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> <add> it('should support overwriting and deleting default headers', function() { <add> var callback = jasmine.createSpy('callback'); <add> <add> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*'}). <add> respond(200, 'OK'); <add> <add> //delete a default header <add> delete $xhr.defaults.headers.common['X-Requested-With']; <add> $xhr('GET', 'URL', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> callback.reset(); <add> <add> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*', <add> 'Content-Type': 'application/json'}). <add> respond(200, 'OK'); <add> <add> //overwrite a default header <add> $xhr.defaults.headers.post['Content-Type'] = 'application/json'; <add> $xhr('POST', 'URL', 'xx', callback); <add> $browserXhr.flush(); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> }); <add> }); <add> }); <add> <ide> describe('xsrf', function(){ <ide> it('should copy the XSRF cookie into a XSRF Header', function(){ <ide> var code, response;
5
Text
Text
fix a small typo in `docs/deprecated.md`
45e5b2552ab1ca685e88e0feeedc92fb817d8567
<ide><path>docs/deprecated.md <ide> filesystem does not support `d_type`. For example, XFS does not support `d_type` <ide> if it is formatted with the `ftype=0` option. <ide> <ide> Please also refer to [#27358](https://github.com/docker/docker/issues/27358) for <del>futher information. <add>further information. <ide> <ide> ### Three argument form in `docker import` <ide> **Deprecated In Release: [v0.6.7](https://github.com/docker/docker/releases/tag/v0.6.7)**
1
Javascript
Javascript
update vectorkeyframetrack inheritance
a400150ede2af942095d33eeb4243fc1c00a49a5
<ide><path>src/animation/tracks/VectorKeyframeTrack.js <del>import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype.js'; <del>import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <add>import { KeyframeTrack } from '../KeyframeTrack.js'; <ide> <ide> /** <ide> * <ide> import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js'; <ide> <ide> function VectorKeyframeTrack( name, times, values, interpolation ) { <ide> <del> KeyframeTrackConstructor.call( this, name, times, values, interpolation ); <add> KeyframeTrack.call( this, name, times, values, interpolation ); <ide> <ide> } <ide> <del>VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrackPrototype ), { <add>VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { <ide> <ide> constructor: VectorKeyframeTrack, <ide>
1
Javascript
Javascript
add annotations to example
547871e779f7a1e340c03296405735415764a0e8
<ide><path>src/loader.js <ide> function setupModuleLoader(window) { <ide> * myModule.value('appName', 'MyCoolApp'); <ide> * <ide> * // configure existing services inside initialization blocks. <del> * myModule.config(function($locationProvider) { <add> * myModule.config(['$locationProvider', function($locationProvider) { <ide> * // Configure existing providers <ide> * $locationProvider.hashPrefix('!'); <del> * }); <add> * }]); <ide> * ``` <ide> * <ide> * Then you can create an injector and load your modules like this:
1
Ruby
Ruby
use hash defaults to dry up ||= calls
77a6e2558475b80481739c091a873bf39f46cf3b
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> class Fixtures <ide> MAX_ID = 2 ** 30 - 1 <ide> DEFAULT_FILTER_RE = /\.ya?ml$/ <ide> <del> @@all_cached_fixtures = {} <add> @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} } <ide> <ide> def self.find_table_name(table_name) # :nodoc: <ide> ActiveRecord::Base.pluralize_table_names ? <ide> def self.find_table_name(table_name) # :nodoc: <ide> <ide> def self.reset_cache(connection = nil) <ide> connection ||= ActiveRecord::Base.connection <del> @@all_cached_fixtures[connection.object_id] = {} <add> @@all_cached_fixtures.delete connection.object_id <ide> end <ide> <ide> def self.cache_for_connection(connection) <del> @@all_cached_fixtures[connection.object_id] ||= {} <ide> @@all_cached_fixtures[connection.object_id] <ide> end <ide> <ide> def self.cache_fixtures(connection, fixtures_map) <ide> def self.instantiate_fixtures(object, table_name, fixtures, load_instances = true) <ide> object.instance_variable_set "@#{table_name.to_s.gsub('.','_')}", fixtures <ide> if load_instances <del> ActiveRecord::Base.silence do <del> fixtures.each do |name, fixture| <del> begin <del> object.instance_variable_set "@#{name}", fixture.find <del> rescue FixtureClassNotFound <del> nil <del> end <add> fixtures.each do |name, fixture| <add> begin <add> object.instance_variable_set "@#{name}", fixture.find <add> rescue FixtureClassNotFound <add> nil <ide> end <ide> end <ide> end <ide> def self.create_fixtures(fixtures_directory, table_names, class_names = {}) <ide> table_names_to_fetch = table_names.reject { |table_name| fixture_is_cached?(connection, table_name) } <ide> <ide> unless table_names_to_fetch.empty? <del> ActiveRecord::Base.silence do <del> connection.disable_referential_integrity do <del> fixtures_map = {} <add> connection.disable_referential_integrity do <add> fixtures_map = {} <ide> <del> fixtures = table_names_to_fetch.map do |table_name| <del> fixtures_map[table_name] = Fixtures.new(connection, table_name.tr('/', '_'), class_names[table_name.tr('/', '_').to_sym], File.join(fixtures_directory, table_name)) <del> end <add> fixtures = table_names_to_fetch.map do |table_name| <add> fixtures_map[table_name] = Fixtures.new(connection, table_name.tr('/', '_'), class_names[table_name.tr('/', '_').to_sym], File.join(fixtures_directory, table_name)) <add> end <ide> <del> all_loaded_fixtures.update(fixtures_map) <add> all_loaded_fixtures.update(fixtures_map) <ide> <del> connection.transaction(:requires_new => true) do <del> fixtures.reverse.each { |fixture| fixture.delete_existing_fixtures } <del> fixtures.each { |fixture| fixture.insert_fixtures } <add> connection.transaction(:requires_new => true) do <add> fixtures.reverse.each { |fixture| fixture.delete_existing_fixtures } <add> fixtures.each { |fixture| fixture.insert_fixtures } <ide> <del> # Cap primary key sequences to max(pk). <del> if connection.respond_to?(:reset_pk_sequence!) <del> table_names.each do |table_name| <del> connection.reset_pk_sequence!(table_name.tr('/', '_')) <del> end <add> # Cap primary key sequences to max(pk). <add> if connection.respond_to?(:reset_pk_sequence!) <add> table_names.each do |table_name| <add> connection.reset_pk_sequence!(table_name.tr('/', '_')) <ide> end <ide> end <del> <del> cache_fixtures(connection, fixtures_map) <ide> end <add> <add> cache_fixtures(connection, fixtures_map) <ide> end <ide> end <ide> cached_fixtures(connection, table_names)
1
Ruby
Ruby
remove unnecessary @compiled_root from static.rb
3c217faa860d70bb26912864bfd1eca76142b1b9
<ide><path>actionpack/lib/action_dispatch/middleware/static.rb <ide> module ActionDispatch <ide> class FileHandler <ide> def initialize(root, index: 'index', headers: {}) <ide> @root = root.chomp('/') <del> @compiled_root = /^#{Regexp.escape(root)}/ <ide> @file_server = ::Rack::File.new(@root, headers) <ide> @index = index <ide> end
1
Javascript
Javascript
make $sniffer service private
aaedefb92e6bec6626e173e5155072c91471596a
<ide><path>src/service/sniffer.js <ide> 'use strict'; <ide> <ide> /** <del> * @ngdoc object <add> * !!! This is an undocumented "private" service !!! <add> * <ide> * @name angular.module.ng.$sniffer <ide> * @requires $window <ide> * <ide> */ <ide> function $SnifferProvider(){ <ide> this.$get = ['$window', function($window){ <del> if ($window.Modernizr) return $window.Modernizr; <del> <ide> return { <ide> history: !!($window.history && $window.history.pushState), <ide> hashchange: 'onhashchange' in $window && <ide><path>test/service/snifferSpec.js <ide> describe('$sniffer', function() { <ide> expect(sniffer({onhashchange: true, document: {documentMode: 7}}).hashchange).toBe(false); <ide> }); <ide> }); <del> <del> it('should use Modernizr if defined', function() { <del> var Modernizr = {}; <del> expect(sniffer({Modernizr: Modernizr})).toBe(Modernizr); <del> }); <ide> });
2
Javascript
Javascript
exclude lots of native node module cruft
1895121784e4262970550988e3f01b4ca5dcf562
<ide><path>script/lib/include-path-in-packaged-app.js <ide> const EXCLUDE_REGEXPS_SOURCES = [ <ide> escapeRegExp(path.join('node_modules', 'pegjs')), <ide> escapeRegExp(path.join('node_modules', '.bin', 'pegjs')), <ide> escapeRegExp(path.join('node_modules', 'spellchecker', 'vendor', 'hunspell') + path.sep) + '.*', <del> escapeRegExp(path.join('build', 'Release') + path.sep) + '.*\\.pdb', <ide> <ide> // Ignore *.cc and *.h files from native modules <ide> escapeRegExp(path.sep) + '.+\\.(cc|h)$', <ide> const EXCLUDE_REGEXPS_SOURCES = [ <ide> escapeRegExp(path.sep) + '.+\\.target.mk$', <ide> escapeRegExp(path.sep) + 'linker\\.lock$', <ide> escapeRegExp(path.join('build', 'Release') + path.sep) + '.+\\.node\\.dSYM', <add> escapeRegExp(path.join('build', 'Release') + path.sep) + '.*\\.(pdb|lib|exp|map|ipdb|iobj)', <ide> <ide> // Ignore test and example folders <ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + '_*te?sts?_*' + escapeRegExp(path.sep),
1
Mixed
Javascript
replace `onevent` by `before/afterevent`
7205ff5e2aa4515bae0c62bb9d8355745837270e
<ide><path>docs/09-Advanced.md <ide> Plugins should implement the `IPlugin` interface: <ide> <ide> destroy: function(chartInstance) { } <ide> <del> /** <del> * Called when an event occurs on the chart <del> * @param e {Core.Event} the Chart.js wrapper around the native event. e.native is the original event <del> * @return {Boolean} true if the chart is changed and needs to re-render <del> */ <del> onEvent: function(chartInstance, e) {} <add> // Called when an event occurs on the chart <add> beforeEvent: function(chartInstance, event) {} <add> afterEvent: function(chartInstance, event) {} <ide> } <ide> ``` <ide> <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> eventHandler: function(e) { <ide> var me = this; <ide> var tooltip = me.tooltip; <del> var hoverOptions = me.options.hover; <add> <add> if (plugins.notify(me, 'beforeEvent', [e]) === false) { <add> return; <add> } <ide> <ide> // Buffer any update calls so that renders do not occur <ide> me._bufferedRender = true; <ide> me._bufferedRequest = null; <ide> <ide> var changed = me.handleEvent(e); <ide> changed |= tooltip && tooltip.handleEvent(e); <del> changed |= plugins.notify(me, 'onEvent', [e]); <add> <add> plugins.notify(me, 'afterEvent', [e]); <ide> <ide> var bufferedRequest = me._bufferedRequest; <ide> if (bufferedRequest) { <ide> module.exports = function(Chart) { <ide> <ide> // We only need to render at this point. Updating will cause scales to be <ide> // recomputed generating flicker & using more memory than necessary. <del> me.render(hoverOptions.animationDuration, true); <add> me.render(me.options.hover.animationDuration, true); <ide> } <ide> <ide> me._bufferedRender = false; <ide><path>src/core/core.legend.js <ide> module.exports = function(Chart) { <ide> delete chartInstance.legend; <ide> } <ide> }, <del> onEvent: function(chartInstance, e) { <add> afterEvent: function(chartInstance, e) { <ide> var legend = chartInstance.legend; <ide> if (legend) { <ide> legend.handleEvent(e); <ide><path>src/core/core.plugin.js <ide> module.exports = function(Chart) { <ide> * @param {Number} easingValue - The current animation value, between 0.0 and 1.0. <ide> * @param {Object} options - The plugin options. <ide> */ <add> /** <add> * @method IPlugin#beforeEvent <add> * @desc Called before processing the specified `event`. If any plugin returns `false`, <add> * the event will be discarded. <add> * @param {Chart.Controller} chart - The chart instance. <add> * @param {IEvent} event - The event object. <add> * @param {Object} options - The plugin options. <add> */ <add> /** <add> * @method IPlugin#afterEvent <add> * @desc Called after the `event` has been consumed. Note that this hook <add> * will not be called if the `event` has been previously discarded. <add> * @param {Chart.Controller} chart - The chart instance. <add> * @param {IEvent} event - The event object. <add> * @param {Object} options - The plugin options. <add> */ <ide> /** <ide> * @method IPlugin#resize <ide> * @desc Called after the chart as been resized. <ide><path>test/platform.dom.tests.js <ide> describe('Platform.dom', function() { <ide> it('should notify plugins about events', function() { <ide> var notifiedEvent; <ide> var plugin = { <del> onEvent: function(chart, e) { <add> afterEvent: function(chart, e) { <ide> notifiedEvent = e; <ide> } <ide> };
5
Ruby
Ruby
organize the matchers a bit more
3ab6ae0c601d1b4459efd8bb39650fee370aa5b8
<ide><path>spec/algebra/integration/basic_spec.rb <ide> require 'spec_helper' <ide> <del>def have_rows(expected) <del> simple_matcher "have rows" do |given, matcher| <del> found, got, expected = [], [], expected.map { |r| r.tuple } <del> given.each do |row| <del> got << row.tuple <del> found << expected.find { |r| row.tuple == r } <del> end <del> <del> matcher.failure_message = "Expected to get:\n" \ <del> "#{expected.map {|r| " #{r.inspect}" }.join("\n")}\n" \ <del> "instead, got:\n" \ <del> "#{got.map {|r| " #{r.inspect}" }.join("\n")}" <del> <del> found.compact.length == expected.length && got.compact.length == expected.length <del> end <del>end <del> <del>share_examples_for 'A Relation' do <del> <del> before :all do <del> # The two needed instance variables need to be set in a <del> # before :all callback. <del> # @relation is the relation being tested here. <del> # @expected is an array of the elements that are expected to be in <del> # the relation. <del> %w[ @relation @expected ].each do |ivar| <del> raise "#{ivar} needs to be defined" unless instance_variable_get(ivar) <del> end <del> <del> # There needs to be enough items to be able to run all the tests <del> raise "@expected needs to have at least 6 items" unless @expected.length >= 6 <del> end <del> <del> describe "#each" do <del> it "iterates over the rows in any order" do <del> @relation.should have_rows(@expected) <del> end <del> end <del> <del> describe "#where" do <del> before :all do <del> @expected = @expected.sort_by { |r| r[@relation[:age]] } <del> @pivot = @expected[@expected.length / 2] <del> end <del> <del> it "finds rows with an equal to predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] == @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].eq(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a not predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] != @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].not(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a less than predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] < @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].lt(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a less than or equal to predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] <= @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].lteq(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a greater than predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] > @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].gt(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a greater than or equal to predicate" do <del> expected = @expected.select { |r| r[@relation[:age]] >= @pivot[@relation[:age]] } <del> @relation.where(@relation[:age].gteq(@pivot[@relation[:age]])).should have_rows(expected) <del> end <del> <del> it "finds rows with a matches predicate" <del> <del> it "finds rows with an in predicate" do <del> pending <del> set = @expected[1..(@expected.length/2+1)] <del> @relation.all(:id.in => set.map { |r| r.id }).should have_resources(set) <del> end <del> end <del>end <del> <ide> module Arel <ide> describe "Relation" do <del> <ide> before :all do <ide> @engine = Testing::Engine.new <ide> @relation = Model.build do |r| <ide> module Arel <ide> @engine.rows.should == [[1, 'Foo', 10]] <ide> end <ide> end <del> <ide> end <ide> end <ide>\ No newline at end of file <ide><path>spec/shared/relation_spec.rb <add>share_examples_for 'A Relation' do <add> <add> before :all do <add> # The two needed instance variables need to be set in a <add> # before :all callback. <add> # @relation is the relation being tested here. <add> # @expected is an array of the elements that are expected to be in <add> # the relation. <add> %w[ @relation @expected ].each do |ivar| <add> raise "#{ivar} needs to be defined" unless instance_variable_get(ivar) <add> end <add> <add> # There needs to be enough items to be able to run all the tests <add> raise "@expected needs to have at least 6 items" unless @expected.length >= 6 <add> end <add> <add> describe "#each" do <add> it "iterates over the rows in any order" do <add> @relation.should have_rows(@expected) <add> end <add> end <add> <add> describe "#where" do <add> before :all do <add> @expected = @expected.sort_by { |r| r[@relation[:age]] } <add> @pivot = @expected[@expected.length / 2] <add> end <add> <add> it "finds rows with an equal to predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] == @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].eq(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a not predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] != @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].not(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a less than predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] < @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].lt(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a less than or equal to predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] <= @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].lteq(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a greater than predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] > @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].gt(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a greater than or equal to predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] >= @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].gteq(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a matches predicate" <add> <add> it "finds rows with an in predicate" do <add> pending <add> set = @expected[1..(@expected.length/2+1)] <add> @relation.all(:id.in => set.map { |r| r.id }).should have_resources(set) <add> end <add> end <add> <add> describe "#order" do <add> describe "by one attribute" do <add> before :all do <add> @expected.map! { |r| r[@relation[:age]] } <add> @expected.sort! <add> end <add> <add> it "can be specified as ascending order" do <add> actual = [] <add> @relation.order(@relation[:age].asc).each { |r| actual << r[@relation[:age]] } <add> actual.should == @expected <add> end <add> <add> it "can be specified as descending order" do <add> actual = [] <add> @relation.order(@relation[:age].desc).each { |r| actual << r[@relation[:age]] } <add> actual.should == @expected.reverse <add> end <add> end <add> <add> describe "by two attributes" do <add> it "works" <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/spec_helper.rb <ide> require 'fileutils' <ide> require 'arel' <ide> <del>Dir["#{dir}/support/*.rb"].each do |file| <add>Dir["#{dir}/{support,shared}/*.rb"].each do |file| <ide> require file <ide> end <ide> <ide> Spec::Runner.configure do |config| <del> config.include BeLikeMatcher, HashTheSameAsMatcher, DisambiguateAttributesMatcher <add> config.include Matchers <ide> config.include AdapterGuards <ide> config.include Check <ide> <ide><path>spec/support/matchers.rb <ide> require "support/matchers/be_like" <ide> require "support/matchers/disambiguate_attributes" <del>require "support/matchers/hash_the_same_as" <ide>\ No newline at end of file <add>require "support/matchers/hash_the_same_as" <add>require "support/matchers/have_rows" <ide>\ No newline at end of file <ide><path>spec/support/matchers/be_like.rb <del>module BeLikeMatcher <add>module Matchers <ide> class BeLike <ide> def initialize(expected) <ide> @expected = expected <ide><path>spec/support/matchers/disambiguate_attributes.rb <del>module DisambiguateAttributesMatcher <add>module Matchers <ide> class DisambiguateAttributes <ide> def initialize(attributes) <ide> @attributes = attributes <ide><path>spec/support/matchers/hash_the_same_as.rb <del>module HashTheSameAsMatcher <add>module Matchers <ide> class HashTheSameAs <ide> def initialize(expected) <ide> @expected = expected <ide><path>spec/support/matchers/have_rows.rb <add>module Matchers <add> def have_rows(expected) <add> simple_matcher "have rows" do |given, matcher| <add> found, got, expected = [], [], expected.map { |r| r.tuple } <add> given.each do |row| <add> got << row.tuple <add> found << expected.find { |r| row.tuple == r } <add> end <add> <add> matcher.failure_message = "Expected to get:\n" \ <add> "#{expected.map {|r| " #{r.inspect}" }.join("\n")}\n" \ <add> "instead, got:\n" \ <add> "#{got.map {|r| " #{r.inspect}" }.join("\n")}" <add> <add> found.compact.length == expected.length && got.compact.length == expected.length <add> end <add> end <add>end <ide>\ No newline at end of file
8
Python
Python
fix wrong import
97f2e0d810a9bf539061bdac588e4f5dc03a5561
<ide><path>libcloud/container/drivers/kubernetes.py <ide> from libcloud.compute.base import NodeImage <ide> <ide> from libcloud.utils.misc import to_n_cpus <del>from libcloud.utils.mist import to_cpu_str <add>from libcloud.utils.misc import to_cpu_str <ide> from libcloud.utils.misc import to_memory_str <ide> from libcloud.utils.misc import to_n_bytes <ide>
1
Python
Python
pass regression test for #401 (resolves #401)
d0b85faf692ac37ff435c05148b0c7d7212effe1
<ide><path>spacy/tests/regression/test_issue401.py <ide> import pytest <ide> <ide> <del>@pytest.mark.xfail <ide> @pytest.mark.models <ide> @pytest.mark.parametrize('text,i', [("Jane's got a new car", 1), <ide> ("Jane thinks that's a nice car", 3)])
1
Javascript
Javascript
add strictequal method to assert
1593237ecc8b3710fa024cbd7afa30c48b1541aa
<ide><path>test/parallel/test-http2-create-client-secure-session.js <ide> function onStream(stream, headers) { <ide> const socket = stream.session[kSocket]; <ide> <ide> assert(stream.session.encrypted); <del> assert(stream.session.alpnProtocol, 'h2'); <add> assert.strictEqual(stream.session.alpnProtocol, 'h2'); <ide> const originSet = stream.session.originSet; <ide> assert(Array.isArray(originSet)); <ide> assert.strictEqual(originSet[0],
1
Text
Text
update copyright year in license to 2014
51032692f335db8b75411a097810b5e7740fc871
<ide><path>LICENSE.md <del>Copyright (c) 2013 Nick Downie <add>Copyright (c) 2014 Nick Downie <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: <ide>
1
Javascript
Javascript
simplify unique titles test
d6f217c1b956517ff36bf192f273940473bc6d5e
<ide><path>seed/challengeTitles.js <ide> class ChallengeTitles { <ide> } <ide> check(title) { <ide> if (typeof title !== 'string') { <del> throw new Error(`Expected a valid string for ${title}, got ${typeof title}`); <add> throw new Error(`Expected a valid string for ${title}, but got a(n) ${typeof title}`); <ide> } else if (title.length === 0) { <ide> throw new Error(`Expected a title length greater than 0`); <ide> } <ide> const titleToCheck = title.toLowerCase().replace(/\s+/g, ''); <del> const titleIndex = _.findIndex(this.knownTitles, existing => titleToCheck === existing); <del> if (titleIndex !== -1) { <add> const isKnown = this.knownTitles.includes(titleToCheck); <add> if (isKnown) { <ide> throw new Error(` <ide> All challenges must have a unique title. <ide>
1
Python
Python
update tokenizer exceptions for german
702d1eed930b354e5fece66142fe938d68fbd672
<ide><path>spacy/de/tokenizer_exceptions.py <ide> from __future__ import unicode_literals <ide> <ide> from ..symbols import * <del>from ..language_data import PRON_LEMMA <add>from ..language_data import PRON_LEMMA, DET_LEMMA <ide> <ide> <ide> TOKENIZER_EXCEPTIONS = { <ide> ], <ide> <ide> "'S": [ <del> {ORTH: "'S", LEMMA: PRON_LEMMA} <add> {ORTH: "'S", LEMMA: PRON_LEMMA, TAG: "PPER"} <ide> ], <ide> <ide> "'n": [ <del> {ORTH: "'n", LEMMA: "ein"} <add> {ORTH: "'n", LEMMA: DET_LEMMA, NORM: "ein"} <ide> ], <ide> <ide> "'ne": [ <del> {ORTH: "'ne", LEMMA: "eine"} <add> {ORTH: "'ne", LEMMA: DET_LEMMA, NORM: "eine"} <ide> ], <ide> <ide> "'nen": [ <del> {ORTH: "'nen", LEMMA: "einen"} <add> {ORTH: "'nen", LEMMA: DET_LEMMA, NORM: "einen"} <add> ], <add> <add> "'nem": [ <add> {ORTH: "'nem", LEMMA: DET_LEMMA, NORM: "einem"} <ide> ], <ide> <ide> "'s": [ <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER"} <ide> ], <ide> <ide> "Abb.": [ <ide> ], <ide> <ide> "S'": [ <del> {ORTH: "S'", LEMMA: PRON_LEMMA} <add> {ORTH: "S'", LEMMA: PRON_LEMMA, TAG: "PPER"} <ide> ], <ide> <ide> "Sa.": [ <ide> <ide> "auf'm": [ <ide> {ORTH: "auf", LEMMA: "auf"}, <del> {ORTH: "'m", LEMMA: PRON_LEMMA} <add> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem" } <ide> ], <ide> <ide> "bspw.": [ <ide> ], <ide> <ide> "du's": [ <del> {ORTH: "du", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "du", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "ebd.": [ <ide> ], <ide> <ide> "er's": [ <del> {ORTH: "er", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "er", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "evtl.": [ <ide> <ide> "hinter'm": [ <ide> {ORTH: "hinter", LEMMA: "hinter"}, <del> {ORTH: "'m", LEMMA: PRON_LEMMA} <add> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"} <ide> ], <ide> <ide> "i.O.": [ <ide> ], <ide> <ide> "ich's": [ <del> {ORTH: "ich", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "ich", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "ihr's": [ <del> {ORTH: "ihr", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "ihr", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "incl.": [ <ide> ], <ide> <ide> "s'": [ <del> {ORTH: "s'", LEMMA: PRON_LEMMA} <add> {ORTH: "s'", LEMMA: PRON_LEMMA, TAG: "PPER"} <ide> ], <ide> <ide> "s.o.": [ <ide> {ORTH: "s.o.", LEMMA: "siehe oben"} <ide> ], <ide> <ide> "sie's": [ <del> {ORTH: "sie", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "sie", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "sog.": [ <ide> <ide> "unter'm": [ <ide> {ORTH: "unter", LEMMA: "unter"}, <del> {ORTH: "'m", LEMMA: PRON_LEMMA} <add> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"} <ide> ], <ide> <ide> "usf.": [ <ide> <ide> "vor'm": [ <ide> {ORTH: "vor", LEMMA: "vor"}, <del> {ORTH: "'m", LEMMA: PRON_LEMMA} <add> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"} <ide> ], <ide> <ide> "wir's": [ <del> {ORTH: "wir", LEMMA: PRON_LEMMA}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA} <add> {ORTH: "wir", LEMMA: PRON_LEMMA, TAG: "PPER"}, <add> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"} <ide> ], <ide> <ide> "z.B.": [ <ide> <ide> "über'm": [ <ide> {ORTH: "über", LEMMA: "über"}, <del> {ORTH: "'m", LEMMA: PRON_LEMMA} <add> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"} <ide> ] <ide> } <ide> <ide> "wiss.", <ide> "x.", <ide> "y.", <del> "z.", <add> "z." <ide> ]
1
Python
Python
fix identation in executor_config example
264c466b467845bcca25081e91ed76222ae5e7fa
<ide><path>airflow/models/baseoperator.py <ide> class derived from this one results in the creation of a task object, <ide> <ide> MyOperator(..., <ide> executor_config={ <del> "KubernetesExecutor": <del> {"image": "myCustomDockerImage"} <del> } <add> "KubernetesExecutor": <add> {"image": "myCustomDockerImage"} <add> } <ide> ) <ide> <ide> :type executor_config: dict
1
Javascript
Javascript
add e2e test for jsonp error handling
862d78c1d96a22ae215ec272e6f0d07b374421bf
<ide><path>src/service/xhr.js <ide> var self = this; <ide> <ide> this.fetch = function() { <del> self.clear(); <add> self.code = null; <add> self.response = null; <add> <ide> $xhr(self.method, self.url, function(code, response) { <ide> self.code = code; <ide> self.response = response; <add> }, function(code, response) { <add> self.code = code; <add> self.response = response || "Request failed"; <ide> }); <ide> }; <ide> <del> this.clear = function() { <del> self.code = null; <del> self.response = null; <add> this.updateModel = function(method, url) { <add> self.method = method; <add> self.url = url; <ide> }; <ide> } <ide> FetchCntl.$inject = ['$xhr']; <ide> <option>GET</option> <ide> <option>JSON</option> <ide> </select> <del> <input type="text" name="url" value="index.html" size="80"/><br/> <del> <button ng:click="fetch()">fetch</button> <del> <button ng:click="clear()">clear</button> <del> <a href="" ng:click="method='GET'; url='index.html'">sample</a> <del> <a href="" ng:click="method='JSON'; url='https://www.googleapis.com/buzz/v1/activities/googlebuzz/@self?alt=json&callback=JSON_CALLBACK'">buzz</a> <add> <input type="text" name="url" value="index.html" size="80"/> <add> <button ng:click="fetch()">fetch</button><br> <add> <button ng:click="updateModel('GET', 'index.html')">Sample GET</button> <add> <button ng:click="updateModel('JSON', 'https://www.googleapis.com/buzz/v1/activities/googlebuzz/@self?alt=json&callback=JSON_CALLBACK')">Sample JSONP (Buzz API)</button> <add> <button ng:click="updateModel('JSON', 'https://www.invalid_JSONP_request.com&callback=JSON_CALLBACK')">Invalid JSONP</button> <ide> <pre>code={{code}}</pre> <ide> <pre>response={{response}}</pre> <ide> </div> <ide> </doc:source> <add> <doc:scenario> <add> it('should make xhr GET request', function() { <add> element(':button:contains("Sample GET")').click(); <add> element(':button:contains("fetch")').click(); <add> expect(binding('code')).toBe('code=200'); <add> expect(binding('response')).toMatch(/angularjs.org/); <add> }); <add> <add> it('should make JSONP request to the Buzz API', function() { <add> element(':button:contains("Buzz API")').click(); <add> element(':button:contains("fetch")').click(); <add> expect(binding('code')).toBe('code=200'); <add> expect(binding('response')).toMatch(/buzz-feed/); <add> }); <add> <add> it('should make JSONP request to invalid URL and invoke the error handler', <add> function() { <add> element(':button:contains("Invalid JSONP")').click(); <add> element(':button:contains("fetch")').click(); <add> expect(binding('code')).toBe('code='); <add> expect(binding('response')).toBe('response=Request failed'); <add> }); <add> </doc:scenario> <ide> </doc:example> <ide> */ <ide> angularServiceInject('$xhr', function($browser, $error, $log, $updateView){
1
Javascript
Javascript
remove default export from plugins/index
5920858513710276dc33d33a172ce67bd4215d13
<ide><path>src/index.js <ide> Chart.scaleService = scaleService; <ide> Chart.Ticks = Ticks; <ide> <ide> // Register built-in scales <del>import * as scales from './scales/index'; <add>import * as scales from './scales'; <ide> Object.keys(scales).forEach(key => Chart.scaleService.registerScale(scales[key])); <ide> <ide> // Loading built-in plugins <del>import plugins from './plugins/index'; <add>import * as plugins from './plugins'; <ide> for (const k in plugins) { <ide> if (Object.prototype.hasOwnProperty.call(plugins, k)) { <ide> Chart.plugins.register(plugins[k]); <ide><path>src/plugins/index.js <del>import filler from './plugin.filler'; <del>import legend from './plugin.legend'; <del>import title from './plugin.title'; <del>import tooltip from './plugin.tooltip'; <del> <del>export default { <del> filler, <del> legend, <del> title, <del> tooltip <del>}; <add>export {default as filler} from './plugin.filler'; <add>export {default as legend} from './plugin.legend'; <add>export {default as title} from './plugin.title'; <add>export {default as tooltip} from './plugin.tooltip';
2
PHP
PHP
remove unneeded class
6b167368c96ad146cdeab9c67ede66e5f9759ac8
<ide><path>src/Illuminate/Foundation/Artisan.php <del><?php namespace Illuminate\Foundation; <del> <del>use Illuminate\Console\Application as ConsoleApplication; <del> <del>class Artisan { <del> <del> /** <del> * The application instance. <del> * <del> * @var \Illuminate\Foundation\Application <del> */ <del> protected $app; <del> <del> /** <del> * The Artisan console instance. <del> * <del> * @var \Illuminate\Console\Application <del> */ <del> protected $artisan; <del> <del> /** <del> * Create a new Artisan command runner instance. <del> * <del> * @param \Illuminate\Foundation\Application $app <del> * @return void <del> */ <del> public function __construct(Application $app) <del> { <del> $this->app = $app; <del> } <del> <del> /** <del> * Get the Artisan console instance. <del> * <del> * @return \Illuminate\Console\Application <del> */ <del> protected function getArtisan() <del> { <del> if ( ! is_null($this->artisan)) return $this->artisan; <del> <del> $this->app->loadDeferredProviders(); <del> <del> $this->artisan = ConsoleApplication::make($this->app); <del> <del> return $this->artisan->boot(); <del> } <del> <del> /** <del> * Dynamically pass all missing methods to console Artisan. <del> * <del> * @param string $method <del> * @param array $parameters <del> * @return mixed <del> */ <del> public function __call($method, $parameters) <del> { <del> return call_user_func_array(array($this->getArtisan(), $method), $parameters); <del> } <del> <del>}
1
Mixed
Ruby
allow any key in renderer environment hash
6fccd7b6293dcae383757379c5c3809c6674084e
<ide><path>actionpack/CHANGELOG.md <add>* Allow keys not found in RACK_KEY_TRANSLATION for setting the environment when rendering <add> arbitrary templates. <add> <add> *Sammy Larbi* <add> <ide> * Remove deprecated support to non-keyword arguments in `ActionDispatch::IntegrationTest#process`, <ide> `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head`. <ide> <ide><path>actionpack/lib/action_controller/renderer.rb <ide> def normalize_keys(env) <ide> method: ->(v) { v.upcase }, <ide> } <ide> <del> def rack_key_for(key); RACK_KEY_TRANSLATION[key]; end <add> def rack_key_for(key) <add> RACK_KEY_TRANSLATION.fetch(key, key.to_s) <add> end <ide> <ide> def rack_value_for(key, value) <ide> RACK_VALUE_TRANSLATION.fetch(key, IDENTITY).call value <ide><path>actionpack/test/controller/renderer_test.rb <ide> class RendererTest < ActiveSupport::TestCase <ide> assert_equal "true", content <ide> end <ide> <add> test "rendering with custom env using a key that is not in RACK_KEY_TRANSLATION" do <add> value = "warden is here" <add> renderer = ApplicationController.renderer.new warden: value <add> content = renderer.render inline: "<%= request.env['warden'] %>" <add> <add> assert_equal value, content <add> end <add> <ide> test "rendering with defaults" do <ide> renderer = ApplicationController.renderer.new https: true <ide> content = renderer.render inline: "<%= request.ssl? %>"
3
Ruby
Ruby
remove redundant `test_too_many_binds`
36483cdb486fb72ef08ada2a60a0085f2bf66f2f
<ide><path>activerecord/test/cases/adapters/sqlite3/bind_parameter_test.rb <del># frozen_string_literal: true <del> <del>require "cases/helper" <del>require "models/topic" <del> <del>module ActiveRecord <del> module ConnectionAdapters <del> class SQLite3Adapter <del> class BindParameterTest < ActiveRecord::SQLite3TestCase <del> def test_too_many_binds <del> topics = Topic.where(id: (1..999).to_a << 2**63) <del> assert_equal Topic.count, topics.count <del> <del> topics = Topic.where.not(id: (1..999).to_a << 2**63) <del> assert_equal 0, topics.count <del> end <del> end <del> end <del> end <del>end
1
Text
Text
use a local virtualenv, not in the users homedir
9a8082878a08bb87f5e71f245caedc3c9dfd3616
<ide><path>docs/tutorial/1-serialization.md <ide> The tutorial is fairly in-depth, so you should probably get a cookie and a cup o <ide> Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. <ide> <ide> :::bash <del> mkdir ~/env <del> virtualenv ~/env/tutorial <del> source ~/env/tutorial/bin/activate <add> virtualenv env <add> source env/bin/activate <ide> <ide> Now that we're inside a virtualenv environment, we can install our package requirements. <ide>
1
Python
Python
resolve line-too-long in premade_models
ee4e6ec720941958833f022cddec708902f78c2d
<ide><path>keras/premade_models/linear.py <ide> def __init__( <ide> units: Positive integer, output dimension without the batch size. <ide> activation: Activation function to use. <ide> If you don't specify anything, no activation is applied. <del> use_bias: whether to calculate the bias/intercept for this model. If set <del> to False, no bias/intercept will be used in calculations, e.g., the data <del> is already centered. <add> use_bias: whether to calculate the bias/intercept for this model. If <add> set to False, no bias/intercept will be used in calculations, e.g., <add> the data is already centered. <ide> kernel_initializer: Initializer for the `kernel` weights matrices. <ide> bias_initializer: Initializer for the bias vector. <ide> kernel_regularizer: regularizer for kernel vectors. <ide> bias_regularizer: regularizer for bias vector. <del> **kwargs: The keyword arguments that are passed on to BaseLayer.__init__. <add> **kwargs: The keyword arguments that are passed on to <add> BaseLayer.__init__. <ide> """ <ide> <ide> self.units = units <ide><path>keras/premade_models/wide_deep.py <ide> class WideDeepModel(keras_training.Model): <ide> dnn_model = keras.Sequential([keras.layers.Dense(units=64), <ide> keras.layers.Dense(units=1)]) <ide> combined_model = WideDeepModel(linear_model, dnn_model) <del> combined_model.compile(optimizer=['sgd', 'adam'], loss='mse', metrics=['mse']) <add> combined_model.compile(optimizer=['sgd', 'adam'], <add> loss='mse', metrics=['mse']) <ide> # define dnn_inputs and linear_inputs as separate numpy arrays or <ide> # a single numpy array if dnn_inputs is same as linear_inputs. <ide> combined_model.fit([linear_inputs, dnn_inputs], y, epochs) <ide> class WideDeepModel(keras_training.Model): <ide> dnn_model.compile('rmsprop', 'mse') <ide> dnn_model.fit(dnn_inputs, y, epochs) <ide> combined_model = WideDeepModel(linear_model, dnn_model) <del> combined_model.compile(optimizer=['sgd', 'adam'], loss='mse', metrics=['mse']) <add> combined_model.compile(optimizer=['sgd', 'adam'], <add> loss='mse', metrics=['mse']) <ide> combined_model.fit([linear_inputs, dnn_inputs], y, epochs) <ide> ``` <ide> <ide> def __init__(self, linear_model, dnn_model, activation=None, **kwargs): <ide> """Create a Wide & Deep Model. <ide> <ide> Args: <del> linear_model: a premade LinearModel, its output must match the output of <del> the dnn model. <add> linear_model: a premade LinearModel, its output must match the output <add> of the dnn model. <ide> dnn_model: a `tf.keras.Model`, its output must match the output of the <ide> linear model. <ide> activation: Activation function. Set it to None to maintain a linear <ide> activation. <del> **kwargs: The keyword arguments that are passed on to BaseLayer.__init__. <del> Allowed keyword arguments include `name`. <add> **kwargs: The keyword arguments that are passed on to <add> BaseLayer.__init__. Allowed keyword arguments include `name`. <ide> """ <ide> super().__init__(**kwargs) <ide> base_layer.keras_premade_model_gauge.get_cell("WideDeep").set(True) <ide> def _make_train_function(self): <ide> # Training updates <ide> updates = [] <ide> linear_updates = linear_optimizer.get_updates( <del> params=self.linear_model.trainable_weights, # pylint: disable=protected-access <add> params=self.linear_model.trainable_weights, <ide> loss=self.total_loss, <ide> ) <ide> updates += linear_updates <ide> dnn_updates = dnn_optimizer.get_updates( <del> params=self.dnn_model.trainable_weights, # pylint: disable=protected-access <add> params=self.dnn_model.trainable_weights, <ide> loss=self.total_loss, <ide> ) <ide> updates += dnn_updates
2
Javascript
Javascript
use worker.exitedafterdisconnect consistently
eaaec57332c466b39a12245de3b31d002250bec1
<ide><path>test/parallel/test-cluster-worker-constructor.js <ide> const cluster = require('cluster'); <ide> let worker; <ide> <ide> worker = new cluster.Worker(); <del>assert.strictEqual(worker.suicide, undefined); <add>assert.strictEqual(worker.exitedAfterDisconnect, undefined); <ide> assert.strictEqual(worker.state, 'none'); <ide> assert.strictEqual(worker.id, 0); <ide> assert.strictEqual(worker.process, undefined); <ide> worker = new cluster.Worker({ <ide> state: 'online', <ide> process: process <ide> }); <del>assert.strictEqual(worker.suicide, undefined); <add>assert.strictEqual(worker.exitedAfterDisconnect, undefined); <ide> assert.strictEqual(worker.state, 'online'); <ide> assert.strictEqual(worker.id, 3); <ide> assert.strictEqual(worker.process, process); <ide><path>test/parallel/test-cluster-worker-deprecated.js <del>'use strict'; <del>require('../common'); <del> <del>const assert = require('assert'); <del>const cluster = require('cluster'); <del> <del>const worker = new cluster.Worker(); <del> <del>assert.strictEqual(worker.exitedAfterDisconnect, undefined); <del>assert.strictEqual(worker.suicide, undefined); <del> <del>worker.exitedAfterDisconnect = 'recommended'; <del>assert.strictEqual(worker.exitedAfterDisconnect, 'recommended'); <del>assert.strictEqual(worker.suicide, 'recommended'); <del> <del>worker.suicide = 'deprecated'; <del>assert.strictEqual(worker.exitedAfterDisconnect, 'deprecated'); <del>assert.strictEqual(worker.suicide, 'deprecated'); <ide><path>test/parallel/test-cluster-worker-disconnect.js <ide> if (cluster.isWorker) { <ide> http.Server(() => { <ide> <ide> }).listen(0, '127.0.0.1'); <del> const worker = cluster.worker; <del> assert.strictEqual(worker.exitedAfterDisconnect, worker.suicide); <ide> <ide> cluster.worker.on('disconnect', common.mustCall(() => { <del> assert.strictEqual(cluster.worker.exitedAfterDisconnect, <del> cluster.worker.suicide); <ide> process.exit(42); <ide> })); <ide> <ide><path>test/parallel/test-cluster-worker-exit.js <ide> if (cluster.isWorker) { <ide> worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], <ide> worker_emitExit: [1, "the worker did not emit 'exit'"], <ide> worker_state: ['disconnected', 'the worker state is incorrect'], <del> worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], <ide> worker_exitedAfterDisconnect: [ <ide> false, 'the .exitedAfterDisconnect flag is incorrect' <ide> ], <ide> if (cluster.isWorker) { <ide> // Check worker events and properties <ide> worker.on('disconnect', common.mustCall(() => { <ide> results.worker_emitDisconnect += 1; <del> results.worker_suicideMode = worker.suicide; <ide> results.worker_exitedAfterDisconnect = worker.exitedAfterDisconnect; <ide> results.worker_state = worker.state; <ide> if (results.worker_emitExit > 0) { <ide><path>test/parallel/test-regress-GH-3238.js <ide> if (cluster.isMaster) { <ide> function forkWorker(action) { <ide> const worker = cluster.fork({ action }); <ide> worker.on('disconnect', common.mustCall(() => { <del> assert.strictEqual(worker.suicide, true); <add> assert.strictEqual(worker.exitedAfterDisconnect, true); <ide> })); <ide> <ide> worker.on('exit', common.mustCall(() => { <del> assert.strictEqual(worker.suicide, true); <add> assert.strictEqual(worker.exitedAfterDisconnect, true); <ide> })); <ide> } <ide>
5
Python
Python
remove unused import
43e9f5e71a159d3e2ebdab332961bc5379b932f6
<ide><path>libcloud/storage/drivers/cloudfiles.py <ide> # limitations under the License. <ide> <ide> import httplib <del>import os.path <ide> import urllib <ide> <ide> try:
1
Javascript
Javascript
move polyfill for codepointat to string prototype
c8129b878755b0885f09ee4e6ae6efc44eefe8ff
<ide><path>src/shared/compatibility.js <ide> const hasDOM = typeof window === 'object' && typeof document === 'object'; <ide> // Provides support for String.codePointAt in legacy browsers. <ide> // Support: IE11. <ide> (function checkStringCodePointAt() { <del> if (String.codePointAt) { <add> if (String.prototype.codePointAt) { <ide> return; <ide> } <del> String.codePointAt = require('core-js/fn/string/code-point-at'); <add> require('core-js/fn/string/code-point-at'); <ide> })(); <ide> <ide> // Provides support for String.fromCodePoint in legacy browsers.
1
Ruby
Ruby
reword polymorphic routes + mounted engine rdoc
dafb4d604a54d691132b89768c1e34dd0d7067ac
<ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb <ide> module Routing <ide> # edit_polymorphic_path(@post) # => "/posts/1/edit" <ide> # polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf" <ide> # <del> # == Using with mounted engines <add> # == Usage with mounted engines <ide> # <del> # If you use mounted engine, there is a possibility that you will need to use <del> # polymorphic_url pointing at engine's routes. To do that, just pass proxy used <del> # to reach engine's routes as a first argument: <add> # If you are using a mounted engine and you need to use a polymorphic_url <add> # pointing at the engine's routes, pass in the engine's route proxy as the first <add> # argument to the method. For example: <ide> # <del> # For example: <del> # <del> # polymorphic_url([blog, @post]) # it will call blog.post_path(@post) <del> # form_for([blog, @post]) # => "/blog/posts/1 <add> # polymorphic_url([blog, @post]) # calls blog.post_path(@post) <add> # form_for([blog, @post]) # => "/blog/posts/1" <ide> # <ide> module PolymorphicRoutes <ide> # Constructs a call to a named RESTful route for the given record and returns the
1
PHP
PHP
fix incorrect test
570c4f71d9f579952abd367870a3d6e944173942
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function testLoadSingle() <ide> $this->manager->loadSingle('Articles'); <ide> $this->manager->loadSingle('Tags'); <ide> <del> $table = $this->getTableLocator()->get('ArticlesTags'); <add> $table = $this->getTableLocator()->get('Articles'); <ide> $results = $table->find('all')->toArray(); <ide> $schema = $table->getSchema(); <ide> $expectedConstraint = [ <del> 'type' => 'foreign', <add> 'type' => 'primary', <ide> 'columns' => [ <del> 'tag_id', <del> ], <del> 'references' => [ <del> 'tags', <ide> 'id', <ide> ], <del> 'update' => 'cascade', <del> 'delete' => 'cascade', <ide> 'length' => [], <ide> ]; <del> $this->assertSame($expectedConstraint, $schema->getConstraint('tag_id_fk')); <del> $this->assertCount(4, $results); <add> $this->assertSame($expectedConstraint, $schema->getConstraint('primary')); <add> $this->assertCount(3, $results); <ide> <ide> $this->manager->unload($test); <ide> }
1
Text
Text
add note to changelog
4c8d248757cb18b9251411e0c3a2d29e951386d5
<ide><path>CHANGELOG.md <ide> * Fix `null` showing up in a warning instead of the component stack. ([@gaearon](https://github.com/gaearon) in [#10915](https://github.com/facebook/react/pull/10915)) <ide> * Fix IE11 crash in development mode. ([@leidegre](https://github.com/leidegre) in [#10921](https://github.com/facebook/react/pull/10921)) <ide> * Fix `tabIndex` not getting applied to SVG elements. ([@gaearon](http://github.com/gaearon) in [#11034](https://github.com/facebook/react/pull/11034)) <add>* Suppress the new unknown tag warning for `<dialog>` element. ([@gaearon](http://github.com/gaearon) in [#11035](https://github.com/facebook/react/pull/11035)) <ide> * Minor bundle size improvements. ([@gaearon](https://github.com/gaearon) in [#10802](https://github.com/facebook/react/pull/10802), [#10803](https://github.com/facebook/react/pull/10803)) <ide> <ide> </details>
1
Javascript
Javascript
add comment about 3rd party integrations
8e90194f7d38136be48bfebc8fc3c45d88dbc2d6
<ide><path>shells/browser/shared/src/renderer.js <ide> Object.defineProperty( <ide> '__REACT_DEVTOOLS_ATTACH__', <ide> ({ <ide> enumerable: false, <add> // This property needs to be configurable to allow third-party integrations <add> // to attach their own renderer. Note that using third-party integrations <add> // is not officially supported. Use at your own risk. <ide> configurable: true, <ide> get() { <ide> return attach;
1
Javascript
Javascript
use a default branch instead of master
ce5e0f3068172fedd689b8905381a1796ee6481d
<ide><path>script/lib/update-dependency/fetch-outdated-dependencies.js <ide> const apm = async function({ dependencies, packageDependencies }) { <ide> <ide> const npm = async function(cwd) { <ide> try { <del> console.log('Checking npm registry...'); <add> console.log('Checking npm registry...', cwd); <ide> <ide> const currentState = await npmCheck({ <ide> cwd, <ide> ignoreDev: true, <ide> skipUnused: true <add> }).catch(ex => { <add> console.log(ex); <ide> }); <ide> const outdatedPackages = currentState <ide> .get('packages') <ide><path>script/lib/update-dependency/git.js <ide> const git = (git, repositoryRootPath) => { <ide> } catch (ex) { <ide> console.log(ex.message); <ide> } <add> <add> async function createOrCheckoutBranch(newBranch) { <add> const { branches } = await git.branch(); <add> const found = Object.keys(branches).find( <add> branch => branch.indexOf(newBranch) > -1 <add> ); <add> found <add> ? await git.checkout(found) <add> : await git.checkoutLocalBranch(newBranch); <add> <add> return { found, newBranch }; <add> } <add> <ide> return { <del> switchToMaster: async function() { <del> await git.checkout('origin/master'); <add> switchToCleanBranch: async function() { <add> const cleanBranch = 'clean-branch'; <add> const { current } = await git.branch(); <add> if (current !== cleanBranch) createOrCheckoutBranch(cleanBranch); <ide> }, <ide> makeBranch: async function(dependency) { <ide> const newBranch = `${dependency.moduleName}-${dependency.latest}`; <del> const { branches } = await git.branch(); <ide> const { files } = await git.status(); <ide> if (files.length > 0) { <ide> await git.reset('hard'); <ide> } <del> const found = Object.keys(branches).find( <del> branch => branch.indexOf(newBranch) > -1 <del> ); <del> found <del> ? await git.checkout(found) <del> : await git.checkoutLocalBranch(newBranch); <del> return { found, newBranch }; <add> return createOrCheckoutBranch(newBranch); <ide> }, <ide> createCommit: async function({ moduleName, latest }) { <ide> try { <ide><path>script/lib/update-dependency/main.js <ide> const runApmInstall = require('../run-apm-install'); <ide> const { <ide> makeBranch, <ide> createCommit, <del> switchToMaster, <add> switchToCleanBranch, <ide> publishBranch, <ide> deleteBranch <ide> } = require('./git')(git, repositoryRootPath); <ide> const fetchOutdatedDependencies = require('./fetch-outdated-dependencies'); <ide> module.exports = async function() { <ide> try { <ide> // ensure we are on master <del> await switchToMaster(); <add> await switchToCleanBranch(); <ide> const failedBumps = []; <ide> const successfullBumps = []; <ide> const outdateDependencies = [ <ide> module.exports = async function() { <ide> }); <ide> } <ide> <del> await switchToMaster(); <add> await switchToCleanBranch(); <ide> } <ide> // create PRs here <ide> for (const { dependency, branch, branchIsRemote } of pendingPRs) { <ide><path>script/lib/update-dependency/spec/git-spec.js <ide> const repositoryRootPath = path.resolve('.', 'fixtures', 'dummy'); <ide> const git = simpleGit(repositoryRootPath); <ide> <ide> const { <del> switchToMaster, <add> switchToCleanBranch, <ide> makeBranch, <ide> publishBranch, <ide> createCommit, <ide> describe('GIT', () => { <ide> const branch = `${dependency.moduleName}-${dependency.latest}`; <ide> <ide> beforeEach(async () => { <del> await git.checkout('master'); <add> await git.checkout('clean-branch'); <ide> }); <ide> <ide> it('remotes should include ATOM', async () => { <ide> const remotes = await git.getRemotes(); <ide> expect(remotes.map(({ name }) => name).includes('ATOM')).toBeTruthy(); <ide> }); <ide> <del> it('current branch should be master', async () => { <add> it('current branch should be clean-branch', async () => { <ide> const testBranchExists = await findBranch('test'); <ide> testBranchExists <ide> ? await git.checkout('test') <ide> : await git.checkoutLocalBranch('test'); <ide> expect((await git.branch()).current).toBe('test'); <del> await switchToMaster(); <del> expect((await git.branch()).current).toBe('master'); <add> await switchToCleanBranch(); <add> expect((await git.branch()).current).toBe('clean-branch'); <ide> await git.deleteLocalBranch('test', true); <ide> }); <ide> <ide> describe('GIT', () => { <ide> expect(found).toBe(undefined); <ide> expect(newBranch).toBe(branch); <ide> expect((await git.branch()).current).toBe(branch); <del> await git.checkout('master'); <add> await git.checkout('clean-branch'); <ide> await git.deleteLocalBranch(branch, true); <ide> }); <ide> <ide> describe('GIT', () => { <ide> const { found } = await makeBranch(dependency); <ide> expect(found).not.toBe(undefined); <ide> expect((await git.branch()).current).toBe(found); <del> await git.checkout('master'); <add> await git.checkout('clean-branch'); <ide> await git.deleteLocalBranch(branch, true); <ide> }); <ide> <ide> describe('GIT', () => { <ide> <ide> it('should delete an existing branch', async () => { <ide> await git.checkoutLocalBranch(branch); <del> await git.checkout('master'); <add> await git.checkout('clean-branch'); <ide> expect(await findBranch(branch)).not.toBe(undefined); <ide> await deleteBranch(branch); <ide> expect(await findBranch(branch)).toBe(undefined);
4
Text
Text
release notes for 1.1.2 and 1.0.4
0551aa95f0376c52568a027296e225d828cede38
<ide><path>CHANGELOG.md <add><a name="1.1.2"></a> <add># 1.1.2 tofu-animation (2013-01-22) <add> <add>_Note: 1.1.x releases are [considered unstable](http://blog.angularjs.org/2012/07/angularjs-10-12-roadmap.html). <add>They pass all tests but we reserve the right to change new features/apis in between minor releases. Check them <add>out and please give us feedback._ <add> <add>_Note: This release also contains all bug fixes available in [1.0.4](#1.0.4)._ <add> <add>## Features <add> <add>- **$compile:** support modifying the DOM structure in postlink fn <add> ([cdf6fb19](https://github.com/angular/angular.js/commit/cdf6fb19c85560b30607e71dc2b19fde54760faa)) <add>- **$log:** add $log.debug() <add> ([9e991ddb](https://github.com/angular/angular.js/commit/9e991ddb1de13adf520eda459950be5b90b5b6d9), <add> [#1592](https://github.com/angular/angular.js/issues/1592)) <add>- **$parse:** allow strict equality in angular expressions <add> ([a179a9a9](https://github.com/angular/angular.js/commit/a179a9a96eda5c566bda8a70ac8a75822c936a68), <add> [#908](https://github.com/angular/angular.js/issues/908)) <add>- **$resource:** <add> - allow dynamic default parameters <add> ([cc42c99b](https://github.com/angular/angular.js/commit/cc42c99bec6a03d6c41b8e1d29ba2b1f5c16b87d)) <add> - support all $http.config actions <add> ([af89daf4](https://github.com/angular/angular.js/commit/af89daf4641f57b92be6c1f3635f5a3237f20c71)) <add>- **$route:** allow using functions as template params in 'when' <add> ([faf02f0c](https://github.com/angular/angular.js/commit/faf02f0c4db7962f863b0da2a82c8cafab2c706f)) <add>- **$timeout-mock:** add verifyNoPendingTasks method <add> ([f0c6ebc0](https://github.com/angular/angular.js/commit/f0c6ebc07653f6267acec898ccef5677884e3081), <add> [#1245](https://github.com/angular/angular.js/issues/1245)) <add>- **directive:** <add> - added ngOpen boolean directive <add> ([b8bd4d54](https://github.com/angular/angular.js/commit/b8bd4d5460d9952e9a3bb14992636b17859bd457)) <add> - ngKeydown, ngKeyup <add> ([e03182f0](https://github.com/angular/angular.js/commit/e03182f018f5069acd5e883ce2e9349b83f2d03f), <add> [#1035](https://github.com/angular/angular.js/issues/1035)) <add>- **limitTo filter:** limitTo filter accepts strings <add> ([9e96d983](https://github.com/angular/angular.js/commit/9e96d983451899ef0cef3e68395c8f6c1ef83bbe), <add> [#653](https://github.com/angular/angular.js/issues/653)) <add>- **scenario:** <add> - add mouseover method to the ngScenario dsl <add> ([2f437e89](https://github.com/angular/angular.js/commit/2f437e89781cb2b449abb685e36b26ca1cf0fff5)) <add> - fail when an option to select does not exist <add> ([15183f3e](https://github.com/angular/angular.js/commit/15183f3e1fbee031c9595206163962788f98b298)) <add> <add> <add>## Breaking Changes <add> <add>- **date:** due to [cc821502](https://github.com/angular/angular.js/commit/cc821502bca64d15e1c576bf20a62b28b3d9a88a), <add> string input without timezone info is now parsed as local time/date <add> <add> <add> <add><a name="1.0.4"></a> <add># 1.0.4 bewildering-hair (2013-01-22) <add> <add>## Bug Fixes <add> <add>- **$compile:** <add> - do not wrap empty root text nodes in spans <add> ([49f9e4ce](https://github.com/angular/angular.js/commit/49f9e4cef13e68ff85b3c160cf8fac6e7cd042a3), <add> [#1059](https://github.com/angular/angular.js/issues/1059)) <add> - safely create transclude comment nodes <add> ([74dd2f79](https://github.com/angular/angular.js/commit/74dd2f7980ea8ec434a6e0565d857c910653ed9b), <add> [#1740](https://github.com/angular/angular.js/issues/1740)) <add>- **$injector:** <add> - remove bogus fn arg <add> ([b6b7c5a1](https://github.com/angular/angular.js/commit/b6b7c5a1d66073937709158da8c2d688cb45c9f6), <add> [#1711](https://github.com/angular/angular.js/issues/1711)) <add> - provider can now be defined in the array format <add> ([2c405f41](https://github.com/angular/angular.js/commit/2c405f417125c80c387a51baece8bf6e1e0c0a81), <add> [#1452](https://github.com/angular/angular.js/issues/1452)) <add>- **$resource:** <add> - HTTP method should be case-insensitive <add> ([8991680d](https://github.com/angular/angular.js/commit/8991680d8ab632dda60cd70c780868c803c74509), <add> [#1403](https://github.com/angular/angular.js/issues/1403)) <add>- **$route:** <add> - support route params not separated with slashes. <add> ([c6392616](https://github.com/angular/angular.js/commit/c6392616ea5245bd0d2f77dded0b948d9e2637c8)) <add> - correctly extract $routeParams from urls <add> ([30a9da5d](https://github.com/angular/angular.js/commit/30a9da5dc159dd1e19b677914356925c7ebdf632)) <add>- **Scope:** ensure that a scope is destroyed only once <add> ([d6da505f](https://github.com/angular/angular.js/commit/d6da505f4e044f8a487ac27a3ec707c11853ee0a), <add> [#1627](https://github.com/angular/angular.js/issues/1627)) <add>- **angular.equals:** <add> - consistently compare undefined object props <add> ([5ae63fd3](https://github.com/angular/angular.js/commit/5ae63fd385295d5a7bbdc79466f59727dcab1c85), <add> [3c2e1c5e](https://github.com/angular/angular.js/commit/3c2e1c5e4d12529b1d69a6173c38097527dccc4f), <add> [#1648](https://github.com/angular/angular.js/issues/1648)) <add>- **date filter:** parse string input as local time unless TZ is specified <add> ([cc821502](https://github.com/angular/angular.js/commit/cc821502bca64d15e1c576bf20a62b28b3d9a88a), <add> [#847](https://github.com/angular/angular.js/issues/847)) <add>- **jqLite:** <add> - children() should only return elements <add> ([febb4c1c](https://github.com/angular/angular.js/commit/febb4c1c35cf767ae31fc9fef1f4b4f026ac9de0)) <add> - make next() ignore non-element nodes <add> ([76a6047a](https://github.com/angular/angular.js/commit/76a6047af690781b8238ba7924279470ba76d081)) <add>- **scenario:** don't trigger input events on IE9 <add> ([8b9e6c35](https://github.com/angular/angular.js/commit/8b9e6c3501746edb2c9e2d585e8e0eaeb8ba8327)) <add>- **Directives:** <add> - **ngRepeat:** correctly apply $last if repeating over object <add> ([7e746015](https://github.com/angular/angular.js/commit/7e746015ea7dec3e9eb81bc4678fa9b6a83bc47c), <add> [#1789](https://github.com/angular/angular.js/issues/1789)) <add> - **ngResource:** correct leading slash removal. <add> ([b2f46251](https://github.com/angular/angular.js/commit/b2f46251aca76c8568ee7d4bab54edbc9d7a186a)) <add> - **ngSwitch:** don't leak when destroyed while not attached <add> ([a26234f7](https://github.com/angular/angular.js/commit/a26234f7183013e2fcc9b35377e181ad96dc9917), <add> [#1621](https://github.com/angular/angular.js/issues/1621)) <add> - **select:** support optgroup + select[multiple] combo <add> ([26adeb11](https://github.com/angular/angular.js/commit/26adeb119bc4fafa6286de484626b8de4170abc9), <add> [#1553](https://github.com/angular/angular.js/issues/1553)) <add> <add> <add>## Features <add> <add>- **$compile:** support modifying the DOM structure in postlink fn <add> ([cdf6fb19](https://github.com/angular/angular.js/commit/cdf6fb19c85560b30607e71dc2b19fde54760faa)) <add> <add> <add> <ide> <a name="1.1.1"></a> <ide> # 1.1.1 pathological-kerning (2012-11-26) <ide>
1
Ruby
Ruby
add some whitespace for readability
1818c4e8b49d053ca7a220288dd6823984bc0328
<ide><path>activerecord/lib/active_record/insert_all.rb <ide> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil) <ide> raise ArgumentError, "Empty list of attributes passed" if inserts.blank? <ide> <ide> @model, @connection, @inserts, @on_duplicate, @returning, @unique_by = model, model.connection, inserts, on_duplicate, returning, unique_by <add> <ide> @returning = (connection.supports_insert_returning? ? primary_keys : false) if @returning.nil? <ide> @returning = false if @returning == [] <add> <ide> @on_duplicate = :skip if @on_duplicate == :update && updatable_columns.empty? <ide> <ide> ensure_valid_options_for_connection! <ide><path>activerecord/test/cases/insert_all_test.rb <ide> def test_insert_all_returns_ActiveRecord_Result <ide> <ide> def test_insert_all_returns_primary_key_if_returning_is_supported <ide> skip unless supports_insert_returning? <add> <ide> result = Book.insert_all! [{ name: "Rework", author_id: 1 }] <ide> assert_equal %w[ id ], result.columns <ide> end <ide> <ide> def test_insert_all_returns_nothing_if_returning_is_empty <ide> skip unless supports_insert_returning? <add> <ide> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: [] <ide> assert_equal [], result.columns <ide> end <ide> <ide> def test_insert_all_returns_nothing_if_returning_is_false <ide> skip unless supports_insert_returning? <add> <ide> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: false <ide> assert_equal [], result.columns <ide> end <ide> <ide> def test_insert_all_returns_requested_fields <ide> skip unless supports_insert_returning? <add> <ide> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: [:id, :name] <ide> assert_equal %w[ Rework ], result.pluck("name") <ide> end <ide> <ide> def test_insert_all_can_skip_duplicate_records <ide> skip unless supports_insert_on_duplicate_skip? <add> <ide> assert_no_difference "Book.count" do <ide> Book.insert_all [{ id: 1, name: "Agile Web Development with Rails" }] <ide> end <ide> end <ide> <ide> def test_insert_all_will_raise_if_duplicates_are_skipped_only_for_a_certain_conflict_target <ide> skip unless supports_insert_on_duplicate_skip? && supports_insert_conflict_target? <add> <ide> assert_raise ActiveRecord::RecordNotUnique do <ide> Book.insert_all [{ id: 1, name: "Agile Web Development with Rails" }], <ide> unique_by: { columns: %i{author_id name} } <ide> def test_insert_all_will_raise_if_duplicates_are_skipped_only_for_a_certain_conf <ide> <ide> def test_upsert_all_updates_existing_records <ide> skip unless supports_insert_on_duplicate_update? <add> <ide> new_name = "Agile Web Development with Rails, 4th Edition" <ide> Book.upsert_all [{ id: 1, name: new_name }] <ide> assert_equal new_name, Book.find(1).name <ide> end <ide> <ide> def test_upsert_all_does_not_update_readonly_attributes <ide> skip unless supports_insert_on_duplicate_update? <add> <ide> new_name = "Agile Web Development with Rails, 4th Edition" <ide> ReadonlyNameBook.upsert_all [{ id: 1, name: new_name }] <ide> assert_not_equal new_name, Book.find(1).name <ide> end <ide> <ide> def test_upsert_all_does_not_update_primary_keys <ide> skip unless supports_insert_on_duplicate_update? && supports_insert_conflict_target? <add> <ide> Book.upsert_all [{ id: 101, name: "Perelandra", author_id: 7 }] <ide> Book.upsert_all [{ id: 103, name: "Perelandra", author_id: 7, isbn: "1974522598" }], <ide> unique_by: { columns: %i{author_id name} } <add> <ide> book = Book.find_by(name: "Perelandra") <ide> assert_equal 101, book.id, "Should not have updated the ID" <ide> assert_equal "1974522598", book.isbn, "Should have updated the isbn" <ide> end <ide> <ide> def test_upsert_all_does_not_perform_an_upsert_if_a_partial_index_doesnt_apply <ide> skip unless supports_insert_on_duplicate_update? && supports_insert_conflict_target? && supports_partial_index? <add> <ide> Book.upsert_all [{ name: "Out of the Silent Planet", author_id: 7, isbn: "1974522598", published_on: Date.new(1938, 4, 1) }] <ide> Book.upsert_all [{ name: "Perelandra", author_id: 7, isbn: "1974522598" }], <ide> unique_by: { columns: %w[ isbn ], where: "published_on IS NOT NULL" } <add> <ide> assert_equal ["Out of the Silent Planet", "Perelandra"], Book.where(isbn: "1974522598").order(:name).pluck(:name) <ide> end <ide> end
2
Python
Python
fix silly mistake in chararray
b963f883d4db71676ee9be260f63f38f6aead8e6
<ide><path>numpy/core/defchararray.py <ide> def __getitem__(self, obj): <ide> val = ndarray.__getitem__(self, obj) <ide> if isinstance(val, (string_, unicode_)): <ide> return val.rstrip() <add> return val <ide> <ide> def __add__(self, other): <ide> b = broadcast(self, other)
1
Text
Text
add changelog for
512a8c7363d23c3f84eccbf9b1ca128e583c9aab
<ide><path>actionpack/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Add i18n scope to disance_of_time_in_words. *Steve Klabnik* <add> <ide> * `assert_template`: <ide> - is no more passing with empty string. <ide> - is now validating option keys. It accepts: `:layout`, `:partial`, `:locals` and `:count`.
1
Java
Java
remove warning suppression in mocks
41737e827cf47c933f664b1256af67dd278e1620
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java <ide> public Enumeration<String> getAttributeNames() { <ide> return Collections.enumeration(new LinkedHashSet<String>(this.attributes.keySet())); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> public Enumeration<String> getAttributeNamesInScope(int scope) { <ide> switch (scope) { <ide> case PAGE_SCOPE: <ide><path>spring-test/src/main/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public String getRealPath(String path) { <ide> return this.servletContext.getRealPath(path); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> public Set<String> getResourcePaths(String path) { <ide> return this.servletContext.getResourcePaths(path); <ide> } <ide> public Object getAttribute(String name) { <ide> return this.servletContext.getAttribute(name); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> public Enumeration<String> getAttributeNames() { <ide> return this.servletContext.getAttributeNames(); <ide> } <ide> public String getInitParameter(String name) { <ide> return this.servletContext.getInitParameter(name); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> public Enumeration<String> getInitParameterNames() { <ide> return this.servletContext.getInitParameterNames(); <ide> }
2
Ruby
Ruby
add libressl to uses_from_macos allow list
25b7d28f91d88dc2ac431cebba9a9c2998b365f1
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_formula_name <ide> USES_FROM_MACOS_ALLOWLIST = %w[ <ide> apr <ide> apr-util <add> libressl <ide> openblas <ide> openssl@1.1 <ide> ].freeze
1
PHP
PHP
replace spaces with tabs
7435635e501140d9addf2eabd5524a5d027e5b98
<ide><path>src/Illuminate/Console/Command.php <ide> public function table(array $headers, array $rows, $style = 'default') <ide> $table = new Table($this->output); <ide> $table->setHeaders($headers); <ide> $table->setRows($rows); <del> $table->setStyle($style); <add> $table->setStyle($style); <ide> $table->render(); <ide> } <ide>
1
Ruby
Ruby
get more tests to pass
9cfd1d44915f4615bbb760198cd01bf4dfc69f5a
<ide><path>railties/lib/initializer.rb <add>require "pathname" <add> <ide> module Rails <ide> class Configuration <ide> attr_accessor :cache_classes, :load_paths, :eager_load_paths, :framework_paths, <ide> :load_once_paths, :gems_dependencies_loaded, :after_initialize_blocks, <ide> :frameworks, :framework_root_path, :root_path, :plugin_paths, :plugins, <ide> :plugin_loader, :plugin_locators, :gems, :loaded_plugins, :reload_plugins, <del> :i18n <add> :i18n, :gems <ide> <ide> def initialize <ide> @framework_paths = [] <ide> def default_i18n <ide> i18n <ide> end <ide> <add> # Adds a single Gem dependency to the rails application. By default, it will require <add> # the library with the same name as the gem. Use :lib to specify a different name. <add> # <add> # # gem 'aws-s3', '>= 0.4.0' <add> # # require 'aws/s3' <add> # config.gem 'aws-s3', :lib => 'aws/s3', :version => '>= 0.4.0', \ <add> # :source => "http://code.whytheluckystiff.net" <add> # <add> # To require a library be installed, but not attempt to load it, pass :lib => false <add> # <add> # config.gem 'qrp', :version => '0.4.1', :lib => false <add> def gem(name, options = {}) <add> @gems << Rails::GemDependency.new(name, options) <add> end <add> <ide> def default_gems <ide> [] <ide> end <ide> def self.run(initializer = nil, config = nil) <ide> # TODO: w0t? <ide> module Rails <ide> class << self <add> # The Configuration instance used to configure the Rails environment <add> def configuration <add> @@configuration <add> end <add> <add> def configuration=(configuration) <add> @@configuration = configuration <add> end <add> <add> def initialized? <add> @initialized || false <add> end <add> <add> def initialized=(initialized) <add> @initialized ||= initialized <add> end <add> <add> def logger <add> if defined?(RAILS_DEFAULT_LOGGER) <add> RAILS_DEFAULT_LOGGER <add> else <add> nil <add> end <add> end <add> <add> def backtrace_cleaner <add> @@backtrace_cleaner ||= begin <add> # Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded <add> require 'rails/backtrace_cleaner' <add> Rails::BacktraceCleaner.new <add> end <add> end <add> <ide> def root <ide> Pathname.new(RAILS_ROOT) if defined?(RAILS_ROOT) <ide> end <del> end <ide> <add> def env <add> @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV) <add> end <add> <add> def cache <add> RAILS_CACHE <add> end <add> <add> def version <add> VERSION::STRING <add> end <add> <add> def public_path <add> @@public_path ||= self.root ? File.join(self.root, "public") : "public" <add> end <add> <add> def public_path=(path) <add> @@public_path = path <add> end <add> end <ide> class OrderedOptions < Array #:nodoc: <ide> def []=(key, value) <ide> key = key.to_sym <ide><path>railties/test/generator_lookup_test.rb <ide> def setup <ide> # We need to add our testing plugin directory to the plugin paths so <ide> # the locator knows where to look for our plugins <ide> @configuration.plugin_paths += @fixture_dirs.map{|fd| plugin_fixture_path(fd)} <del> @initializer = Rails::Initializer.new(@configuration) <del> @initializer.add_plugin_load_paths <del> @initializer.load_plugins <add> @initializer = Rails::Initializer.default <add> @initializer.config = @configuration <add> @initializer.run(:add_plugin_load_paths) <add> @initializer.run(:load_plugins) <add> @initializer.run(:set_root_path) <ide> load 'rails_generator.rb' <ide> require 'rails_generator/scripts' <ide> end
2
Javascript
Javascript
fix bug where the wrong context was being passed
eb62b083150d3777ba11c0efbbacc64052d98457
<ide><path>packages/ember-states/lib/state.js <ide> Ember.State = Ember.Object.extend(Ember.Evented, { <ide> }); <ide> <ide> Ember.State.transitionTo = function(target) { <del> var event = function(router, context) { <del> router.transitionTo(target, context); <add> var event = function(router, event) { <add> router.transitionTo(target, event.context); <ide> }; <ide> <ide> event.transitionTarget = target;
1
Ruby
Ruby
trim entries where possible to fix ruby crashes
4265540cc41959c4bf5d68cd5e9f046b8aa79cc5
<ide><path>Library/Homebrew/load_path.rb <ide> <ide> HOMEBREW_LIBRARY_PATH = Pathname(__dir__).realpath.freeze <ide> <del>$LOAD_PATH.push(HOMEBREW_LIBRARY_PATH.to_s) unless $LOAD_PATH.include?(HOMEBREW_LIBRARY_PATH.to_s) <add>$LOAD_PATH.push HOMEBREW_LIBRARY_PATH.to_s <ide> <ide> require "vendor/bundle/bundler/setup" <add> <add>$LOAD_PATH.select! { |d| Pathname(d).directory? } <add>$LOAD_PATH.uniq! <ide><path>Library/Homebrew/test/support/helper/spec/shared_context/integration_test.rb <ide> RSpec.shared_context "integration test" do <ide> extend RSpec::Matchers::DSL <ide> <del> if OS.mac? && <del> !RUBY_BIN.to_s.match?(%r{^/(System/Library/Frameworks/Ruby\.framework/Versions/(Current|\d+\.\d+)/)usr/bin$}) <del> skip "integration test requires system Ruby" <del> end <del> <ide> matcher :be_a_success do <ide> match do |actual| <ide> status = actual.is_a?(Proc) ? actual.call : actual
2
Python
Python
fix xcom.delete error in airflow 2.2.0
47c5973b3d1ad6d492fb1ceff19d5ec43b8e74af
<ide><path>airflow/models/xcom.py <ide> class BaseXCom(Base, LoggingMixin): <ide> BaseXCom.execution_date == foreign(DagRun.execution_date) <ide> )""", <ide> uselist=False, <add> passive_deletes="all", <ide> ) <ide> run_id = association_proxy("dag_run", "run_id") <ide>
1
Text
Text
fix lint errors for docs/basics/
6d2cf8948cefd46d9ed62fdc2fdf2ae4f8376b66
<ide><path>docs/basics/Actions.md <ide> First, let’s define some actions. <ide> Here’s an example action which represents adding a new todo item: <ide> <ide> ```js <del>const ADD_TODO = 'ADD_TODO'; <add>const ADD_TODO = 'ADD_TODO' <ide> ``` <ide> <ide> ```js <ide> const ADD_TODO = 'ADD_TODO'; <ide> Actions are plain JavaScript objects. Actions must have a `type` property that indicates the type of action being performed. Types should typically be defined as string constants. Once your app is large enough, you may want to move them into a separate module. <ide> <ide> ```js <del>import { ADD_TODO, REMOVE_TODO } from '../actionTypes'; <add>import { ADD_TODO, REMOVE_TODO } from '../actionTypes' <ide> ``` <ide> <ide> >##### Note on Boilerplate <ide> function addTodoWithDispatch(text) { <ide> const action = { <ide> type: ADD_TODO, <ide> text <del> }; <del> dispatch(action); <add> } <add> dispatch(action) <ide> } <ide> ``` <ide> <ide> function addTodo(text) { <ide> return { <ide> type: ADD_TODO, <ide> text <del> }; <add> } <ide> } <ide> ``` <ide> <ide> This makes them more portable and easier to test. To actually initiate a dispatch, pass the result to the `dispatch()` function: <ide> <ide> ```js <del>dispatch(addTodo(text)); <del>dispatch(completeTodo(index)); <add>dispatch(addTodo(text)) <add>dispatch(completeTodo(index)) <ide> ``` <ide> <ide> Or create a **bound action creator** that automatically dispatches: <ide> <ide> ```js <del>const boundAddTodo = (text) => dispatch(addTodo(text)); <del>const boundCompleteTodo = (index) => dispatch(completeTodo(index)); <add>const boundAddTodo = (text) => dispatch(addTodo(text)) <add>const boundCompleteTodo = (index) => dispatch(completeTodo(index)) <ide> ``` <ide> <ide> You’ll be able to call them directly: <ide> <ide> ``` <del>boundAddTodo(text); <del>boundCompleteTodo(index); <add>boundAddTodo(text) <add>boundCompleteTodo(index) <ide> ``` <ide> <ide> The `dispatch()` function can be accessed directly from the store as [`store.dispatch()`](../api/Store.md#dispatch), but more likely you'll access it using a helper like [react-redux](http://github.com/gaearon/react-redux)'s `connect()`. You can use [`bindActionCreators()`](../api/bindActionCreators.md) to automatically bind many action creators to a `dispatch()` function. <ide> The `dispatch()` function can be accessed directly from the store as [`store.dis <ide> * action types <ide> */ <ide> <del>export const ADD_TODO = 'ADD_TODO'; <del>export const COMPLETE_TODO = 'COMPLETE_TODO'; <del>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; <add>export const ADD_TODO = 'ADD_TODO' <add>export const COMPLETE_TODO = 'COMPLETE_TODO' <add>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER' <ide> <ide> /* <ide> * other constants <ide> export const VisibilityFilters = { <ide> SHOW_ALL: 'SHOW_ALL', <ide> SHOW_COMPLETED: 'SHOW_COMPLETED', <ide> SHOW_ACTIVE: 'SHOW_ACTIVE' <del>}; <add>} <ide> <ide> /* <ide> * action creators <ide> */ <ide> <ide> export function addTodo(text) { <del> return { type: ADD_TODO, text }; <add> return { type: ADD_TODO, text } <ide> } <ide> <ide> export function completeTodo(index) { <del> return { type: COMPLETE_TODO, index }; <add> return { type: COMPLETE_TODO, index } <ide> } <ide> <ide> export function setVisibilityFilter(filter) { <del> return { type: SET_VISIBILITY_FILTER, filter }; <add> return { type: SET_VISIBILITY_FILTER, filter } <ide> } <ide> ``` <ide> <ide><path>docs/basics/DataFlow.md <ide> The data lifecycle in any Redux app follows these 4 steps: <ide> An [action](Actions.md) is a plain object describing *what happened*. For example: <ide> <ide> ```js <del> { type: 'LIKE_ARTICLE', articleId: 42 }; <del> { type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Megan' } }; <del> { type: 'ADD_TODO', text: 'Read the Redux docs.'}; <add> { type: 'LIKE_ARTICLE', articleId: 42 } <add> { type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Megan' } } <add> { type: 'ADD_TODO', text: 'Read the Redux docs.'} <ide> ``` <ide> <ide> Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.’ was added to the list of todos.” <ide> The data lifecycle in any Redux app follows these 4 steps: <ide> // The current application state (list of todos and chosen filter) <ide> let previousState = { <ide> visibleTodoFilter: 'SHOW_ALL', <del> todos: [{ <del> text: 'Read the docs.', <del> complete: false <del> }] <del> }; <add> todos: [ <add> { <add> text: 'Read the docs.', <add> complete: false <add> } <add> ] <add> } <ide> <ide> // The action being performed (adding a todo) <ide> let action = { <ide> type: 'ADD_TODO', <ide> text: 'Understand the flow.' <del> }; <add> } <ide> <ide> // Your reducer returns the next application state <del> let nextState = todoApp(previousState, action); <add> let nextState = todoApp(previousState, action) <ide> ``` <ide> <ide> Note that a reducer is a pure function. It only *computes* the next state. It should be completely predictable: calling it with the same inputs many times should produce the same outputs. It shouldn’t perform any side effects like API calls or router transitions. These should happen before an action is dispatched. <ide> The data lifecycle in any Redux app follows these 4 steps: <ide> ```js <ide> function todos(state = [], action) { <ide> // Somehow calculate it... <del> return nextState; <add> return nextState <ide> } <ide> <ide> function visibleTodoFilter(state = 'SHOW_ALL', action) { <ide> // Somehow calculate it... <del> return nextState; <add> return nextState <ide> } <ide> <ide> let todoApp = combineReducers({ <ide> todos, <ide> visibleTodoFilter <del> }); <add> }) <ide> ``` <ide> <ide> When you emit an action, `todoApp` returned by `combineReducers` will call both reducers: <ide> <ide> ```js <del> let nextTodos = todos(state.todos, action); <del> let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action); <add> let nextTodos = todos(state.todos, action) <add> let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action) <ide> ``` <ide> <ide> It will then combine both sets of results into a single state tree: <ide> The data lifecycle in any Redux app follows these 4 steps: <ide> return { <ide> todos: nextTodos, <ide> visibleTodoFilter: nextVisibleTodoFilter <del> }; <add> } <ide> ``` <ide> <ide> While [`combineReducers()`](../api/combineReducers.md) is a handy helper utility, you don’t have to use it; feel free to write your own root reducer! <ide><path>docs/basics/ExampleTodoList.md <ide> This is the complete source code of the tiny todo app we built during the [basic <ide> #### `index.js` <ide> <ide> ```js <del>import React from 'react'; <del>import { render } from 'react-dom'; <del>import { createStore } from 'redux'; <del>import { Provider } from 'react-redux'; <del>import App from './containers/App'; <del>import todoApp from './reducers'; <add>import React from 'react' <add>import { render } from 'react-dom' <add>import { createStore } from 'redux' <add>import { Provider } from 'react-redux' <add>import App from './containers/App' <add>import todoApp from './reducers' <ide> <del>let store = createStore(todoApp); <add>let store = createStore(todoApp) <ide> <del>let rootElement = document.getElementById('root'); <add>let rootElement = document.getElementById('root') <ide> render( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>, <ide> rootElement <del>); <add>) <ide> ``` <ide> <ide> ## Action Creators and Constants <ide> render( <ide> * action types <ide> */ <ide> <del>export const ADD_TODO = 'ADD_TODO'; <del>export const COMPLETE_TODO = 'COMPLETE_TODO'; <del>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; <add>export const ADD_TODO = 'ADD_TODO' <add>export const COMPLETE_TODO = 'COMPLETE_TODO' <add>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER' <ide> <ide> /* <ide> * other constants <ide> export const VisibilityFilters = { <ide> SHOW_ALL: 'SHOW_ALL', <ide> SHOW_COMPLETED: 'SHOW_COMPLETED', <ide> SHOW_ACTIVE: 'SHOW_ACTIVE' <del>}; <add>} <ide> <ide> /* <ide> * action creators <ide> */ <ide> <ide> export function addTodo(text) { <del> return { type: ADD_TODO, text }; <add> return { type: ADD_TODO, text } <ide> } <ide> <ide> export function completeTodo(index) { <del> return { type: COMPLETE_TODO, index }; <add> return { type: COMPLETE_TODO, index } <ide> } <ide> <ide> export function setVisibilityFilter(filter) { <del> return { type: SET_VISIBILITY_FILTER, filter }; <add> return { type: SET_VISIBILITY_FILTER, filter } <ide> } <ide> ``` <ide> <ide> export function setVisibilityFilter(filter) { <ide> #### `reducers.js` <ide> <ide> ```js <del>import { combineReducers } from 'redux'; <del>import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions'; <del>const { SHOW_ALL } = VisibilityFilters; <add>import { combineReducers } from 'redux' <add>import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions' <add>const { SHOW_ALL } = VisibilityFilters <ide> <ide> function visibilityFilter(state = SHOW_ALL, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return action.filter; <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return action.filter <add> default: <add> return state <ide> } <ide> } <ide> <ide> function todos(state = [], action) { <ide> switch (action.type) { <del> case ADD_TODO: <del> return [...state, { <del> text: action.text, <del> completed: false <del> }]; <del> case COMPLETE_TODO: <del> return [ <del> ...state.slice(0, action.index), <del> Object.assign({}, state[action.index], { <del> completed: true <del> }), <del> ...state.slice(action.index + 1) <del> ]; <del> default: <del> return state; <add> case ADD_TODO: <add> return [ <add> ...state, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> case COMPLETE_TODO: <add> return [ <add> ...state.slice(0, action.index), <add> Object.assign({}, state[action.index], { <add> completed: true <add> }), <add> ...state.slice(action.index + 1) <add> ] <add> default: <add> return state <ide> } <ide> } <ide> <ide> const todoApp = combineReducers({ <ide> visibilityFilter, <ide> todos <del>}); <add>}) <ide> <del>export default todoApp; <add>export default todoApp <ide> ``` <ide> <ide> ## Smart Components <ide> <ide> #### `containers/App.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions'; <del>import AddTodo from '../components/AddTodo'; <del>import TodoList from '../components/TodoList'; <del>import Footer from '../components/Footer'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions' <add>import AddTodo from '../components/AddTodo' <add>import TodoList from '../components/TodoList' <add>import Footer from '../components/Footer' <ide> <ide> class App extends Component { <ide> render() { <ide> // Injected by connect() call: <del> const { dispatch, visibleTodos, visibilityFilter } = this.props; <add> const { dispatch, visibleTodos, visibilityFilter } = this.props <ide> return ( <ide> <div> <ide> <AddTodo <ide> class App extends Component { <ide> dispatch(setVisibilityFilter(nextFilter)) <ide> } /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> App.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> <ide> function selectTodos(todos, filter) { <ide> switch (filter) { <del> case VisibilityFilters.SHOW_ALL: <del> return todos; <del> case VisibilityFilters.SHOW_COMPLETED: <del> return todos.filter(todo => todo.completed); <del> case VisibilityFilters.SHOW_ACTIVE: <del> return todos.filter(todo => !todo.completed); <add> case VisibilityFilters.SHOW_ALL: <add> return todos <add> case VisibilityFilters.SHOW_COMPLETED: <add> return todos.filter(todo => todo.completed) <add> case VisibilityFilters.SHOW_ACTIVE: <add> return todos.filter(todo => !todo.completed) <ide> } <ide> } <ide> <ide> function select(state) { <ide> return { <ide> visibleTodos: selectTodos(state.todos, state.visibilityFilter), <ide> visibilityFilter: state.visibilityFilter <del> }; <add> } <ide> } <ide> <ide> // Wrap the component to inject dispatch and state into it <del>export default connect(select)(App); <add>export default connect(select)(App) <ide> ``` <ide> <ide> ## Dumb Components <ide> <ide> #### `components/AddTodo.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class AddTodo extends Component { <ide> render() { <ide> export default class AddTodo extends Component { <ide> Add <ide> </button> <ide> </div> <del> ); <add> ) <ide> } <ide> <ide> handleClick(e) { <del> const node = this.refs.input; <del> const text = node.value.trim(); <del> this.props.onAddClick(text); <del> node.value = ''; <add> const node = this.refs.input <add> const text = node.value.trim() <add> this.props.onAddClick(text) <add> node.value = '' <ide> } <ide> } <ide> <ide> AddTodo.propTypes = { <ide> onAddClick: PropTypes.func.isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/Footer.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Footer extends Component { <ide> renderFilter(filter, name) { <ide> if (filter === this.props.filter) { <del> return name; <add> return name <ide> } <ide> <ide> return ( <ide> <a href='#' onClick={e => { <del> e.preventDefault(); <del> this.props.onFilterChange(filter); <add> e.preventDefault() <add> this.props.onFilterChange(filter) <ide> }}> <ide> {name} <ide> </a> <del> ); <add> ) <ide> } <ide> <ide> render() { <ide> export default class Footer extends Component { <ide> {this.renderFilter('SHOW_ACTIVE', 'Active')} <ide> . <ide> </p> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Footer.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/Todo.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Todo extends Component { <ide> render() { <ide> export default class Todo extends Component { <ide> }}> <ide> {this.props.text} <ide> </li> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Todo.propTypes = { <ide> onClick: PropTypes.func.isRequired, <ide> text: PropTypes.string.isRequired, <ide> completed: PropTypes.bool.isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/TodoList.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import Todo from './Todo'; <add>import React, { Component, PropTypes } from 'react' <add>import Todo from './Todo' <ide> <ide> export default class TodoList extends Component { <ide> render() { <ide> export default class TodoList extends Component { <ide> onClick={() => this.props.onTodoClick(index)} /> <ide> )} <ide> </ul> <del> ); <add> ) <ide> } <ide> } <ide> <ide> TodoList.propTypes = { <ide> text: PropTypes.string.isRequired, <ide> completed: PropTypes.bool.isRequired <ide> }).isRequired).isRequired <del>}; <add>} <ide> ``` <ide><path>docs/basics/Reducers.md <ide> You’ll often find that you need to store some data, as well as some UI state, <ide> ```js <ide> { <ide> visibilityFilter: 'SHOW_ALL', <del> todos: [{ <del> text: 'Consider using Redux', <del> completed: true, <del> }, { <del> text: 'Keep all state in a single tree', <del> completed: false <del> }] <add> todos: [ <add> { <add> text: 'Consider using Redux', <add> completed: true, <add> }, <add> { <add> text: 'Keep all state in a single tree', <add> completed: false <add> } <add> ] <ide> } <ide> ``` <ide> <ide> With this out of the way, let’s start writing our reducer by gradually teachin <ide> We’ll start by specifying the initial state. Redux will call our reducer with an `undefined` state for the first time. This is our chance to return the initial state of our app: <ide> <ide> ```js <del>import { VisibilityFilters } from './actions'; <add>import { VisibilityFilters } from './actions' <ide> <ide> const initialState = { <ide> visibilityFilter: VisibilityFilters.SHOW_ALL, <ide> todos: [] <del>}; <add>} <ide> <ide> function todoApp(state, action) { <ide> if (typeof state === 'undefined') { <del> return initialState; <add> return initialState <ide> } <ide> <ide> // For now, don’t handle any actions <ide> // and just return the state given to us. <del> return state; <add> return state <ide> } <ide> ``` <ide> <ide> One neat trick is to use the [ES6 default arguments syntax](https://developer.mo <ide> function todoApp(state = initialState, action) { <ide> // For now, don’t handle any actions <ide> // and just return the state given to us. <del> return state; <add> return state <ide> } <ide> ``` <ide> <ide> Now let’s handle `SET_VISIBILITY_FILTER`. All it needs to do is to change `vis <ide> ```js <ide> function todoApp(state = initialState, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return Object.assign({}, state, { <del> visibilityFilter: action.filter <del> }); <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return Object.assign({}, state, { <add> visibilityFilter: action.filter <add> }) <add> default: <add> return state <ide> } <ide> } <ide> ``` <ide> We have two more actions to handle! Let’s extend our reducer to handle `ADD_TO <ide> ```js <ide> function todoApp(state = initialState, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return Object.assign({}, state, { <del> visibilityFilter: action.filter <del> }); <del> case ADD_TODO: <del> return Object.assign({}, state, { <del> todos: [...state.todos, { <del> text: action.text, <del> completed: false <del> }] <del> }); <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return Object.assign({}, state, { <add> visibilityFilter: action.filter <add> }) <add> case ADD_TODO: <add> return Object.assign({}, state, { <add> todos: [ <add> ...state.todos, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> }) <add> default: <add> return state <ide> } <ide> } <ide> ``` <ide> case COMPLETE_TODO: <ide> }), <ide> ...state.todos.slice(action.index + 1) <ide> ] <del> }); <add> }) <ide> ``` <ide> <ide> Because we want to update a specific item in the array without resorting to mutations, we have to slice it before and after the item. If you find yourself often writing such operations, it’s a good idea to use a helper like [react-addons-update](https://facebook.github.io/react/docs/update.html), [updeep](https://github.com/substantial/updeep), or even a library like [Immutable](http://facebook.github.io/immutable-js/) that has native support for deep updates. Just remember to never assign to anything inside the `state` unless you clone it first. <ide> Here is our code so far. It is rather verbose: <ide> ```js <ide> function todoApp(state = initialState, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return Object.assign({}, state, { <del> visibilityFilter: action.filter <del> }); <del> case ADD_TODO: <del> return Object.assign({}, state, { <del> todos: [...state.todos, { <del> text: action.text, <del> completed: false <del> }] <del> }); <del> case COMPLETE_TODO: <del> return Object.assign({}, state, { <del> todos: [ <del> ...state.todos.slice(0, action.index), <del> Object.assign({}, state.todos[action.index], { <del> completed: true <del> }), <del> ...state.todos.slice(action.index + 1) <del> ] <del> }); <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return Object.assign({}, state, { <add> visibilityFilter: action.filter <add> }) <add> case ADD_TODO: <add> return Object.assign({}, state, { <add> todos: [ <add> ...state.todos, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> }) <add> case COMPLETE_TODO: <add> return Object.assign({}, state, { <add> todos: [ <add> ...state.todos.slice(0, action.index), <add> Object.assign({}, state.todos[action.index], { <add> completed: true <add> }), <add> ...state.todos.slice(action.index + 1) <add> ] <add> }) <add> default: <add> return state <ide> } <ide> } <ide> ``` <ide> <ide> Is there a way to make it easier to comprehend? It seems like `todos` and `visibilityFilter` are updated completely independently. Sometimes state fields depend on one another and more consideration is required, but in our case we can easily split updating `todos` into a separate function: <ide> <ide> ```js <del>function todos(state = [], action) { <del> switch (action.type) { <del> case ADD_TODO: <del> return [...state, { <del> text: action.text, <del> completed: false <del> }]; <del> case COMPLETE_TODO: <del> return [ <del> ...state.slice(0, action.index), <del> Object.assign({}, state[action.index], { <del> completed: true <del> }), <del> ...state.slice(action.index + 1) <del> ]; <del> default: <del> return state; <del> } <del>} <del> <ide> function todoApp(state = initialState, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return Object.assign({}, state, { <del> visibilityFilter: action.filter <del> }); <del> case ADD_TODO: <del> case COMPLETE_TODO: <del> return Object.assign({}, state, { <del> todos: todos(state.todos, action) <del> }); <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return Object.assign({}, state, { <add> visibilityFilter: action.filter <add> }) <add> case ADD_TODO: <add> return Object.assign({}, state, { <add> todos: [ <add> ...state.todos, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> }) <add> case COMPLETE_TODO: <add> return Object.assign({}, state, { <add> todos: [ <add> ...state.todos.slice(0, action.index), <add> Object.assign({}, state.todos[action.index], { <add> completed: true <add> }), <add> ...state.todos.slice(action.index + 1) <add> ] <add> }) <add> default: <add> return state <ide> } <ide> } <ide> ``` <ide> Let’s explore reducer composition more. Can we also extract a reducer managing <ide> function visibilityFilter(state = SHOW_ALL, action) { <ide> switch (action.type) { <ide> case SET_VISIBILITY_FILTER: <del> return action.filter; <add> return action.filter <ide> default: <del> return state; <add> return state <ide> } <ide> } <ide> ``` <ide> Now we can rewrite the main reducer as a function that calls the reducers managi <ide> ```js <ide> function todos(state = [], action) { <ide> switch (action.type) { <del> case ADD_TODO: <del> return [...state, { <del> text: action.text, <del> completed: false <del> }]; <del> case COMPLETE_TODO: <del> return [ <del> ...state.slice(0, action.index), <del> Object.assign({}, state[action.index], { <del> completed: true <del> }), <del> ...state.slice(action.index + 1) <del> ]; <del> default: <del> return state; <add> case ADD_TODO: <add> return [ <add> ...state, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> case COMPLETE_TODO: <add> return [ <add> ...state.slice(0, action.index), <add> Object.assign({}, state[action.index], { <add> completed: true <add> }), <add> ...state.slice(action.index + 1) <add> ] <add> default: <add> return state <ide> } <ide> } <ide> <ide> function visibilityFilter(state = SHOW_ALL, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return action.filter; <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return action.filter <add> default: <add> return state <ide> } <ide> } <ide> <ide> function todoApp(state = {}, action) { <ide> return { <ide> visibilityFilter: visibilityFilter(state.visibilityFilter, action), <ide> todos: todos(state.todos, action) <del> }; <add> } <ide> } <ide> ``` <ide> <ide> This is already looking good! When the app is larger, we can split the reducers <ide> Finally, Redux provides a utility called [`combineReducers()`](../api/combineReducers.md) that does the same boilerplate logic that the `todoApp` above currently does. With its help, we can rewrite `todoApp` like this: <ide> <ide> ```js <del>import { combineReducers } from 'redux'; <add>import { combineReducers } from 'redux' <ide> <ide> const todoApp = combineReducers({ <ide> visibilityFilter, <ide> todos <del>}); <add>}) <ide> <del>export default todoApp; <add>export default todoApp <ide> ``` <ide> <ide> Note that this is completely equivalent to: <ide> export default function todoApp(state = {}, action) { <ide> return { <ide> visibilityFilter: visibilityFilter(state.visibilityFilter, action), <ide> todos: todos(state.todos, action) <del> }; <add> } <ide> } <ide> ``` <ide> <ide> const reducer = combineReducers({ <ide> a: doSomethingWithA, <ide> b: processB, <ide> c: c <del>}); <add>}) <ide> ``` <ide> <ide> ```js <ide> function reducer(state, action) { <ide> a: doSomethingWithA(state.a, action), <ide> b: processB(state.b, action), <ide> c: c(state.c, action) <del> }; <add> } <ide> } <ide> ``` <ide> <ide> All [`combineReducers()`](../api/combineReducers.md) does is generate a function <ide> >Because `combineReducers` expects an object, we can put all top-level reducers into a separate file, `export` each reducer function, and use `import * as reducers` to get them as an object with their names as the keys: <ide> <ide> >```js <del>>import { combineReducers } from 'redux'; <del>>import * as reducers from './reducers'; <add>>import { combineReducers } from 'redux' <add>>import * as reducers from './reducers' <ide> > <del>>const todoApp = combineReducers(reducers); <add>>const todoApp = combineReducers(reducers) <ide> >``` <ide> > <ide> >Because `import *` is still new syntax, we don’t use it anymore in the documentation to avoid [confusion](https://github.com/rackt/redux/issues/428#issuecomment-129223274), but you may encounter it in some community examples. <ide> All [`combineReducers()`](../api/combineReducers.md) does is generate a function <ide> #### `reducers.js` <ide> <ide> ```js <del>import { combineReducers } from 'redux'; <del>import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions'; <del>const { SHOW_ALL } = VisibilityFilters; <add>import { combineReducers } from 'redux' <add>import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions' <add>const { SHOW_ALL } = VisibilityFilters <ide> <ide> function visibilityFilter(state = SHOW_ALL, action) { <ide> switch (action.type) { <del> case SET_VISIBILITY_FILTER: <del> return action.filter; <del> default: <del> return state; <add> case SET_VISIBILITY_FILTER: <add> return action.filter <add> default: <add> return state <ide> } <ide> } <ide> <ide> function todos(state = [], action) { <ide> switch (action.type) { <del> case ADD_TODO: <del> return [...state, { <del> text: action.text, <del> completed: false <del> }]; <del> case COMPLETE_TODO: <del> return [ <del> ...state.slice(0, action.index), <del> Object.assign({}, state[action.index], { <del> completed: true <del> }), <del> ...state.slice(action.index + 1) <del> ]; <del> default: <del> return state; <add> case ADD_TODO: <add> return [ <add> ...state, <add> { <add> text: action.text, <add> completed: false <add> } <add> ] <add> case COMPLETE_TODO: <add> return [ <add> ...state.slice(0, action.index), <add> Object.assign({}, state[action.index], { <add> completed: true <add> }), <add> ...state.slice(action.index + 1) <add> ] <add> default: <add> return state <ide> } <ide> } <ide> <ide> const todoApp = combineReducers({ <ide> visibilityFilter, <ide> todos <del>}); <add>}) <ide> <del>export default todoApp; <add>export default todoApp <ide> ``` <ide> <ide> ## Next Steps <ide><path>docs/basics/Store.md <ide> It’s important to note that you’ll only have a single store in a Redux appli <ide> It’s easy to create a store if you have a reducer. In the [previous section](Reducers.md), we used [`combineReducers()`](../api/combineReducers.md) to combine several reducers into one. We will now import it, and pass it to [`createStore()`](../api/createStore.md). <ide> <ide> ```js <del>import { createStore } from 'redux'; <del>import todoApp from './reducers'; <del> <del>let store = createStore(todoApp); <add>import { createStore } from 'redux' <add>import todoApp from './reducers' <add>let store = createStore(todoApp) <ide> ``` <ide> <ide> You may optionally specify the initial state as the second argument to [`createStore()`](../api/createStore.md). This is useful for hydrating the state of the client to match the state of a Redux application running on the server. <ide> <ide> ```js <del>let store = createStore(todoApp, window.STATE_FROM_SERVER); <add>let store = createStore(todoApp, window.STATE_FROM_SERVER) <ide> ``` <ide> <ide> ## Dispatching Actions <ide> <ide> Now that we have created a store, let’s verify our program works! Even without any UI, we can already test the update logic. <ide> <ide> ```js <del>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from './actions'; <add>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from './actions' <ide> <ide> // Log the initial state <del>console.log(store.getState()); <add>console.log(store.getState()) <ide> <ide> // Every time the state changes, log it <ide> let unsubscribe = store.subscribe(() => <ide> console.log(store.getState()) <del>); <add>) <ide> <ide> // Dispatch some actions <del>store.dispatch(addTodo('Learn about actions')); <del>store.dispatch(addTodo('Learn about reducers')); <del>store.dispatch(addTodo('Learn about store')); <del>store.dispatch(completeTodo(0)); <del>store.dispatch(completeTodo(1)); <del>store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED)); <add>store.dispatch(addTodo('Learn about actions')) <add>store.dispatch(addTodo('Learn about reducers')) <add>store.dispatch(addTodo('Learn about store')) <add>store.dispatch(completeTodo(0)) <add>store.dispatch(completeTodo(1)) <add>store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED)) <ide> <ide> // Stop listening to state updates <del>unsubscribe(); <add>unsubscribe() <ide> ``` <ide> <ide> You can see how this causes the state held by the store to change: <ide> We specified the behavior of our app before we even started writing the UI. We w <ide> #### `index.js` <ide> <ide> ```js <del>import { createStore } from 'redux'; <del>import todoApp from './reducers'; <add>import { createStore } from 'redux' <add>import todoApp from './reducers' <ide> <del>let store = createStore(todoApp); <add>let store = createStore(todoApp) <ide> ``` <ide> <ide> ## Next Steps <ide><path>docs/basics/UsageWithReact.md <ide> These are all normal React components, so we won’t stop to examine them in det <ide> #### `components/AddTodo.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class AddTodo extends Component { <ide> render() { <ide> export default class AddTodo extends Component { <ide> Add <ide> </button> <ide> </div> <del> ); <add> ) <ide> } <ide> <ide> handleClick(e) { <del> const node = this.refs.input; <del> const text = node.value.trim(); <del> this.props.onAddClick(text); <del> node.value = ''; <add> const node = this.refs.input <add> const text = node.value.trim() <add> this.props.onAddClick(text) <add> node.value = '' <ide> } <ide> } <ide> <ide> AddTodo.propTypes = { <ide> onAddClick: PropTypes.func.isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/Todo.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Todo extends Component { <ide> render() { <ide> export default class Todo extends Component { <ide> }}> <ide> {this.props.text} <ide> </li> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Todo.propTypes = { <ide> onClick: PropTypes.func.isRequired, <ide> text: PropTypes.string.isRequired, <ide> completed: PropTypes.bool.isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/TodoList.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import Todo from './Todo'; <add>import React, { Component, PropTypes } from 'react' <add>import Todo from './Todo' <ide> <ide> export default class TodoList extends Component { <ide> render() { <ide> export default class TodoList extends Component { <ide> onClick={() => this.props.onTodoClick(index)} /> <ide> )} <ide> </ul> <del> ); <add> ) <ide> } <ide> } <ide> <ide> TodoList.propTypes = { <ide> text: PropTypes.string.isRequired, <ide> completed: PropTypes.bool.isRequired <ide> }).isRequired).isRequired <del>}; <add>} <ide> ``` <ide> <ide> #### `components/Footer.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Footer extends Component { <ide> renderFilter(filter, name) { <ide> if (filter === this.props.filter) { <del> return name; <add> return name <ide> } <ide> <ide> return ( <ide> <a href='#' onClick={e => { <del> e.preventDefault(); <del> this.props.onFilterChange(filter); <add> e.preventDefault() <add> this.props.onFilterChange(filter) <ide> }}> <ide> {name} <ide> </a> <del> ); <add> ) <ide> } <ide> <ide> render() { <ide> export default class Footer extends Component { <ide> {this.renderFilter('SHOW_ACTIVE', 'Active')} <ide> . <ide> </p> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Footer.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> ``` <ide> <ide> That’s it! We can verify that they work correctly by writing a dummy `App` to render them: <ide> <ide> #### `containers/App.js` <ide> <ide> ```js <del>import React, { Component } from 'react'; <del>import AddTodo from '../components/AddTodo'; <del>import TodoList from '../components/TodoList'; <del>import Footer from '../components/Footer'; <add>import React, { Component } from 'react' <add>import AddTodo from '../components/AddTodo' <add>import TodoList from '../components/TodoList' <add>import Footer from '../components/Footer' <ide> <ide> export default class App extends Component { <ide> render() { <ide> export default class App extends Component { <ide> console.log('add todo', text) <ide> } /> <ide> <TodoList <del> todos={[{ <del> text: 'Use Redux', <del> completed: true <del> }, { <del> text: 'Learn to connect it to React', <del> completed: false <del> }]} <add> todos={ <add> [ <add> { <add> text: 'Use Redux', <add> completed: true <add> }, <add> { <add> text: 'Learn to connect it to React', <add> completed: false <add> } <add> ] <add> } <ide> onTodoClick={index => <ide> console.log('todo clicked', index) <ide> } /> <ide> export default class App extends Component { <ide> console.log('filter change', filter) <ide> } /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> ``` <ide> First, we need to import `Provider` from [`react-redux`](http://github.com/gaear <ide> #### `index.js` <ide> <ide> ```js <del>import React from 'react'; <del>import { render } from 'react-dom'; <del>import { createStore } from 'redux'; <del>import { Provider } from 'react-redux'; <del>import App from './containers/App'; <del>import todoApp from './reducers'; <add>import React from 'react' <add>import { render } from 'react-dom' <add>import { createStore } from 'redux' <add>import { Provider } from 'react-redux' <add>import App from './containers/App' <add>import todoApp from './reducers' <ide> <del>let store = createStore(todoApp); <add>let store = createStore(todoApp) <ide> <del>let rootElement = document.getElementById('root'); <add>let rootElement = document.getElementById('root') <ide> render( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>, <ide> rootElement <del>); <add>) <ide> ``` <ide> <ide> This makes our store instance available to the components below. (Internally, this is done via React’s [“context” feature](http://facebook.github.io/react/docs/context.html).) <ide> To make performant memoized transformations with composable selectors, check out <ide> #### `containers/App.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions'; <del>import AddTodo from '../components/AddTodo'; <del>import TodoList from '../components/TodoList'; <del>import Footer from '../components/Footer'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions' <add>import AddTodo from '../components/AddTodo' <add>import TodoList from '../components/TodoList' <add>import Footer from '../components/Footer' <ide> <ide> class App extends Component { <ide> render() { <ide> // Injected by connect() call: <del> const { dispatch, visibleTodos, visibilityFilter } = this.props; <add> const { dispatch, visibleTodos, visibilityFilter } = this.props <ide> return ( <ide> <div> <ide> <AddTodo <ide> class App extends Component { <ide> dispatch(setVisibilityFilter(nextFilter)) <ide> } /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> App.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> <ide> function selectTodos(todos, filter) { <ide> switch (filter) { <del> case VisibilityFilters.SHOW_ALL: <del> return todos; <del> case VisibilityFilters.SHOW_COMPLETED: <del> return todos.filter(todo => todo.completed); <del> case VisibilityFilters.SHOW_ACTIVE: <del> return todos.filter(todo => !todo.completed); <add> case VisibilityFilters.SHOW_ALL: <add> return todos <add> case VisibilityFilters.SHOW_COMPLETED: <add> return todos.filter(todo => todo.completed) <add> case VisibilityFilters.SHOW_ACTIVE: <add> return todos.filter(todo => !todo.completed) <ide> } <ide> } <ide> <ide> function select(state) { <ide> return { <ide> visibleTodos: selectTodos(state.todos, state.visibilityFilter), <ide> visibilityFilter: state.visibilityFilter <del> }; <add> } <ide> } <ide> <ide> // Wrap the component to inject dispatch and state into it <del>export default connect(select)(App); <add>export default connect(select)(App) <ide> ``` <ide> <ide> That’s it! The tiny todo app now functions correctly.
6
Text
Text
add more detail to svg paths
88bf0150f4dd5561d7ac6f63d00de77a05a3032c
<ide><path>guide/english/svg/shapes/index.md <ide> title: SVG Shapes <ide> <ide> Several shapes can be created using SVG drawing. An SVG drawing can use and combine seven shapes: Path, Rectangle, Circle, Ellipse, Line, Polyline, and Polygon. <ide> <add>Almost all shapes take these common attributes: <add> <add>``` <add>fill: color to be filled <add>stroke: color of the stroke <add>stroke-width: how wide the width is <add>``` <add> <ide> ### Path <ide> <ide> The `path` element is the most commonly seen, and is usually generated by programs designed to export SVG code. <ide> The `path` element is the most commonly seen, and is usually generated by progra <ide> <path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" /> <ide> ``` <ide> <del>The example `path` above will generate a "plus" symbole (+) when used inside an SVG drawing. SVG `path` elements are not built manually, but generated through design programs that can manipulate vector graphics, such as Illustrator or Inkscape. <add>The example `path` above will generate a "plus" symbol (+) when used inside an SVG drawing. <add> <add>SVG `path` elements are not usually coded manually, but generated through design programs that can manipulate vector graphics, such as Adobe Illustrator or Inkscape. However, with enough practice, you will be able to make impressive icons writing your own `path` element. <add> <add>The `d` property is known as "Line commands", and it tells the drawing engine how you want things to be drawn. All line commands come in upper- and lower-case forms, where the upper-case form is absolute positioning, and the lower-case form is relative from the previous point. <add> <add>The basic line commands are as follows: <add> <add>* M/m (x y): `M`ove to this point. Imagine this as picking up your pen and placing it on this point. It does not draw anything. <add>* L/l (x y): draw a `L`ine to this point. <add>* H/h (x): draw a horizontal line to this point. Equivalent to `L/l x 0` <add>* V/v (y): draw a vertical line to this point. Equivalent to `L/l 0 y` <add>* Z/z (no args): draws a line from the last point to this point. No difference in upper/lower case. <add> <add>There are more complicated line commands, which you can read more about on the [MDN Docs on Paths](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths). <ide> <ide> ### Rectangle <ide> <ide> This example will draw the same shape as the `polyline` above, but it will draw <ide> ## More Information <ide> <ide> MDN Documentation: <a href='https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Basic_Shapes' target='_blank' rel='nofollow'>MDN</a> <add>[MDN Docs on Paths](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths)
1
Python
Python
add multilingual documentation support
8ff619d95eb21f74ac0a1ef97b8313c5d25e029d
<ide><path>docs/source/conf.py <ide> # A list of files that should not be packed into the epub file. <ide> epub_exclude_files = ["search.html"] <ide> <add># Localization <add>locale_dirs = ['locale/'] <add>gettext_compact = False <ide> <ide> def setup(app): <ide> app.add_css_file("css/huggingface.css") <ide><path>setup.py <ide> "sphinx-rtd-theme==0.4.3", # sphinx-rtd-theme==0.5.0 introduced big changes in the style. <ide> "sphinx==3.2.1", <ide> "sphinxext-opengraph==0.4.1", <add> "sphinx-intl", <ide> "starlette", <ide> "tensorflow-cpu>=2.3", <ide> "tensorflow>=2.3", <ide> def run(self): <ide> "sphinx-rtd-theme", <ide> "sphinx-copybutton", <ide> "sphinxext-opengraph", <add> "sphinx-intl", <ide> ) <ide> # "docs" needs "all" to resolve all the references <ide> extras["docs"] = extras["all"] + extras["docs_specific"] <ide><path>src/transformers/dependency_versions_table.py <ide> "sphinx-rtd-theme": "sphinx-rtd-theme==0.4.3", <ide> "sphinx": "sphinx==3.2.1", <ide> "sphinxext-opengraph": "sphinxext-opengraph==0.4.1", <add> "sphinx-intl": "sphinx-intl", <ide> "starlette": "starlette", <ide> "tensorflow-cpu": "tensorflow-cpu>=2.3", <ide> "tensorflow": "tensorflow>=2.3",
3
Javascript
Javascript
support custom properties
619bf98d5b479f9582dbc40259b666f1c5a83146
<ide><path>src/css.js <ide> var <ide> // except "table", "table-cell", or "table-caption" <ide> // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display <ide> rdisplayswap = /^(none|table(?!-c[ea]).+)/, <add> rcustomProp = /^--/, <ide> cssShow = { position: "absolute", visibility: "hidden", display: "block" }, <ide> cssNormalTransform = { <ide> letterSpacing: "0", <ide> function vendorPropName( name ) { <ide> } <ide> } <ide> <add>// Return a property mapped along what jQuery.cssProps suggests or to <add>// a vendor prefixed property. <add>function finalPropName( name ) { <add> var ret = jQuery.cssProps[ name ]; <add> if ( !ret ) { <add> ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; <add> } <add> return ret; <add>} <add> <ide> function setPositiveNumber( elem, value, subtract ) { <ide> <ide> // Any relative (+/-) values have already been <ide> jQuery.extend( { <ide> // Make sure that we're working with the right name <ide> var ret, type, hooks, <ide> origName = jQuery.camelCase( name ), <add> isCustomProp = rcustomProp.test( name ), <ide> style = elem.style; <ide> <del> name = jQuery.cssProps[ origName ] || <del> ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); <add> // Make sure that we're working with the right name. We don't <add> // want to query the value if it is a CSS custom property <add> // since they are user-defined. <add> if ( !isCustomProp ) { <add> name = finalPropName( origName ); <add> } <ide> <ide> // Gets hook for the prefixed version, then unprefixed version <ide> hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; <ide> jQuery.extend( { <ide> if ( !hooks || !( "set" in hooks ) || <ide> ( value = hooks.set( elem, value, extra ) ) !== undefined ) { <ide> <del> style[ name ] = value; <add> if ( isCustomProp ) { <add> style.setProperty( name, value ); <add> } else { <add> style[ name ] = value; <add> } <ide> } <ide> <ide> } else { <ide> jQuery.extend( { <ide> <ide> css: function( elem, name, extra, styles ) { <ide> var val, num, hooks, <del> origName = jQuery.camelCase( name ); <add> origName = jQuery.camelCase( name ), <add> isCustomProp = rcustomProp.test( name ); <ide> <del> // Make sure that we're working with the right name <del> name = jQuery.cssProps[ origName ] || <del> ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); <add> // Make sure that we're working with the right name. We don't <add> // want to modify the value if it is a CSS custom property <add> // since they are user-defined. <add> if ( !isCustomProp ) { <add> name = finalPropName( origName ); <add> } <ide> <ide> // Try prefixed name followed by the unprefixed name <ide> hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; <ide> jQuery.extend( { <ide> num = parseFloat( val ); <ide> return extra === true || isFinite( num ) ? num || 0 : val; <ide> } <add> <ide> return val; <ide> } <ide> } ); <ide><path>src/css/curCSS.js <ide> function curCSS( elem, name, computed ) { <ide> <ide> computed = computed || getStyles( elem ); <ide> <del> // Support: IE <=9 only <del> // getPropertyValue is only needed for .css('filter') (#12537) <add> // getPropertyValue is needed for: <add> // .css('filter') (IE 9 only, #12537) <add> // .css('--customProperty) (#3144) <ide> if ( computed ) { <ide> ret = computed.getPropertyValue( name ) || computed[ name ]; <ide> <ide><path>test/unit/css.js <ide> QUnit.test( "Do not throw on frame elements from css method (#15098)", function( <ide> <ide> } )(); <ide> <add> <add>QUnit.test( "css(--customProperty)", function( assert ) { <add> jQuery( "#qunit-fixture" ).append( <add> "<style>\n" + <add> " .test__customProperties {\n" + <add> " --prop1:val1;\n" + <add> " --prop2: val2;\n" + <add> " --prop3:val3 ;\n" + <add> " --prop4:\"val4\";\n" + <add> " --prop5:'val5';\n" + <add> " }\n" + <add> "</style>" <add> ); <add> <add> var div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ), <add> $elem = jQuery( "<div>" ).addClass( "test__customProperties" ).appendTo( "#qunit-fixture" ), <add> webkit = /\bsafari\b/i.test( navigator.userAgent ) && <add> !/\firefox\b/i.test( navigator.userAgent ) && <add> !/\edge\b/i.test( navigator.userAgent ), <add> oldSafari = webkit && ( /\b9\.\d(\.\d+)* safari/i.test( navigator.userAgent ) || <add> /\b10\.0(\.\d+)* safari/i.test( navigator.userAgent ) ), <add> expected = 10; <add> <add> if ( webkit ) { <add> expected -= 2; <add> } <add> if ( oldSafari ) { <add> expected -= 2; <add> } <add> assert.expect( expected ); <add> <add> div.css( "--color", "blue" ); <add> assert.equal( div.css( "--color" ), "blue", "Modified CSS custom property using string" ); <add> <add> div.css( "--color", "yellow" ); <add> assert.equal( div.css( "--color" ), "yellow", "Overwrite CSS custom property" ); <add> <add> div.css( { "--color": "red" } ); <add> assert.equal( div.css( "--color" ), "red", "Modified CSS custom property using object" ); <add> <add> div.css( { "--mixedCase": "green" } ); <add> assert.equal( div.css( "--mixedCase" ), "green", "Modified CSS custom property with mixed case" ); <add> <add> div.css( { "--theme-dark": "purple" } ); <add> assert.equal( div.css( "--theme-dark" ), "purple", "Modified CSS custom property with dashed name" ); <add> <add> assert.equal( $elem.css( "--prop1" ), "val1", "Basic CSS custom property" ); <add> <add> // Support: Safari 9.1-10.0 only <add> // Safari collapses whitespaces & quotes. Ignore it. <add> if ( !oldSafari ) { <add> assert.equal( $elem.css( "--prop2" ), " val2", "Preceding whitespace maintained" ); <add> assert.equal( $elem.css( "--prop3" ), "val3 ", "Following whitespace maintained" ); <add> } <add> <add> // Support: Chrome 49-55, Safari 9.1-10.0 <add> // Chrome treats single quotes as double ones. <add> // Safari treats double quotes as single ones. <add> if ( !webkit ) { <add> assert.equal( $elem.css( "--prop4" ), "\"val4\"", "Works with double quotes" ); <add> assert.equal( $elem.css( "--prop5" ), "'val5'", "Works with single quotes" ); <add> } <add>} ); <add> <ide> }
3
PHP
PHP
allow connection in 'exists' validation (test)
9ad2666abfc64e81dc3b4e7cdc5e24ab0c6cdab1
<ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidationExists() <ide> $mock3->shouldReceive('getMultiCount')->once()->with('users', 'email_addr', ['foo'], [])->andReturn(false); <ide> $v->setPresenceVerifier($mock3); <ide> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:connection.users']); <add> $mock5 = m::mock('Illuminate\Validation\PresenceVerifierInterface'); <add> $mock5->shouldReceive('setConnection')->once()->with('connection'); <add> $mock5->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, [])->andReturn(true); <add> $v->setPresenceVerifier($mock5); <add> $this->assertTrue($v->passes()); <ide> } <ide> <ide> public function testValidationExistsIsNotCalledUnnecessarily()
1
Python
Python
eliminate more warnings in testing
c08e80eb6c1f47a9d65e363316ae1f6c6e6f870d
<ide><path>numpy/core/numeric.py <ide> class errstate(object): <ide> # Note that we don't want to run the above doctests because they will fail <ide> # without a from __future__ import with_statement <ide> def __init__(self, **kwargs): <del> try: <del> self.errcall = kwargs.pop('errcall') <del> except KeyError: <del> self.errcall = None <add> self.call = kwargs.pop('call',None) <ide> self.kwargs = kwargs <ide> def __enter__(self): <ide> self.oldstate = seterr(**self.kwargs) <del> self.oldcall = seterrcall(self.errcall) <add> if self.call: <add> self.oldcall = seterrcall(self.call) <ide> def __exit__(self, *exc_info): <ide> seterr(**self.oldstate) <del> seterrcall(self.oldcall) <add> if self.call: <add> seterrcall(self.oldcall) <ide> <ide> def _setdef(): <ide> defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT2, None] <ide><path>numpy/core/tests/test_ma.py <ide> def check_testUfuncs1 (self): <ide> self.failUnless (eq(numpy.tanh(x), tanh(xm))) <ide> olderr = numpy.seterr(divide='ignore', invalid='ignore') <ide> self.failUnless (eq(numpy.sqrt(abs(x)), sqrt(xm))) <del> numpy.seterr(**olderr) <ide> self.failUnless (eq(numpy.log(abs(x)), log(xm))) <ide> self.failUnless (eq(numpy.log10(abs(x)), log10(xm))) <add> numpy.seterr(**olderr) <ide> self.failUnless (eq(numpy.exp(x), exp(xm))) <ide> self.failUnless (eq(numpy.arcsin(z), arcsin(zm))) <ide> self.failUnless (eq(numpy.arccos(z), arccos(zm))) <ide> def check_testUfuncRegression(self): <ide> mf = getattr(numpy.ma, f) <ide> args = self.d[:uf.nin] <ide> olderr = numpy.geterr() <del> if f in ['sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh']: <add> if f in ['sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh', 'log', <add> 'log10','divide','true_divide', 'floor_divide', 'remainder', 'fmod']: <ide> numpy.seterr(invalid='ignore') <del> if f in ['arctanh']: <del> numpyseterr(divide='ignore'] <add> if f in ['arctanh', 'log', 'log10']: <add> numpy.seterr(divide='ignore') <ide> ur = uf(*args) <ide> mr = mf(*args) <ide> numpy.seterr(**olderr)
2
Go
Go
allow unc paths on build
df7ab6f3dbec85c1cf32b36c4c7dcfdc374f6566
<ide><path>api/client/build.go <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> return nil <ide> } <ide> <add>// isUNC returns true if the path is UNC (one starting \\). It always returns <add>// false on Linux. <add>func isUNC(path string) bool { <add> return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`) <add>} <add> <ide> // getDockerfileRelPath uses the given context directory for a `docker build` <ide> // and returns the absolute path to the context directory, the relative path of <ide> // the dockerfile in that context directory, and a non-nil error on success. <ide> func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDi <ide> <ide> // The context dir might be a symbolic link, so follow it to the actual <ide> // target directory. <del> absContextDir, err = filepath.EvalSymlinks(absContextDir) <del> if err != nil { <del> return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err) <add> // <add> // FIXME. We use isUNC (always false on non-Windows platforms) to workaround <add> // an issue in golang. On Windows, EvalSymLinks does not work on UNC file <add> // paths (those starting with \\). This hack means that when using links <add> // on UNC paths, they will not be followed. <add> if !isUNC(absContextDir) { <add> absContextDir, err = filepath.EvalSymlinks(absContextDir) <add> if err != nil { <add> return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err) <add> } <ide> } <ide> <ide> stat, err := os.Lstat(absContextDir) <ide> func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDi <ide> } <ide> <ide> // Evaluate symlinks in the path to the Dockerfile too. <del> absDockerfile, err = filepath.EvalSymlinks(absDockerfile) <del> if err != nil { <del> return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err) <add> // <add> // FIXME. We use isUNC (always false on non-Windows platforms) to workaround <add> // an issue in golang. On Windows, EvalSymLinks does not work on UNC file <add> // paths (those starting with \\). This hack means that when using links <add> // on UNC paths, they will not be followed. <add> if !isUNC(absDockerfile) { <add> absDockerfile, err = filepath.EvalSymlinks(absDockerfile) <add> if err != nil { <add> return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err) <add> } <ide> } <ide> <ide> if _, err := os.Lstat(absDockerfile); err != nil {
1
PHP
PHP
bind only true ints as ints
6e77be515a1830ebcae9dce5a504e2b74a089dad
<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_INT) !== false ? PDO::PARAM_INT : PDO::PARAM_STR <add> is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR <ide> ); <ide> } <ide> }
1
Text
Text
remove comments about react 0.13
d31a333e6b9ff1d554fee097fd58ca96a53f35ff
<ide><path>docs/basics/ExampleTodoList.md <ide> let store = createStore(todoApp); <ide> <ide> let rootElement = document.getElementById('root'); <ide> render( <del> // The child must be wrapped in a function <del> // to work around an issue in React 0.13. <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>, <ide><path>docs/basics/UsageWithReact.md <ide> let store = createStore(todoApp); <ide> <ide> let rootElement = document.getElementById('root'); <ide> render( <del> // The child must be wrapped in a function <del> // to work around an issue in React 0.13. <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>,
2
Text
Text
fix spellings error
8214fa6b26862334214fb7a82a23aa7d4841b1a4
<ide><path>docs/introduction/GettingStarted.md <ide> The [**Redux Fundamentals tutorial**](../tutorials/fundamentals/part-1-overview. <ide> <ide> ### Learn Modern Redux Livestream <ide> <del>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with Typescript, as well as the new RTK Query data fetching APIs. <add>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with TypeScript, as well as the new RTK Query data fetching APIs. <ide> <ide> See [the "Learn Modern Redux" show notes page](https://www.learnwithjason.dev/let-s-learn-modern-redux) for a transcript and links to the example app source. <ide> <ide><path>docs/introduction/LearningResources.md <ide> This page includes our recommendations for some of the best external resources a <ide> <ide> _Tutorials that teach the basic concepts of Redux and how to use it_ <ide> <del>- **Intro to React, Redux, and Typescript** <br /> <add>- **Intro to React, Redux, and TypeScript** <br /> <ide> https://blog.isquaredsoftware.com/2020/12/presentations-react-redux-ts-intro/ <br /> <ide> Redux maintainer Mark Erikson's slideset that covers the basics of React, Redux, and TypeScript. Redux topics include stores, reducers, middleware, React-Redux, and Redux Toolkit. <ide> <ide> _Tutorials that teach the basic concepts of Redux and how to use it_ <ide> https://www.freecodecamp.org/news/redux-for-beginners-the-brain-friendly-guide-to-redux/ <br /> <ide> An easy-to-follow tutorial that builds a small todo app with Redux Toolkit and React-Redux, including data fetching. <ide> <del>- **Redux made easy with Redux Toolkit and Typescript** <br /> <add>- **Redux made easy with Redux Toolkit and TypeScript** <br /> <ide> https://www.mattbutton.com/redux-made-easy-with-redux-toolkit-and-typescript/ <br /> <ide> A helpful tutorial that shows how to use Redux Toolkit and TypeScript together to write Redux applications, and how RTK simplifies typical Redux usage. <ide> <ide><path>docs/tutorials/tutorials-index.md <ide> We have two different full-size tutorials: <ide> <ide> ### Learn Modern Redux Livestream <ide> <del>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with Typescript, as well as the new RTK Query data fetching APIs: <add>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with TypeScript, as well as the new RTK Query data fetching APIs: <ide> <ide> <LiteYouTubeEmbed <ide> id="9zySeP5vH9c" <ide><path>docs/tutorials/videos.md <ide> While we don't currently have any "official" Redux tutorial videos from the Redu <ide> <ide> ## Learn Modern Redux Livestream <ide> <del>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with Typescript, as well as the new RTK Query data fetching APIs: <add>Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with TypeScript, as well as the new RTK Query data fetching APIs: <ide> <ide> <LiteYouTubeEmbed <ide> id="9zySeP5vH9c"
4
Python
Python
use a line-break in the `nested_iters` signature
2fa73cd2296ee68626d2cb3b816aaa39ba546e2d
<ide><path>numpy/core/_add_newdocs.py <ide> <ide> add_newdoc('numpy.core', 'nested_iters', <ide> """ <del> nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, order="K", casting="safe", buffersize=0) <add> nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, \ <add> order="K", casting="safe", buffersize=0) <ide> <ide> Create nditers for use in nested loops <ide>
1
PHP
PHP
fix more typing issues
7dd994e7891fa91c997b0c2e6cb95fb92edd517f
<ide><path>src/Database/Exception/NestedTransactionRollbackException.php <ide> class NestedTransactionRollbackException extends Exception <ide> * Constructor <ide> * <ide> * @param string|null $message If no message is given a default meesage will be used. <del> * @param int $code Status code, defaults to 500. <add> * @param int|null $code Status code, defaults to 500. <ide> * @param \Throwable|null $previous the previous exception. <ide> */ <del> public function __construct(?string $message = null, int $code = 500, ?Throwable $previous = null) <add> public function __construct(?string $message = null, ?int $code = 500, ?Throwable $previous = null) <ide> { <ide> if ($message === null) { <ide> $message = 'Cannot commit transaction - rollback() has been already called in the nested transaction'; <ide><path>src/Database/IdentifierQuoter.php <ide> protected function _quoteInsert(Query $query): void <ide> $table = $this->_driver->quoteIdentifier($table); <ide> foreach ($columns as &$column) { <ide> if (is_scalar($column)) { <del> $column = $this->_driver->quoteIdentifier($column); <add> $column = $this->_driver->quoteIdentifier((string)$column); <ide> } <ide> } <ide> $query->insert($columns)->into($table); <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function testJunctionConnection() <ide> { <ide> $mock = $this->getMockBuilder('Cake\Database\Connection') <ide> ->setMethods(['setDriver']) <del> ->setConstructorArgs(['name' => 'other_source']) <add> ->setConstructorArgs([['name' => 'other_source']]) <ide> ->getMock(); <ide> ConnectionManager::setConfig('other_source', $mock); <ide> $this->article->setConnection(ConnectionManager::get('other_source')); <ide><path>tests/TestCase/TestSuite/TestFixtureTest.php <ide> namespace Cake\Test\TestCase\TestSuite; <ide> <ide> use Cake\Database\Schema\TableSchema; <add>use Cake\Database\StatementInterface; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\Fixture\TestFixture; <ide> public function testCreate() <ide> ->will($this->returnValue(['sql', 'sql'])); <ide> $fixture->setTableSchema($table); <ide> <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['execute', 'closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->atLeastOnce())->method('closeCursor'); <ide> $statement->expects($this->atLeastOnce())->method('execute'); <add> <ide> $db->expects($this->exactly(2)) <ide> ->method('prepare') <ide> ->will($this->returnValue($statement)); <ide> public function testInsert() <ide> ->with($expected[2]) <ide> ->will($this->returnSelf()); <ide> <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->once())->method('closeCursor'); <add> <ide> $query->expects($this->once()) <ide> ->method('execute') <ide> ->will($this->returnValue($statement)); <ide> public function testInsertImport() <ide> ->with($expected[0]) <ide> ->will($this->returnSelf()); <ide> <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->once())->method('closeCursor'); <add> <ide> $query->expects($this->once()) <ide> ->method('execute') <ide> ->will($this->returnValue($statement)); <ide> public function testInsertStrings() <ide> ->with($expected[2]) <ide> ->will($this->returnSelf()); <ide> <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->once())->method('closeCursor'); <add> <ide> $query->expects($this->once()) <ide> ->method('execute') <ide> ->will($this->returnValue($statement)); <ide> public function testDrop() <ide> $db = $this->getMockBuilder('Cake\Database\Connection') <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->once())->method('closeCursor'); <ide> $db->expects($this->once())->method('execute') <ide> ->with('sql') <ide> public function testTruncate() <ide> $db = $this->getMockBuilder('Cake\Database\Connection') <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $statement = $this->getMockBuilder('\PDOStatement') <del> ->setMethods(['closeCursor']) <del> ->getMock(); <add> $statement = $this->createMock(StatementInterface::class); <ide> $statement->expects($this->once())->method('closeCursor'); <add> <ide> $db->expects($this->once())->method('execute') <ide> ->with('sql') <ide> ->will($this->returnValue($statement));
4
Python
Python
fix meta defaults and error in package command
b89f6fa011c6f49e3e04041c6646c045ffe45845
<ide><path>spacy/cli/package.py <ide> def package( <ide> meta = generate_meta(meta, msg) <ide> errors = validate(ModelMetaSchema, meta) <ide> if errors: <del> msg.fail("Invalid model meta.json", "\n".join(errors), exits=1) <add> msg.fail("Invalid model meta.json") <add> print("\n".join(errors)) <add> sys.exit(1) <ide> model_name = meta["lang"] + "_" + meta["name"] <ide> model_name_v = model_name + "-" + meta["version"] <ide> main_path = output_dir / model_name_v <ide> def get_meta( <ide> "lang": "en", <ide> "name": "model", <ide> "version": "0.0.0", <del> "description": None, <del> "author": None, <del> "email": None, <del> "url": None, <add> "description": "", <add> "author": "", <add> "email": "", <add> "url": "", <ide> "license": "MIT", <ide> } <ide> meta.update(existing_meta)
1
PHP
PHP
add methods to get/set default strategy class
8db3384ae4a14721716d60cb6946c6f9836a1dbf
<ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface <ide> 'getLocale' => 'getLocale', <ide> 'translationField' => 'translationField', <ide> ], <del> 'strategyClass' => EavStrategy::class, <ide> 'fields' => [], <ide> 'defaultLocale' => '', <ide> 'referenceName' => '', <ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface <ide> 'validator' => false, <ide> ]; <ide> <add> /** <add> * Default strategy class name. <add> * <add> * @var string <add> */ <add> protected static $defaultStrategyClass = EavStrategy::class; <add> <ide> /** <ide> * Translation strategy instance. <ide> * <ide> public function initialize(array $config) <ide> $this->getStrategy(); <ide> } <ide> <add> /** <add> * Set default strategy class name. <add> * <add> * @param string $class Class name. <add> * @return void <add> */ <add> public static function setDefaultStrategyClass(string $class) <add> { <add> static::$defaultStrategyClass = $class; <add> } <add> <add> /** <add> * Get default strategy class name. <add> * <add> * @return string <add> */ <add> public static function getDefaultStrategyClass(): string <add> { <add> return static::$defaultStrategyClass; <add> } <add> <ide> /** <ide> * Get strategy class instance. <ide> * <ide> public function getStrategy(): TranslateStrategyInterface <ide> return $this->strategy; <ide> } <ide> <add> return $this->strategy = $this->createStrategy(); <add> } <add> <add> /** <add> * Create strategy instance. <add> * <add> * @return \Cake\ORM\Behavior\Translate\TranslateStrategyInterface <add> */ <add> protected function createStrategy() <add> { <ide> $config = array_diff_key( <ide> $this->_config, <ide> ['implementedFinders', 'implementedMethods', 'strategyClass'] <ide> ); <del> $this->strategy = new $this->_config['strategyClass']($this->_table, $config); <add> $className = $this->getConfig('strategyClass', static::$defaultStrategyClass); <ide> <del> return $this->strategy; <add> return new $className($this->_table, $config); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php <ide> <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\I18n\I18n; <add>use Cake\ORM\Behavior\TranslateBehavior; <add>use Cake\ORM\Behavior\Translate\EavStrategy; <ide> use Cake\ORM\Behavior\Translate\ShadowTableStrategy; <ide> use Cake\ORM\Behavior\Translate\TranslateTrait; <ide> use Cake\ORM\Entity; <ide> class BakedArticle extends Entity <ide> ]; <ide> } <ide> <del>class Table extends \Cake\ORM\Table <del>{ <del> public function addBehavior($name, array $options = []) <del> { <del> if ($name === 'Translate') { <del> $options['strategyClass'] = ShadowTableStrategy::class; <del> <del> $this->_behaviors->load('Translate', $options); <del> <del> return; <del> } <del> <del> parent::addBehavior($name, $options); <del> } <del>} <del> <ide> /** <ide> * TranslateBehavior test case <ide> */ <ide> class TranslateBehaviorShadowTableTest extends TranslateBehaviorTest <ide> ]; <ide> <ide> /** <del> * Seed the table registry with this test case's Table class <add> * setUpBeforeClass <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public static function setUpBeforeClass() <ide> { <del> parent::setUp(); <add> TranslateBehavior::setDefaultStrategyClass(ShadowTableStrategy::class); <ide> <del> $aliases = ['Articles', 'Authors', 'Comments', 'Tags', 'SpecialTags', 'Groups']; <del> $options = ['className' => Table::class]; <add> parent::setUpBeforeClass(); <add> } <add> <add> /** <add> * tearDownAfterClass <add> * <add> * @return void <add> */ <add> public static function tearDownAfterClass() <add> { <add> TranslateBehavior::setDefaultStrategyClass(EavStrategy::class); <ide> <del> foreach ($aliases as $alias) { <del> $this->getTableLocator()->get($alias, $options); <del> } <add> parent::tearDownAfterClass(); <ide> } <ide> <ide> /** <ide> public function testDefaultAliases() <ide> */ <ide> public function testDefaultPluginAliases() <ide> { <del> $table = $this->getTableLocator()->get( <del> 'SomeRandomPlugin.Articles', <del> ['className' => Table::class] <del> ); <add> $table = $this->getTableLocator()->get('SomeRandomPlugin.Articles'); <ide> <ide> $table->getTable(); <ide> $table->addBehavior('Translate'); <ide> public function testDefaultPluginAliases() <ide> $this->_testFind('SomeRandomPlugin.Articles'); <ide> } <ide> <add> /** <add> * testAutoReferenceName <add> * <add> * The parent test is EAV specific. Test that the config reflects the referenceName - <add> * which is used to determine the the translation table/association name only in the <add> * shadow translate behavior <add> */ <add> public function testAutoReferenceName() <add> { <add> $table = $this->getTableLocator()->get('Articles'); <add> $table->getTable(); <add> $table->addBehavior('Translate'); <add> <add> $config = $table->behaviors()->get('Translate')->getStrategy()->getConfig(); <add> $wantedKeys = [ <add> 'translationTable', <add> 'mainTableAlias', <add> 'hasOneAlias', <add> ]; <add> <add> $config = array_intersect_key($config, array_flip($wantedKeys)); <add> $expected = [ <add> 'translationTable' => 'ArticlesTranslations', <add> 'mainTableAlias' => 'Articles', <add> 'hasOneAlias' => 'ArticlesTranslation', <add> ]; <add> $this->assertEquals($expected, $config, 'The translationTable key should be derived from referenceName'); <add> } <add> <ide> /** <ide> * testChangingReferenceName <ide> * <ide> public function testSelfJoin() <ide> $table->setLocale('eng'); <ide> <ide> $table->belongsTo('Copy', ['className' => 'Articles', 'foreignKey' => 'author_id']); <del> $table->Copy->addBehavior('Translate', [ <del> 'strategyClass' => ShadowTableStrategy::class, <del> ]); <add> $table->Copy->addBehavior('Translate'); <ide> $table->Copy->setLocale('deu'); <ide> <ide> $query = $table->find()
2
Text
Text
remove duplicate period
6ee8e929c30ff7c95bab65bee6e9ce503c3c3331
<ide><path>guides/source/asset_pipeline.md <ide> The first feature of the pipeline is to concatenate assets. This is important in <ide> <ide> Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `:cache => true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries. <ide> <del>Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` file. As you'll learn later in this guide, you can customize this strategy to group files any way you like. In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser. You can invalidate the cache by altering this fingerprint, which happens automatically whenever you change the file contents.. <add>Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` file. As you'll learn later in this guide, you can customize this strategy to group files any way you like. In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser. You can invalidate the cache by altering this fingerprint, which happens automatically whenever you change the file contents. <ide> <ide> The second feature of the asset pipeline is asset minification or compression. For CSS files, this is done by removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own. <ide>
1
Ruby
Ruby
keep rescue template paths in an array
5c6e9d48e18fe72ca0cf0f3594494c0f34ffefd3
<ide><path>actionpack/lib/action_dispatch/middleware/debug_view.rb <ide> <ide> module ActionDispatch <ide> class DebugView < ActionView::Base # :nodoc: <del> RESCUES_TEMPLATE_PATH = File.expand_path("templates", __dir__) <add> RESCUES_TEMPLATE_PATHS = [File.expand_path("templates", __dir__)] <ide> <ide> def initialize(assigns) <del> paths = [RESCUES_TEMPLATE_PATH] <add> paths = RESCUES_TEMPLATE_PATHS.dup <ide> lookup_context = ActionView::LookupContext.new(paths) <ide> super(lookup_context, assigns, nil) <ide> end <ide><path>railties/lib/rails/info_controller.rb <ide> require "action_dispatch/routing/inspector" <ide> <ide> class Rails::InfoController < Rails::ApplicationController # :nodoc: <del> prepend_view_path ActionDispatch::DebugView::RESCUES_TEMPLATE_PATH <add> prepend_view_path ActionDispatch::DebugView::RESCUES_TEMPLATE_PATHS <ide> layout -> { request.xhr? ? false : "application" } <ide> <ide> before_action :require_local! <ide><path>railties/lib/rails/mailers_controller.rb <ide> require "rails/application_controller" <ide> <ide> class Rails::MailersController < Rails::ApplicationController # :nodoc: <del> prepend_view_path ActionDispatch::DebugView::RESCUES_TEMPLATE_PATH <add> prepend_view_path ActionDispatch::DebugView::RESCUES_TEMPLATE_PATHS <ide> <ide> around_action :set_locale, only: [:preview, :download] <ide> before_action :find_preview, only: [:preview, :download]
3
PHP
PHP
fix incorrect @return value in docblock
b877dadfe9d892244a7418f4ea446e1dd4dbc8c0
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function create(array $attributes, array $joining = [], $touch = true) <ide> * <ide> * @param array $records <ide> * @param array $joinings <del> * @return \Illuminate\Database\Eloquent\Model <add> * @return array <ide> */ <ide> public function createMany(array $records, array $joinings = []) <ide> {
1
Javascript
Javascript
fix broken layout caused by unclosed `
17ddba873b49d9329f09b67bb52088e40cb9979a
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. <ide> * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. <ide> * <del> * - **`defaults.jsonpCallbackParam`** - `{string} - the name of the query parameter that passes the name of the <add> * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the <ide> * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the <ide> * {@link $jsonpCallbacks} service. Defaults to `'callback'`. <ide> *
1
Text
Text
add notes on cosmetic patches
6143de0b927089f48b58fa6a8c924e658c9373fc
<ide><path>CONTRIBUTING.md <ide> <ide> * Before submitting, please read the [Contributing to Ruby on Rails](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) guide to know more about coding conventions and benchmarks. <ide> <add>#### **Did you fix whitespace, format code, or make a purely cosmetic patch?** <add> <add>Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted (read more about [our rationales behind this decision](https://github.com/rails/rails/pull/13771#issuecomment-32746700)). <add> <ide> #### **Do you intend to add a new feature or change an existing one?** <ide> <ide> * Suggest your change in the [rubyonrails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core) and start writing code.
1
Python
Python
add part to tag map
f112e7754e4f4368f0a82c3aae3a58f5300176f0
<ide><path>spacy/language_data/tag_map.py <ide> "X": {POS: X}, <ide> "CONJ": {POS: CONJ}, <ide> "ADJ": {POS: ADJ}, <del> "VERB": {POS: VERB} <add> "VERB": {POS: VERB}, <add> "PART": {POS: PART} <ide> }
1
Text
Text
add import in docs. [ci skip]
febaa4db00c322d169a5e60ecd22c909e8a836c2
<ide><path>docs/api-guide/throttling.md <ide> If the `.wait()` method is implemented and the request is throttled, then a `Ret <ide> <ide> The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. <ide> <add> import random <add> <ide> class RandomRateThrottle(throttling.BaseThrottle): <ide> def allow_request(self, request, view): <ide> return random.randint(1, 10) == 1
1
Mixed
Python
handle binary or unicode with jsonfield
265ec8ac62ef4b2b8ee74525e7c263bf559a2355
<ide><path>docs/api-guide/fields.md <ide> You can also use the declarative style, as with `ListField`. For example: <ide> <ide> ## JSONField <ide> <del>A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON encoded strings. <add>A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. <ide> <ide> **Signature**: `JSONField(binary)` <ide> <ide><path>rest_framework/fields.py <ide> def __init__(self, *args, **kwargs): <ide> def to_internal_value(self, data): <ide> try: <ide> if self.binary: <add> if isinstance(data, six.binary_type): <add> data = data.decode('utf-8') <ide> return json.loads(data) <ide> else: <ide> json.dumps(data)
2
Javascript
Javascript
fix failing unit tests in tap gesture recognizer
274a545562554f631eb85a99874a26f433d97f3a
<ide><path>packages/sproutcore-touch/lib/gesture_recognizers/tap.js <ide> SC.TapGestureRecognizer = SC.Gesture.extend({ <ide> didBegin: function() { <ide> this._initialLocation = this.centerPointForTouches(this._touches); <ide> <del> this._waitingForMoreTouches = true; <del> this._waitingInterval = window.setInterval(this._intervalFired,this.MULTITAP_DELAY); <add> if (this._numActiveTouches < get(this, 'numberOfTaps')) { <add> this._waitingForMoreTouches = true; <add> this._waitingInterval = window.setInterval(this._intervalFired,this.MULTITAP_DELAY); <add> } <ide> }, <ide> <ide> shouldEnd: function() { <ide> var currentLocation = this.centerPointForTouches(this._touches); <del> var distance = this.distance([this._initialLocation,currentLocation]); <add> <add> var x = this._initialLocation.x; <add> var y = this._initialLocation.y; <add> var x0 = currentLocation.x; <add> var y0 = currentLocation.y; <add> <add> var distance = Math.sqrt((x -= x0) * x + (y -= y0) * y); <ide> <ide> return (distance <= this._moveThreshold) && !this._waitingForMoreTouches; <ide> }, <ide><path>packages/sproutcore-touch/lib/system/gesture.js <ide> SC.Gesture = SC.Object.extend( <ide> if (get(this, 'gestureIsDiscrete') && this.shouldBegin()) { <ide> set(this, 'state', SC.Gesture.BEGAN); <ide> this.didBegin(); <add> this.attemptGestureEventDelivery(evt, view, get(this, 'name')+'Start'); <ide> } else { <ide> set(this, 'state', SC.Gesture.POSSIBLE); <ide> this.didBecomePossible(); <ide><path>packages/sproutcore-touch/tests/gesture_recognizers/tap_test.js <ide> module("Tap Test",{ <ide> } <ide> }); <ide> <del>test("one start event should put it in possible state", function() { <add>test("one start event should put it in began state", function() { <ide> var numStart = 0; <ide> var touchEvent = jQuery.Event('touchstart'); <ide> touchEvent['originalEvent'] = { <ide> test("one start event should put it in possible state", function() { <ide> <ide> ok(gestures); <ide> equals(gestures.length,1); <del> equals(get(gestures[0], 'state'),SC.Gesture.POSSIBLE, "gesture should be possible"); <add> equals(get(gestures[0], 'state'),SC.Gesture.BEGAN, "gesture should be began"); <ide> }); <ide> <ide> test("when touch ends, tap should fire", function() { <ide> test("when touch ends, tap should fire", function() { <ide> pageY: 10 <ide> }] <ide> }; <add> <ide> view.$().trigger(touchEvent); <ide> <add> var gestures = get(get(view, 'eventManager'), 'gestures'); <add> <ide> ok(startCalled, 'tapStart should be called on the view'); <add> ok(gestures, "gestures should exist"); <add> equals(gestures.length,1); <add> equals(get(gestures[0], 'state'),SC.Gesture.BEGAN, "gesture should be began"); <ide> <ide> touchEvent = new jQuery.Event(); <ide> touchEvent.type='touchend'; <ide> touchEvent['originalEvent'] = { <ide> changedTouches: [{ <del> pageX: 20, <add> pageX: 5, <ide> pageY: 10 <ide> }] <ide> }; <ide> <ide> view.$().trigger(touchEvent); <ide> <del> var gestures = get(get(view, 'eventManager'), 'gestures'); <add> gestures = get(get(view, 'eventManager'), 'gestures'); <ide> <ide> ok(endCalled,'tap should be ended'); <ide> ok(gestures, "gestures should exist");
3
PHP
PHP
tweak some wording
6b939c477c34205a177e8a9d21fa82a1038472d6
<ide><path>app/Http/Controllers/Auth/AuthController.php <ide> class AuthController extends Controller { <ide> use AuthenticatesAndRegistersUsers; <ide> <ide> /** <del> * Where to redirect after registration or login. <add> * Redirect path after registration or login. <ide> * <ide> * @var string <ide> */ <ide><path>app/Http/Controllers/Auth/PasswordController.php <ide> class PasswordController extends Controller { <ide> use ResetsPasswords; <ide> <ide> /** <del> * Where to redirect after password reset. <add> * Redirect path after password reset. <ide> * <ide> * @var string <ide> */
2
PHP
PHP
add missing parameter to tomail
4df539c76353ff1931b0441f0d8f3f07bbf7b342
<ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php <ide> public function via($notifiable) <ide> /** <ide> * Build the mail representation of the notification. <ide> * <add> * @param mixed $notifiable <ide> * @return \Illuminate\Notifications\Messages\MailMessage <ide> */ <del> public function toMail() <add> public function toMail($notifiable) <ide> { <ide> return (new MailMessage) <ide> ->line('You are receiving this email because we received a password reset request for your account.')
1
Ruby
Ruby
call public methods rather than class_eval'ing
28f6b895c6eccd4347eb636c99ec4d54a026cabe
<ide><path>activemodel/lib/active_model/naming.rb <ide> def _singularize(string, replacement='_') <ide> # provided method below, or rolling your own is required. <ide> module Naming <ide> def self.extended(base) #:nodoc: <del> base.class_eval do <del> remove_possible_method(:model_name) <del> delegate :model_name, to: :class <del> end <add> base.remove_possible_method :model_name <add> base.delegate :model_name, to: :class <ide> end <ide> <ide> # Returns an ActiveModel::Name object for module. It can be
1
Javascript
Javascript
stop multiple prettier runs on large commits
0a5c7cbfcfb27d056ccebabe862c69181279d3a9
<ide><path>.lintstagedrc.js <ide> const { ESLint } = require('eslint'); <ide> <ide> const cli = new ESLint(); <ide> <add>// This lets us abort if we've already run a stage for all files <add>const completedStages = new Set(); <add> <ide> // if a lot of files are changed, it's faster to run prettier/eslint on the <ide> // whole project than to run them on each file separately <ide> module.exports = { <ide> '*.(js|ts|tsx)': async files => { <add> if (completedStages.has('js')) return []; <add> <ide> const ignoredIds = await Promise.all( <ide> files.map(file => cli.isPathIgnored(file)) <ide> ); <ide> const lintableFiles = files.filter((_, i) => !ignoredIds[i]); <del> return files.length > 10 <del> ? ['eslint --max-warnings=0 --cache --fix .', 'prettier --write .'] <del> : [ <del> 'eslint --max-warnings=0 --cache --fix ' + lintableFiles.join(' '), <del> ...files.map(filename => `prettier --write '${filename}'`) <del> ]; <add> if (files.length > 10) { <add> completedStages.add('js'); <add> return ['eslint --max-warnings=0 --cache --fix .', 'prettier --write .']; <add> } else { <add> return [ <add> 'eslint --max-warnings=0 --cache --fix ' + lintableFiles.join(' '), <add> ...files.map(filename => `prettier --write '${filename}'`) <add> ]; <add> } <add> }, <add> '*.!(js|ts|tsx)': files => { <add> if (completedStages.has('not-js')) return []; <add> <add> if (files.length > 10) { <add> completedStages.add('not-js'); <add> return 'prettier --write .'; <add> } else { <add> return files.map( <add> filename => `prettier --write --ignore-unknown '${filename}'` <add> ); <add> } <ide> }, <del> '*.!(js|ts|tsx)': files => <del> files.length > 10 <del> ? 'prettier --write .' <del> : files.map( <del> filename => `prettier --write --ignore-unknown '${filename}'` <del> ), <del> './curriculum/challenges/**/*.md': files => <del> files.length > 10 <del> ? 'npm run lint:challenges' <del> : files.map( <del> filename => `node ./tools/scripts/lint/index.js '${filename}'` <del> ) <add> <add> './curriculum/challenges/**/*.md': files => { <add> if (completedStages.has('markdown')) return []; <add> <add> if (files.length > 10) { <add> completedStages.add('markdown'); <add> return 'npm run lint:challenges'; <add> } else { <add> return files.map( <add> filename => `node ./tools/scripts/lint/index.js '${filename}'` <add> ); <add> } <add> } <ide> };
1
Text
Text
remove references to spaderun from readme
cdace7e3957374f2dcb02e89eebf05dacfa1b66a
<ide><path>README.md <ide> example, to run all of the unit tests together: <ide> <ide> # Adding New Packages <ide> <del>Be sure you include the new package as a dependency in the global `package.json` and run `spaderun update`. <del> <del>Note that unless you are adding new __tests__ or adding a new package you should not need to run `spaderun update`. <del> <add>Be sure you include the new package as a dependency in the global `package.json`.
1
Text
Text
replace github -> github (arabic)
504728857ffb194e04c0a720001a500f0583cc35
<ide><path>guide/arabic/electron/index.md <ide> localeTitle: الإلكترون <ide> * [Skype](https://www.skype.com/) (تطبيق الدردشة المرئية الشهير من Microsoft) <ide> * [سلاك](https://slack.com/) (تطبيق مراسلة للفرق) <ide> * [Discord](https://discordapp.com) (تطبيق مراسلة مشهور للاعبين) <del>* [سطح مكتب Github](https://desktop.github.com/) (عميل [Gitub Desktop](https://desktop.github.com/) الرسمي) <add>* [سطح مكتب GitHub](https://desktop.github.com/) (عميل [Gitub Desktop](https://desktop.github.com/) الرسمي) <ide> <ide> ### مراجع معلومات إضافية <ide> <ide> * [موقع رسمي](https://electronjs.org/) <ide> * [فيديو - ما هو الكترون](https://www.youtube.com/watch?v=8YP_nOCO-4Q&feature=youtu.be) <ide> * \[الإلكترون و Vue\]: https://medium.com/@kswanie21/electron-vue-js-f6c40abeb625 <ide> * \[Electron and React\]: https://medium.freecodecamp.org/building-an-electron-application-with-create-react-app-97945861647c <del>* \[Electron and Angular\]: https://scotch.io/tutorials/creating-desktop-applications-with-angularjs-and-github-electron <ide>\ No newline at end of file <add>* \[Electron and Angular\]: https://scotch.io/tutorials/creating-desktop-applications-with-angularjs-and-github-electron <ide><path>guide/arabic/game-development/unreal-engine/index.md <ide> localeTitle: محرك غير واقعي <ide> <ide> Uscript هي لغة البرمجة الأصلية الخاصة بالمحرك ، والتي تستخدم لإنشاء كود اللعبة وألعاب اللعب قبل إصدار Unreal Engine 4 ، وقد تم تصميمها للبرمجة عالية المستوى. تمت كتابة البرنامج النصي وبرمجته من قبل تيم سويني ، وهو أيضًا مبتكر لغة برمجة أخرى ، ZZT-oop. <ide> <del>منذ عام 2015 ، أصبح محرك Unreal مجانيًا للاستخدام ، مع فرض Epic رسومًا بنسبة 5٪ على مبيعات العناوين المنتجة باستخدام المحرك. تجعل Epic غالبية ملفاتهم متاحة عبر Github ، على الرغم من أن مصدر المنصات المغلقة مثل Playstation 4 و Xbox One متاح فقط لمطوري النظام الأساسي المسجلين. <add>منذ عام 2015 ، أصبح محرك Unreal مجانيًا للاستخدام ، مع فرض Epic رسومًا بنسبة 5٪ على مبيعات العناوين المنتجة باستخدام المحرك. تجعل Epic غالبية ملفاتهم متاحة عبر GitHub ، على الرغم من أن مصدر المنصات المغلقة مثل Playstation 4 و Xbox One متاح فقط لمطوري النظام الأساسي المسجلين. <ide> <ide> ### إصدارات غير حقيقية <ide> <ide> Uscript هي لغة البرمجة الأصلية الخاصة بالمحرك ، <ide> #### معلومات اكثر: <ide> <ide> [www.UnrealEngine.com](https://www.unrealengine.com/) <del>[www.EpicGames.com](https://github.com/EpicGames) <ide>\ No newline at end of file <add>[www.EpicGames.com](https://github.com/EpicGames) <ide><path>guide/arabic/git/difference-git-github/index.md <ide> localeTitle: الفرق بين جيت و جيثب <ide> --- <ide> ## الفرق بين جيت و جيثب <ide> <del>Git و Github هما شيئان مختلفان. [Git](https://git-scm.com/) هو [نظام التحكم في الإصدار](https://en.wikipedia.org/wiki/Version_control) ، في حين أن [GitHub](https://github.com/) هي خدمة لاستضافة Git repos ومساعدة الأشخاص على التعاون في كتابة البرامج. ومع ذلك ، فإنهم غالباً ما يكونون مرتبكين بسبب اسمهم المتشابه ، وذلك بسبب حقيقة أن GitHub يعتمد على Git ، ولأن العديد من المواقع والمقالات لا تجعل الفرق بينهما واضحًا بما فيه الكفاية. <add>Git و GitHub هما شيئان مختلفان. [Git](https://git-scm.com/) هو [نظام التحكم في الإصدار](https://en.wikipedia.org/wiki/Version_control) ، في حين أن [GitHub](https://github.com/) هي خدمة لاستضافة Git repos ومساعدة الأشخاص على التعاون في كتابة البرامج. ومع ذلك ، فإنهم غالباً ما يكونون مرتبكين بسبب اسمهم المتشابه ، وذلك بسبب حقيقة أن GitHub يعتمد على Git ، ولأن العديد من المواقع والمقالات لا تجعل الفرق بينهما واضحًا بما فيه الكفاية. <ide> <ide> ![Git ليس GitHub](https://i.imgur.com/EkjwJdr.png) <ide> <ide> GitHub هي شركة توفر استضافة Git للمستودعات. وهذا <ide> <ide> أكثر من مجرد خدمة استضافة Git مستودع ، GitHub هو [برنامج تزوير](https://en.wikipedia.org/wiki/Forge_(software)) . وهذا يعني أنه يوفر أيضًا أداة [تعقب المشكلات وأدواتًا](https://en.wikipedia.org/wiki/Issue_tracking_system) [لمراجعة الشفرة](https://en.wikipedia.org/wiki/Code_review) وأدوات أخرى للتعاون مع الآخرين وإنشاء برنامج. <ide> <del>GitHub ليس الوحيد الذي يقدم هذا النوع من الخدمات. واحد من المنافسين الرئيسيين هو [GitLab](https://gitlab.com) . لمزيد من المعلومات حول هذا ، انظر إلى [المقال حول استضافة Git](https://guide.freecodecamp.org/git/git-hosting) . <ide>\ No newline at end of file <add>GitHub ليس الوحيد الذي يقدم هذا النوع من الخدمات. واحد من المنافسين الرئيسيين هو [GitLab](https://gitlab.com) . لمزيد من المعلومات حول هذا ، انظر إلى [المقال حول استضافة Git](https://guide.freecodecamp.org/git/git-hosting) . <ide><path>guide/arabic/git/git-push/index.md <ide> localeTitle: Git Push <ide> <ide> ### ادفع إلى فرع معين باستخدام معلمة القوة <ide> <del>إذا كنت ترغب في تجاهل التغييرات المحلية التي تم إجراؤها على مستودع Git في Github (الذي يفعله معظم المطورين للحصول على إصلاح سريع لخادم التطوير) ، يمكنك استخدام الأمر -force للدفع عن طريق تجاهل تلك التغييرات. <add>إذا كنت ترغب في تجاهل التغييرات المحلية التي تم إجراؤها على مستودع Git في GitHub (الذي يفعله معظم المطورين للحصول على إصلاح سريع لخادم التطوير) ، يمكنك استخدام الأمر -force للدفع عن طريق تجاهل تلك التغييرات. <ide> <ide> `git push --force <REMOTE-NAME> <BRANCH-NAME> <ide> ` <ide> localeTitle: Git Push <ide> ### معلومات اكثر: <ide> <ide> * [وثائق جيت - دفع](https://git-scm.com/docs/git-push) <del>* [git hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) <ide>\ No newline at end of file <add>* [git hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) <ide><path>guide/arabic/miscellaneous/creating-a-new-github-issue/index.md <ide> --- <del>title: Creating a New Github Issue <del>localeTitle: خلق إصدار جديد Github <add>title: Creating a New GitHub Issue <add>localeTitle: خلق إصدار جديد GitHub <ide> --- <del>قبل إرسال مشكلة ، حاول [البحث عن](https://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) مشكلتك [على Github](https://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) <add>قبل إرسال مشكلة ، حاول [البحث عن](https://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) مشكلتك [على GitHub](https://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) <ide> <ide> إن صياغة قضية جيدة سيجعل من الأسهل على فريق التطوير تكرار مشكلتك وحلها. اتبع هذه الخطوات للقيام بذلك بشكل صحيح: <ide> <ide> localeTitle: خلق إصدار جديد Github <ide> <ide> 6. **يمكنك التقاط لقطة شاشة** للمشكلة وتضمينها في المشاركة. <ide> <del>7. انقر فوق `Submit New Issue` وانت القيام به! سيتم الاشتراك تلقائيًا في الإشعارات لأي تحديثات أو تعليقات مستقبلية. <ide>\ No newline at end of file <add>7. انقر فوق `Submit New Issue` وانت القيام به! سيتم الاشتراك تلقائيًا في الإشعارات لأي تحديثات أو تعليقات مستقبلية. <ide><path>guide/arabic/miscellaneous/delete-a-git-branch-both-locally-and-remotely/index.md <ide> localeTitle: حذف فرع بوابة على حد سواء محليا وعن ب <ide> <ide> ## سير العمل حذف: <ide> <del>دعنا نقول لديك repo تسمى `AwesomeRepo` ، واستضافته على Github ، في موقع مثل `https://github.com/my_username/AwesomeRepo` . <add>دعنا نقول لديك repo تسمى `AwesomeRepo` ، واستضافته على GitHub ، في موقع مثل `https://github.com/my_username/AwesomeRepo` . <ide> <ide> دعونا أيضا نفترض أن لديها فروع مثل: <ide> `master` <ide> localeTitle: حذف فرع بوابة على حد سواء محليا وعن ب <ide> <ide> `git branch -D <branch>` . <ide> <del>على سبيل المثال: `git branch -D fix/authentication` <ide>\ No newline at end of file <add>على سبيل المثال: `git branch -D fix/authentication` <ide><path>guide/arabic/miscellaneous/deploying-to-openshift/index.md <ide> localeTitle: نشر إلى Openshift <ide> <ide> * املأ عنوان Git URL واسم فرعنا <ide> <del>![حيث يمكنك العثور على عنوان URL الخاص بـ Git واسم فرعك في Github](//discourse-user-assets.s3.amazonaws.com/original/2X/1/1a720934d9c2fd79a4aaa14b4ca07e6c1df7f2ce.jpg) <add>![حيث يمكنك العثور على عنوان URL الخاص بـ Git واسم فرعك في GitHub](//discourse-user-assets.s3.amazonaws.com/original/2X/1/1a720934d9c2fd79a4aaa14b4ca07e6c1df7f2ce.jpg) <ide> <ide> ![املأ عنوان URL الخاص بـ Git واسم الفرع الخاص بك](//discourse-user-assets.s3.amazonaws.com/original/2X/9/989e44c1af80c9b8f26883a3d897f377b3a27ca4.jpg) <ide> <ide> localeTitle: نشر إلى Openshift <ide> <ide> إذا وجدت طريقة أفضل لحل هذا القيد. لا تتردد في المساهمة في الويكي الخاص بنا ومشاركته معنا. <ide> <del>يمكنك التحقق من التطبيق يعمل على [http://voting-pitazo.rhcloud.com/#/polls](http://voting-pitazo.rhcloud.com/#/polls) <ide>\ No newline at end of file <add>يمكنك التحقق من التطبيق يعمل على [http://voting-pitazo.rhcloud.com/#/polls](http://voting-pitazo.rhcloud.com/#/polls) <ide><path>guide/arabic/miscellaneous/emojis-for-gitter-and-github/index.md <ide> --- <del>title: Emojis for Gitter and Github <del>localeTitle: Emojis للغيتر و Github <add>title: Emojis for Gitter and GitHub <add>localeTitle: Emojis للغيتر و GitHub <ide> --- <del>يدعم كل من Gitter IM و GitHub مجموعة من الرموز التعبيرية الرائعة (المشاعر). من `:sunny:` ![:sunny:](//forum.freecodecamp.com/images/emoji/emoji_one/sunny.png?v=2 ":مشمس:") إلى `:poop:` ![:poop:](//forum.freecodecamp.com/images/emoji/emoji_one/poop.png?v=2 ":براز الانسان:") يمكنك التعبير عن مجموعة من العواطف! <ide>\ No newline at end of file <add>يدعم كل من Gitter IM و GitHub مجموعة من الرموز التعبيرية الرائعة (المشاعر). من `:sunny:` ![:sunny:](//forum.freecodecamp.com/images/emoji/emoji_one/sunny.png?v=2 ":مشمس:") إلى `:poop:` ![:poop:](//forum.freecodecamp.com/images/emoji/emoji_one/poop.png?v=2 ":براز الانسان:") يمكنك التعبير عن مجموعة من العواطف! <ide><path>guide/arabic/miscellaneous/heroku-deployment-guide/index.md <ide> localeTitle: Heroku Deployment Guide <ide> <ide> 5. سيتم نقلك إلى لوحة التحكم لهذا التطبيق. انقر فوق علامة التبويب نشر. <ide> <del>6. هناك سيكون من دواعي سرورنا أن تجد أنه يمكنك الاتصال ريبو جيثوب. في قسم أسلوب النشر ، اختر Github والمصادقة عن طريق تسجيل الدخول إلى Github. <add>6. هناك سيكون من دواعي سرورنا أن تجد أنه يمكنك الاتصال ريبو جيثوب. في قسم أسلوب النشر ، اختر GitHub والمصادقة عن طريق تسجيل الدخول إلى GitHub. <ide> <ide> 7. أسفل ذلك مباشرةً ، املأ اسم ريبو جيثب الخاص بك. (وهذا يتطلب بالطبع أنك قمت بإعادة دفع الرصيد إلى github إما من cloud9 أو من جهازك المحلي ... وأنك قمت بتكوينه بشكل صحيح. المزيد على ذلك أدناه). <ide> <ide> localeTitle: Heroku Deployment Guide <ide> <ide> نصيحة: في ملف server.js ، تأكد من استخدام `app.listen(process.env.PORT || <default port>)` بحيث يعمل التطبيق على heroku. <ide> <del>العودة إلى الخطوة 7 أعلاه. <ide>\ No newline at end of file <add>العودة إلى الخطوة 7 أعلاه. <ide><path>guide/arabic/miscellaneous/how-to-fork-and-maintain-a-local-instance-of-free-code-camp-on-mac-and-linux/index.md <ide> Free Code Camp Issue Mods والموظفون متواجدون لمساعدتك <ide> ## إعداد النظام الخاص بك <ide> <ide> 1. قم بتثبيت [Git](https://git-scm.com/) أو عميل Git المفضل لديك <del>2. (اختياري) قم [بإعداد مفتاح SSH](https://help.github.com/articles/generating-ssh-keys/) لـ Github. <add>2. (اختياري) قم [بإعداد مفتاح SSH](https://help.github.com/articles/generating-ssh-keys/) لـ GitHub. <ide> يمكن أن يؤدي استخدام SSH إلى زيادة سرعة تفاعلك مع GitHub ، حيث لن تتم مطالبتك بكلمة المرور الخاصة بك. <ide> 3. قم بإنشاء دليل مشاريع رئيسية على نظامك. لأغراض هذه الوثيقة ، سنفترض أنها `/mean/` <ide> <ide> Free Code Camp Issue Mods والموظفون متواجدون لمساعدتك <ide> <ide> سيؤدي ذلك إلى الكتابة فوق فرع التدريج على شوكة الخاص بك. <ide> <del>`bash $ git push origin staging --force Counting objects: 99, done. Delta compression using up to 12 threads. Compressing objects: 100% (38/38), done. Writing objects: 100% (38/38), 16.14 KiB | 0 bytes/s, done. Total 38 (delta 25), reused 0 (delta 0) To git@github.com:yourUserName/FreeCodeCamp.git f7a525c..8a2271d staging -> staging` <ide>\ No newline at end of file <add>`bash $ git push origin staging --force Counting objects: 99, done. Delta compression using up to 12 threads. Compressing objects: 100% (38/38), done. Writing objects: 100% (38/38), 16.14 KiB | 0 bytes/s, done. Total 38 (delta 25), reused 0 (delta 0) To git@github.com:yourUserName/FreeCodeCamp.git f7a525c..8a2271d staging -> staging` <ide><path>guide/arabic/miscellaneous/how-to-get-help-on-gitter/index.md <ide> localeTitle: كيفية الحصول على مساعدة على جيتر <ide> * إذا كانت المشكلة تبدو مع الموقع نفسه ، فقم بنشر لقطة شاشة للمشكلة أو وصفها بشكل جيد. <ide> 2. تذكر أن الناس هناك معسكرين مثلك تمامًا ، لذا كن مهذبًا! <ide> <del>3. إذا حالت مشكلتك حيرة الجميع في Gitter ، فجرّب [البحث عن](http://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) مشكلتك [على Github](http://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) لأي شخص نشر موضوعًا مشابهًا. <ide>\ No newline at end of file <add>3. إذا حالت مشكلتك حيرة الجميع في Gitter ، فجرّب [البحث عن](http://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) مشكلتك [على GitHub](http://forum.freecodecamp.com/t/searching-for-existing-issues-in-github/18390) لأي شخص نشر موضوعًا مشابهًا. <ide><path>guide/arabic/miscellaneous/how-to-make-a-pull-request-on-free-code-camp/index.md <ide> $ git <ide> <ide> ## خطوات مشتركة <ide> <del>1. بمجرد أن يتم تنفيذ التعديلات ، ستتم مطالبتك بإنشاء طلب سحب على صفحة Github الخاصة بـ. <add>1. بمجرد أن يتم تنفيذ التعديلات ، ستتم مطالبتك بإنشاء طلب سحب على صفحة GitHub الخاصة بـ. <ide> 2. بشكل افتراضي ، يجب أن تكون جميع طلبات السحب ضد الريبو الرئيسي FCC ، الفرع `staging` . <ide> 3. اكتب عنوانًا واضحًا للعلاقات العامة الخاصة بك والتي تشير بإيجاز إلى ما يتم إصلاحه. لا تضيف رقم الإصدار في العنوان. أمثلة: `Add Test Cases to Algorithm Drop It` `Correct typo in Challenge Size Your Images` <ide> 4. في نصوص العلاقات العامة الخاصة بك ، قم بتضمين ملخص أكثر تفصيلاً للتغيرات التي قمت بها ولماذا. <ide> $ git <ide> <ide> ### إذا تم رفض PR الخاص بك <ide> <del>لا تيأس! يجب أن تتلقى تعليقات صلبة من المشرفين على القضايا لماذا تم رفضها وما هو مطلوب. من فضلك ، استمر في المساهمة. <ide>\ No newline at end of file <add>لا تيأس! يجب أن تتلقى تعليقات صلبة من المشرفين على القضايا لماذا تم رفضها وما هو مطلوب. من فضلك ، استمر في المساهمة. <ide><path>guide/arabic/miscellaneous/known-issues-with-codepen/index.md <ide> localeTitle: المشاكل المعروفة مع Codepen <ide> 3. **imgur hotlinking:** إذا كنت تستخدم الصور من [http://imgur.com](http://imgur.com) فإنها لن تظهر في معظم الوقت ، وهذا يرجع إلى TOS. طريقة لحل هذه المشكلة هي استخدام خدمة بديلة مثل [http://postimg.org](http://postimg.org) <ide> 4. **إعادة التحميل التلقائي:** بشكل افتراضي ، في كل مرة تقوم فيها بإجراء تغييرات في نوافذ محرر HTML أو JS ، يتم تحديث نافذة المعاينة. يمكنك إيقاف هذا وتمكين "زر التشغيل" ، من خلال الانتقال إلى الإعدادات> السلوك> "هل ترغب في تشغيل زر؟" وإلغاء تحديد المربع. <ide> 5. **location.reload:** إذا واجهت مشكلة في التعليمة البرمجية تعمل في طريقة عرض التصحيح أو في JSFiddle ، ولكن ليس في طريقة عرض محرر Codepen أو عرض الصفحة الكاملة ، تحقق مرة أخرى من استخدام `location.reload()` . إذا قمت بذلك ، يجب عليك إيجاد طريقة أخرى لتحقيق المطلوب ، لأن Codepen سيقوم بتجريد `location.reload` ويترك فقط `()` في التعليمات البرمجية. اقرأ المزيد [هنا:](https://blog.codepen.io/documentation/editor/things-we-strip/) <del>6. **عرض الصور ، إضافة ملفات css / js ، المستضافة على Github:** قد ترغب في تضمينها في ورقة أنماط مشروع Codepen ، أو ملف الصورة أو js المستضافة على Github. إذا قمت بإضافة ارتباط Github لملفك إلى إعداداتك في Codepen ، أو إلى html / css الخاص بك لن يعمل خارج المربع. ما عليك القيام به هو: <add>6. **عرض الصور ، إضافة ملفات css / js ، المستضافة على GitHub:** قد ترغب في تضمينها في ورقة أنماط مشروع Codepen ، أو ملف الصورة أو js المستضافة على GitHub. إذا قمت بإضافة ارتباط GitHub لملفك إلى إعداداتك في Codepen ، أو إلى html / css الخاص بك لن يعمل خارج المربع. ما عليك القيام به هو: <ide> 1. انتقل إلى الإصدار "الخام" من الملف <ide> 2. انسخ عنوان URL <ide> 3. قم بتغيير `raw.githubusercontent.com` إلى `rawgit.com` <del> 4. استخدم عنوان URL هذا للارتباط بملفات مستضافة على جيثب <ide>\ No newline at end of file <add> 4. استخدم عنوان URL هذا للارتباط بملفات مستضافة على جيثب <ide><path>guide/arabic/miscellaneous/learn-a-little-about-latex/index.md <ide> localeTitle: تعلم القليل عن اللاتكس <ide> <ide> ## تفاصيل <ide> <del>[KaTeX Github Repo](https://github.com/Khan/KaTeX) LaTeX هو نظام تنضيد عالي الجودة. يتضمن ميزات مصممة لإنتاج الوثائق التقنية والعلمية. LaTeX هو المعيار الواقعي للاتصال ونشر الوثائق العلمية. مزاياه ملحوظة في وثائق طويلة مثل الكتب والأوراق أو الأطروحة. <add>[KaTeX GitHub Repo](https://github.com/Khan/KaTeX) LaTeX هو نظام تنضيد عالي الجودة. يتضمن ميزات مصممة لإنتاج الوثائق التقنية والعلمية. LaTeX هو المعيار الواقعي للاتصال ونشر الوثائق العلمية. مزاياه ملحوظة في وثائق طويلة مثل الكتب والأوراق أو الأطروحة. <ide> <ide> يستخدم Gitter Katex (تنفيذ مخصص لـ LaTeX) ويمكن استخدامه لتقديم الكود التالي: <ide> <ide> localeTitle: تعلم القليل عن اللاتكس <ide> نص: <ide> <ide> * `$$\huge\textstyle{some text}$$` -> $$ \\ huge \\ textstyle {some text} $$ <del>* `$$\color{#F90}{some text}$$` -> $$ \\ color {# F90} {some text} $$ <ide>\ No newline at end of file <add>* `$$\color{#F90}{some text}$$` -> $$ \\ color {# F90} {some text} $$ <ide><path>guide/arabic/miscellaneous/learn-about-the-latex-language/index.md <ide> localeTitle: تعرف على لغة اللاتكس <ide> <ide> ## تفاصيل <ide> <del>[KaTeX Github Repo](https://github.com/Khan/KaTeX) LaTeX هو نظام تنضيد عالي الجودة. يتضمن ميزات مصممة لإنتاج الوثائق التقنية والعلمية. LaTeX هو المعيار الواقعي للاتصال ونشر الوثائق العلمية. مزاياه ملحوظة في وثائق طويلة مثل الكتب والأوراق أو الأطروحة. <add>[KaTeX GitHub Repo](https://github.com/Khan/KaTeX) LaTeX هو نظام تنضيد عالي الجودة. يتضمن ميزات مصممة لإنتاج الوثائق التقنية والعلمية. LaTeX هو المعيار الواقعي للاتصال ونشر الوثائق العلمية. مزاياه ملحوظة في وثائق طويلة مثل الكتب والأوراق أو الأطروحة. <ide> <ide> يستخدم Gitter Katex (تنفيذ مخصص لـ LaTeX) ويمكن استخدامه لتقديم الكود التالي: <ide> <ide> localeTitle: تعرف على لغة اللاتكس <ide> نص: <ide> <ide> * `$$\huge\textstyle{some text}$$` -> $$ \\ huge \\ textstyle {some text} $$ <del>* `$$\color{#F90}{some text}$$` -> $$ \\ color {# F90} {some text} $$ <ide>\ No newline at end of file <add>* `$$\color{#F90}{some text}$$` -> $$ \\ color {# F90} {some text} $$ <ide><path>guide/arabic/miscellaneous/linking-your-account-with-github/index.md <ide> --- <del>title: Linking Your Account with Github <add>title: Linking Your Account with GitHub <ide> localeTitle: ربط حسابك مع جيثب <ide> --- <ide> في آب 2015 ، قمنا بدفع بعض التغييرات التي تسببت في مشاكل للعديد من المعسكر. <ide> localeTitle: ربط حسابك مع جيثب <ide> 1) اخرج من حسابك الحالي وحاول تسجيل الدخول باستخدام GitHub. <ide> 2) تحقق من خريطة التحدي الخاص بك. يجب ألا يكون حسابك أي تقدم. احذف هذا الحساب هنا: [http://freecodecamp.com/account](http://freecodecamp.com/account) <ide> 3) تسجيل الدخول إلى Free Code Camp بالطريقة المعتادة (Facebook ، البريد الإلكتروني ، إلخ). يجب أن ترى تقدمك الأصلي. <del>3) الآن إضافة جيثب إلى هذا الحساب ، ويجب أن تكون كل مجموعة. <ide>\ No newline at end of file <add>3) الآن إضافة جيثب إلى هذا الحساب ، ويجب أن تكون كل مجموعة. <ide><path>guide/arabic/miscellaneous/searching-for-existing-issues-in-github/index.md <ide> --- <del>title: Searching for Existing Issues in Github <add>title: Searching for Existing Issues in GitHub <ide> localeTitle: البحث عن القضايا الحالية في جيثب <ide> --- <ide> إذا كنت لا تزال ترى مشكلات بعد الحصول على مساعدة على Gitter ، فستحتاج إلى محاولة معرفة ما إذا كان أي شخص آخر قد نشر عن مشكلة مماثلة. <ide> <ide> ![gif خلال الخطوات التالية للبحث عن GitHub لهذه المشكلة](//discourse-user-assets.s3.amazonaws.com/original/2X/3/3577718dd9fe14fbe80b203bc3cc56cdb0d9c3af.gif) <ide> <del>1. انتقل إلى صفحة [Github](https://github.com/FreeCodeCamp/FreeCodeCamp/issues) الخاصة بـ FreeCodeCamp's. <add>1. انتقل إلى صفحة [GitHub](https://github.com/FreeCodeCamp/FreeCodeCamp/issues) الخاصة بـ FreeCodeCamp's. <ide> <ide> 2. استخدم شريط البحث للبحث عن المشكلات التي تم حفظها بالفعل والتي قد تكون ذات صلة بمشكلتك. <ide> <ide> * إذا وجدت واحدة ، اقرأها! يمكنك الاشتراك للحصول على تحديثات حول هذه المشكلة المحددة من خلال النقر على `Subscribe` في الشريط الجانبي. يمكنك أيضًا التعليق على المشكلة إذا كان لديك شيء تريد إضافته. <ide> <del> * إذا لم تتمكن من العثور على أي قضايا ذات صلة ، ينبغي عليك إنشاء إصدار جديد من Gitub . <ide>\ No newline at end of file <add> * إذا لم تتمكن من العثور على أي قضايا ذات صلة ، ينبغي عليك إنشاء إصدار جديد من Gitub . <ide><path>guide/arabic/miscellaneous/searching-for-existing-issues/index.md <ide> localeTitle: البحث عن القضايا الحالية <ide> <ide> ![gif خلال الخطوات التالية للبحث عن GitHub لهذه المشكلة](//discourse-user-assets.s3.amazonaws.com/original/2X/3/3577718dd9fe14fbe80b203bc3cc56cdb0d9c3af.gif) <ide> <del>1. انتقل إلى صفحة [Github](https://github.com/FreeCodeCamp/FreeCodeCamp/issues) الخاصة بـ FreeCodeCamp's. <add>1. انتقل إلى صفحة [GitHub](https://github.com/FreeCodeCamp/FreeCodeCamp/issues) الخاصة بـ FreeCodeCamp's. <ide> <ide> 2. استخدم شريط البحث للبحث عن المشكلات التي تم حفظها بالفعل والتي قد تكون ذات صلة بمشكلتك. <ide> <ide> * إذا وجدت واحدة ، اقرأها! يمكنك الاشتراك للحصول على تحديثات حول هذه المشكلة المحددة من خلال النقر على `Subscribe` في الشريط الجانبي. يمكنك أيضًا التعليق على المشكلة إذا كان لديك شيء تريد إضافته. <ide> <del> * إذا لم تتمكن من العثور على أي قضايا ذات صلة ، ينبغي عليك [إنشاء إصدار جديد من Gitub](http://forum.freecodecamp.com/t/creating-a-new-github-issue/18392) . <ide>\ No newline at end of file <add> * إذا لم تتمكن من العثور على أي قضايا ذات صلة ، ينبغي عليك [إنشاء إصدار جديد من Gitub](http://forum.freecodecamp.com/t/creating-a-new-github-issue/18392) . <ide><path>guide/arabic/miscellaneous/the-history-of-ruby/index.md <ide> localeTitle: تاريخ روبي <ide> <ide> اليوم ، تعتبر روبي أون ريلز إطاراً متيناً للويب ؛ وقد رائدة الكثير من الممارسات العظيمة في تطوير الويب. <ide> <del>وبالمثل ، يتم ترميز العديد من [المواقع الشهيرة](https://prograils.com/posts/top-10-famous-sites-built-with-ruby-on-rails) في Ruby on Rails مثل Github و Airbnb و Groupon وغيرها. <add>وبالمثل ، يتم ترميز العديد من [المواقع الشهيرة](https://prograils.com/posts/top-10-famous-sites-built-with-ruby-on-rails) في Ruby on Rails مثل GitHub و Airbnb و Groupon وغيرها. <ide> <del>هناك العديد من [تطبيقات](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations) روبي. JRuby (Ruby on the JVM) ، و Ruby MRI (تسمى أيضاً CRuby) و IronRuby (Ruby for .NET و Silverlight) هي بعض من أشهرها. <ide>\ No newline at end of file <add>هناك العديد من [تطبيقات](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations) روبي. JRuby (Ruby on the JVM) ، و Ruby MRI (تسمى أيضاً CRuby) و IronRuby (Ruby for .NET و Silverlight) هي بعض من أشهرها. <ide><path>guide/arabic/miscellaneous/use-github-static-pages-to-host-your-front-end-projects/index.md <ide> --- <del>title: Use Github Static Pages to Host Your Front End Projects <add>title: Use GitHub Static Pages to Host Your Front End Projects <ide> localeTitle: استخدم Gitub Static Pages لاستضافة مشاريع الواجهة الأمامية <ide> --- <ide> **فوائد** <ide> localeTitle: استخدم Gitub Static Pages لاستضافة مشاريع ال <ide> <ide> ## جيت إلى جيثب <ide> <del>نظرًا لأنني حفظ بالفعل محليًا ، وباستخدام git للتحكم في الإصدار ، فقد أحسست أيضًا بتحميله إلى Github. بالإضافة إلى ذلك ، لدى Github خدمة رائعة مجانية لمشاريع الواجهة الأمامية التي تسمى [Github Pages](https://pages.github.com/) . مجرد تحديث الريبو الخاص بك والتغييرات الخاصة بك على الهواء مباشرة. <add>نظرًا لأنني حفظ بالفعل محليًا ، وباستخدام git للتحكم في الإصدار ، فقد أحسست أيضًا بتحميله إلى GitHub. بالإضافة إلى ذلك ، لدى GitHub خدمة رائعة مجانية لمشاريع الواجهة الأمامية التي تسمى [GitHub Pages](https://pages.github.com/) . مجرد تحديث الريبو الخاص بك والتغييرات الخاصة بك على الهواء مباشرة. <ide> <del>كيف يعمل بسيط. يتحقق Github مما إذا كان لدى المستودع فرع يسمى `gh-pages` ويخدم أي رمز يجلس في هذا الفرع. لا توجد أشياء خلفية هنا ، ولكن HTML و CSS و JS تعمل مثل السحر. <add>كيف يعمل بسيط. يتحقق GitHub مما إذا كان لدى المستودع فرع يسمى `gh-pages` ويخدم أي رمز يجلس في هذا الفرع. لا توجد أشياء خلفية هنا ، ولكن HTML و CSS و JS تعمل مثل السحر. <ide> <ide> ## اهم الاشياء اولا <ide> <ide> localeTitle: استخدم Gitub Static Pages لاستضافة مشاريع ال <ide> <ide> الترميز سعيدة! <ide> <del>PS. بفضل [هذا الدليل من](http://rogerdudler.github.io/git-guide/) قبل روجر دادلر للحفاظ على الأمور بسيطة. <ide>\ No newline at end of file <add>PS. بفضل [هذا الدليل من](http://rogerdudler.github.io/git-guide/) قبل روجر دادلر للحفاظ على الأمور بسيطة. <ide><path>guide/arabic/miscellaneous/wiki-git-resources/index.md <ide> Git هو نظام تحكم في إصدار الموزعة مجاني ومفتو <ide> * [Git In The Trenches](http://cbx33.github.io/gitt/) - Git In The Trenches ، أو GITT تم تصميمه ليكون كتابًا يركز على تعليم الناس استخدام Git من خلال ربطه بالسيناريوهات التي تواجهها شركة خيالية تسمى Tamagoyaki Inc. تنزيل هذا الكتاب بتنسيق PDF أو mobi أو شكل ePub مجانا. <ide> * [البرنامج التعليمي الرسمي لـ Git](https://git-scm.com/docs/gittutorial) - يشرح هذا البرنامج التعليمي كيفية استيراد مشروع جديد إلى Git وإجراء تغييرات عليه ومشاركة التغييرات مع مطورين آخرين. <ide> * [دليل مستخدم Git الرسمي](https://git-scm.com/docs/user-manual.html) - تم تصميم هذا الدليل ليصبح قابلاً للقراءة من قبل شخص لديه مهارات سطر الأوامر الأساسية لـ UNIX ، ولكن ليس لديه معرفة سابقة بـ Git. <del>* [جرّب Git Tutorial by Github و CodeSchool](https://try.github.io) - هذا البرنامج التعليمي عبارة عن سرعة سريعة مدتها 15 دقيقة للبدء مع Git في المتصفح. <add>* [جرّب Git Tutorial by GitHub و CodeSchool](https://try.github.io) - هذا البرنامج التعليمي عبارة عن سرعة سريعة مدتها 15 دقيقة للبدء مع Git في المتصفح. <ide> <ide> ## موارد آخرى <ide> <ide> * [Git Ready](http://gitready.com) - 'Learn git one commit at a time' by Nick Quaranto <del>* [Hub](https://hub.github.com/) - Hub عبارة عن غلاف سطر أوامر لـ git يجعلك أفضل في GitHub. <ide>\ No newline at end of file <add>* [Hub](https://hub.github.com/) - Hub عبارة عن غلاف سطر أوامر لـ git يجعلك أفضل في GitHub. <ide><path>guide/arabic/miscellaneous/writing-a-markdown-file-for-github-using-atom/index.md <ide> --- <del>title: Writing a Markdown File for Github Using Atom <del>localeTitle: كتابة ملف Markdown ل Github باستخدام Atom <add>title: Writing a Markdown File for GitHub Using Atom <add>localeTitle: كتابة ملف Markdown ل GitHub باستخدام Atom <ide> --- <ide> يمثل Markdown طريقة لتصميم النص على الويب ، ويستفيد مستخدمو GitHub من الترقيم لتوفير الوثائق لمستودعاتهم. <ide> <ide> localeTitle: كتابة ملف Markdown ل Github باستخدام Atom <ide> <ide> لإضافة مشروع أو ملفات إلى GitHub ، انتقل إلى [هذه الصفحة](https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/) . <ide> <del>**خطوة إضافية:** تحتوي Atom على حزمة باسم [Markdown Preview Plus](https://atom.io/packages/markdown-preview-plus) . وهو يفعل نفس طريقة المعاينة العادية للضغط ، ولكن يتم تصميم ملف المعاينة بشكل أكثر دقة على نمط GitHub. المضي قدما وتثبيت هذه الحزمة ونرى ما تحصل عليه. <ide>\ No newline at end of file <add>**خطوة إضافية:** تحتوي Atom على حزمة باسم [Markdown Preview Plus](https://atom.io/packages/markdown-preview-plus) . وهو يفعل نفس طريقة المعاينة العادية للضغط ، ولكن يتم تصميم ملف المعاينة بشكل أكثر دقة على نمط GitHub. المضي قدما وتثبيت هذه الحزمة ونرى ما تحصل عليه. <ide><path>guide/arabic/redux/redux-thunk/index.md <ide> Redux Thunk هي برامج وسيطة تسمح لك بإعادة الوظائف <ide> <ide> ### المراجع <ide> <del>* [Redux Thunk Github Repo](https://github.com/reduxjs/redux-thunk) <add>* [Redux Thunk GitHub Repo](https://github.com/reduxjs/redux-thunk) <ide> * [Redux الوسيطة](https://redux.js.org/advanced/middleware) <ide> <ide> ### مصادر <ide> <del>1. [مثال عداد الزيادة المستشهد به من وثائق Redux Thunk ، بتاريخ 10/02/2018](#https://github.com/reduxjs/redux-thunk) <ide>\ No newline at end of file <add>1. [مثال عداد الزيادة المستشهد به من وثائق Redux Thunk ، بتاريخ 10/02/2018](#https://github.com/reduxjs/redux-thunk) <ide><path>guide/arabic/ruby/index.md <ide> IRB لتقف على التفاعلية روبي شل. الاختصار irb يأ <ide> <ide> ## ماذا بعد تعلم روبي؟ <ide> <del>كل لغة برمجة تلعب دور imporatnt. يمكنك المساهمة في الكثير من المشاريع المفتوحة المصدر أو يمكنك التقدم بطلب للحصول على بعض الشركات الكبرى بعد أن يكون لديك فهم جيد على روبي. كما العديد من مواقع الإنترنت الكبيرة مثل Basecamp، Airbnb، Bleacher Report، Fab.com، Scribd، Groupon، Gumroad، Hulu، Kickstarter، Pitchfork، Sendgrid، Soundcloud، Square، Yammer، Crunchbase، Slideshare، Funny or Die، Zendesk، Github، بنيت Shopify على روبي لذلك ، هناك الكثير من الخيارات بالنسبة لك هناك. علاوة على ذلك ، هناك الكثير من الشركات الناشئة التي تستعين بأشخاص لديهم مهارات في RUby on Rails حيث لا يحاول الكثير من المبرمجين تعلم روبي. لذلك ، قد يكون لديك خفض واضح للعمل في شركة ناشئة. لذلك ، روبي هو المبتدئين ودية ومهارة صعبة للغاية للعثور على عدد جيد من الفتحات للعمل كمطور. <ide>\ No newline at end of file <add>كل لغة برمجة تلعب دور imporatnt. يمكنك المساهمة في الكثير من المشاريع المفتوحة المصدر أو يمكنك التقدم بطلب للحصول على بعض الشركات الكبرى بعد أن يكون لديك فهم جيد على روبي. كما العديد من مواقع الإنترنت الكبيرة مثل Basecamp، Airbnb، Bleacher Report، Fab.com، Scribd، Groupon، Gumroad، Hulu، Kickstarter، Pitchfork، Sendgrid، Soundcloud، Square، Yammer، Crunchbase، Slideshare، Funny or Die، Zendesk، GitHub، بنيت Shopify على روبي لذلك ، هناك الكثير من الخيارات بالنسبة لك هناك. علاوة على ذلك ، هناك الكثير من الشركات الناشئة التي تستعين بأشخاص لديهم مهارات في RUby on Rails حيث لا يحاول الكثير من المبرمجين تعلم روبي. لذلك ، قد يكون لديك خفض واضح للعمل في شركة ناشئة. لذلك ، روبي هو المبتدئين ودية ومهارة صعبة للغاية للعثور على عدد جيد من الفتحات للعمل كمطور.
24
PHP
PHP
apply fixes from styleci
0d18dc3d41d3a3dc48f5bceabed1dbe45d9597ac
<ide><path>tests/Integration/Console/ConsoleApplicationTest.php <ide> public function test_artisan_call_using_command_class() <ide> $this->assertEquals($exitCode, 0); <ide> } <ide> <del> /** <add> /* <ide> * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException <ide> */ <ide> // public function test_artisan_call_invalid_command_name()
1
Javascript
Javascript
flatten text children before rendering
0934ab948ded53f0509ed1914fbcb834e3cf48d1
<ide><path>src/renderers/art/ReactARTFiber.js <ide> function applyShapeProps(instance, props, prevProps = {}) { <ide> function applyTextProps(instance, props, prevProps = {}) { <ide> applyRenderableNodeProps(instance, props, prevProps); <ide> <del> const string = childrenAsString(props.children); <add> const string = props.children; <ide> <ide> if ( <ide> instance._currentString !== string || <ide> const ARTRenderer = ReactFiberReconciler({ <ide> appendInitialChild(parentInstance, child) { <ide> if (typeof child === 'string') { <ide> // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>) <add> invariant(false, 'Text children should already be flattened.'); <ide> return; <ide> } <ide> <ide> const ARTRenderer = ReactFiberReconciler({ <ide> break; <ide> case TYPES.TEXT: <ide> instance = Mode.Text( <del> childrenAsString(props.children), <add> props.children, <ide> props.font, <ide> props.alignment, <ide> props.path, <ide> module.exports = { <ide> RadialGradient, <ide> Shape: TYPES.SHAPE, <ide> Surface, <del> Text: TYPES.TEXT, <add> Text: function Text(props) { <add> // TODO: This means you can't have children that render into strings. <add> const T = TYPES.TEXT; <add> return <T {...props}>{childrenAsString(props.children)}</T>; <add> }, <ide> Transform, <ide> };
1
Python
Python
clarify elasticsearchtaskhandler docstring
d8c4449a91b9b93691c03e1af45bdedc5e23fd5e
<ide><path>airflow/providers/elasticsearch/log/es_task_handler.py <ide> class ElasticsearchTaskHandler(FileTaskHandler, ExternalLoggingMixin, LoggingMixin): <ide> """ <ide> ElasticsearchTaskHandler is a python log handler that <del> reads logs from Elasticsearch. Note logs are not directly <del> indexed into Elasticsearch. Instead, it flushes logs <add> reads logs from Elasticsearch. Note that Airflow does not handle the indexing <add> of logs into Elasticsearch. Instead, Airflow flushes logs <ide> into local files. Additional software setup is required <del> to index the log into Elasticsearch, such as using <add> to index the logs into Elasticsearch, such as using <ide> Filebeat and Logstash. <del> To efficiently query and sort Elasticsearch results, we assume each <add> To efficiently query and sort Elasticsearch results, this handler assumes each <ide> log message has a field `log_id` consists of ti primary keys: <ide> `log_id = {dag_id}-{task_id}-{execution_date}-{try_number}` <ide> Log messages with specific log_id are sorted based on `offset`, <ide> which is a unique integer indicates log message's order. <del> Timestamp here are unreliable because multiple log messages <add> Timestamps here are unreliable because multiple log messages <ide> might have the same timestamp. <ide> """ <ide>
1
Python
Python
set version to v2.1.0a7.dev9
22923b9cb1ffca740218c5f9f2b0d922bed062c7
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a7" <add>__version__ = "2.1.0a7.dev9" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI" <ide> __email__ = "contact@explosion.ai" <ide> __license__ = "MIT" <del>__release__ = True <add>__release__ = False <ide> <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Go
Go
enforce login for push/pull
e02f7912bcc07dbddd47bcf0106ca881fd768559
<ide><path>commands.go <ide> func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <del> if cmd.NArg() == 0 { <add> if cmd.NArg() == 0 || *user == "" { <ide> cmd.Usage() <ide> return nil <ide> } <ide> <add> if srv.runtime.authConfig == nil { <add> return fmt.Errorf("Please login prior to push. ('docker login')") <add> } <add> <ide> // Try to get the image <ide> // FIXME: Handle lookup <ide> // FIXME: Also push the tags in case of ./docker push myrepo:mytag <ide> // img, err := srv.runtime.LookupImage(cmd.Arg(0)) <ide> img, err := srv.runtime.graph.Get(cmd.Arg(0)) <ide> if err != nil { <del> if *user == "" { <del> return fmt.Errorf("Not logged in and no user specified\n") <del> } <ide> // If it fails, try to get the repository <ide> if repo, exists := srv.runtime.repositories.Repositories[cmd.Arg(0)]; exists { <ide> fmt.Fprintf(stdout, "Pushing %s (%d images) on %s...\n", cmd.Arg(0), len(repo), *user+"/"+cmd.Arg(0)) <ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <del> if cmd.NArg() == 0 { <add> if cmd.NArg() == 0 || *user == "" { <ide> cmd.Usage() <ide> return nil <ide> } <ide> <add> if srv.runtime.authConfig == nil { <add> return fmt.Errorf("Please login prior to push. ('docker login')") <add> } <add> <ide> if srv.runtime.graph.LookupRemoteImage(cmd.Arg(0), srv.runtime.authConfig) { <ide> fmt.Fprintf(stdout, "Pulling %s...\n", cmd.Arg(0)) <ide> if err := srv.runtime.graph.PullImage(cmd.Arg(0), srv.runtime.authConfig); err != nil { <ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string <ide> fmt.Fprintf(stdout, "Pulled\n") <ide> return nil <ide> } <del> if *user == "" { <del> return fmt.Errorf("Not loggin and no user specified\n") <del> } <ide> // FIXME: Allow pull repo:tag <ide> fmt.Fprintf(stdout, "Pulling %s from %s...\n", cmd.Arg(0), *user+"/"+cmd.Arg(0)) <ide> if err := srv.runtime.graph.PullRepository(*user, cmd.Arg(0), "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
1
Ruby
Ruby
add unit tests
a06bd4e45df2a98a05e6752d7a662807176b3a77
<ide><path>Library/Homebrew/test/version/parser_spec.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "version/parser" <add> <add>describe Version::Parser do <add> specify "::new" do <add> expect { described_class.new } <add> .to raise_error("Version::Parser is declared as abstract; it cannot be instantiated") <add> end <add> <add> describe Version::RegexParser do <add> specify "::new" do <add> # TODO: see https://github.com/sorbet/sorbet/issues/2374 <add> # expect { described_class.new(/[._-](\d+(?:\.\d+)+)/) } <add> # .to raise_error("Version::RegexParser is declared as abstract; it cannot be instantiated") <add> expect { described_class.new(/[._-](\d+(?:\.\d+)+)/) }.not_to raise_error <add> end <add> <add> specify "::process_spec" do <add> expect { described_class.process_spec(Pathname(TEST_TMPDIR)) } <add> .to raise_error("The method `process_spec` on #<Class:Version::RegexParser> is declared as `abstract`. " \ <add> "It does not have an implementation.") <add> end <add> end <add> <add> describe Version::UrlParser do <add> specify "::new" do <add> expect { described_class.new(/[._-](\d+(?:\.\d+)+)/) }.not_to raise_error <add> end <add> <add> specify "::process_spec" do <add> expect(described_class.process_spec(Pathname("#{TEST_TMPDIR}/testdir-0.1.test"))) <add> .to eq("#{TEST_TMPDIR}/testdir-0.1.test") <add> <add> expect(described_class.process_spec(Pathname("https://sourceforge.net/foo_bar-1.21.tar.gz/download"))) <add> .to eq("https://sourceforge.net/foo_bar-1.21.tar.gz/download") <add> <add> expect(described_class.process_spec(Pathname("https://sf.net/foo_bar-1.21.tar.gz/download"))) <add> .to eq("https://sf.net/foo_bar-1.21.tar.gz/download") <add> <add> expect(described_class.process_spec(Pathname("https://brew.sh/testball-0.1"))) <add> .to eq("https://brew.sh/testball-0.1") <add> <add> expect(described_class.process_spec(Pathname("https://brew.sh/testball-0.1.tgz"))) <add> .to eq("https://brew.sh/testball-0.1.tgz") <add> end <add> end <add> <add> describe Version::StemParser do <add> before { Pathname("#{TEST_TMPDIR}/testdir-0.1.test").mkpath } <add> <add> after { Pathname("#{TEST_TMPDIR}/testdir-0.1.test").unlink } <add> <add> specify "::new" do <add> expect { described_class.new(/[._-](\d+(?:\.\d+)+)/) }.not_to raise_error <add> end <add> <add> describe "::process_spec" do <add> it "works with directories" do <add> expect(described_class.process_spec(Pathname("#{TEST_TMPDIR}/testdir-0.1.test"))).to eq("testdir-0.1.test") <add> end <add> <add> it "works with SourceForge URLs with /download suffix" do <add> expect(described_class.process_spec(Pathname("https://sourceforge.net/foo_bar-1.21.tar.gz/download"))) <add> .to eq("foo_bar-1.21") <add> <add> expect(described_class.process_spec(Pathname("https://sf.net/foo_bar-1.21.tar.gz/download"))) <add> .to eq("foo_bar-1.21") <add> end <add> <add> it "works with URLs without file extension" do <add> expect(described_class.process_spec(Pathname("https://brew.sh/testball-0.1"))).to eq("testball-0.1") <add> end <add> <add> it "works with URLs with file extension" do <add> expect(described_class.process_spec(Pathname("https://brew.sh/testball-0.1.tgz"))).to eq("testball-0.1") <add> end <add> end <add> end <add>end <ide><path>Library/Homebrew/version/parser.rb <ide> def initialize(regex, &block) <ide> <ide> sig { override.params(spec: Pathname).returns(T.nilable(String)) } <ide> def parse(spec) <del> match = @regex.match(process_spec(spec)) <add> match = @regex.match(self.class.process_spec(spec)) <ide> return if match.blank? <ide> <ide> version = match.captures.first <ide> def parse(spec) <ide> end <ide> <ide> sig { abstract.params(spec: Pathname).returns(String) } <del> def process_spec(spec); end <add> def self.process_spec(spec); end <ide> end <ide> <ide> # @api private <ide> class UrlParser < RegexParser <ide> extend T::Sig <ide> <ide> sig { override.params(spec: Pathname).returns(String) } <del> def process_spec(spec) <add> def self.process_spec(spec) <ide> spec.to_s <ide> end <ide> end <ide> def process_spec(spec) <ide> class StemParser < RegexParser <ide> extend T::Sig <ide> <del> SOURCEFORGE_DOWNLOAD_REGEX = %r{((?:sourceforge\.net|sf\.net)/.*)/download$}.freeze <add> SOURCEFORGE_DOWNLOAD_REGEX = %r{(?:sourceforge\.net|sf\.net)/.*/download$}.freeze <ide> NO_FILE_EXTENSION_REGEX = /\.[^a-zA-Z]+$/.freeze <ide> <ide> sig { override.params(spec: Pathname).returns(String) } <del> def process_spec(spec) <add> def self.process_spec(spec) <ide> return spec.basename.to_s if spec.directory? <ide> <ide> spec_s = spec.to_s
2
Text
Text
fix distinct example [skip ci]
5a5170a8d2a1444ace4d7d4346516a84b4fd4ef9
<ide><path>README.md <ide> The `OR` operator works like this: <ide> users.where(users[:name].eq('bob').or(users[:age].lt(25))) <ide> ``` <ide> <del>The `AND` operator behaves similarly. The exception is the `DISTINCT` operator, which is not chainable: <add>The `AND` operator behaves similarly. Here is an example of the `DISTINCT` operator, which as of v6 is also chainable: <ide> <del>``` <add>```ruby <ide> posts = Arel::Table.new(:posts) <ide> posts.project(posts[:title]) <ide> posts.distinct
1
Javascript
Javascript
respect the 'readable' flag on sockets
2789323902a745eea16c645e38d9d67b6fcb69a0
<ide><path>lib/net.js <ide> util.inherits(Socket, stream.Duplex); <ide> // so that only the writable side will be cleaned up. <ide> function onSocketFinish() { <ide> debug('onSocketFinish'); <del> if (this._readableState.ended) { <add> if (!this.readable || this._readableState.ended) { <ide> debug('oSF: ended, destroy', this._readableState); <ide> return this.destroy(); <ide> } <ide> Socket.prototype.end = function(data, encoding) { <ide> DTRACE_NET_STREAM_END(this); <ide> <ide> // just in case we're waiting for an EOF. <del> if (!this._readableState.endEmitted) <add> if (this.readable && !this._readableState.endEmitted) <ide> this.read(0); <ide> return; <ide> }; <ide><path>test/simple/test-stdout-cannot-be-closed-child-process-pipe.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>if (process.argv[2] === 'child') <add> process.stdout.end('foo'); <add>else <add> parent(); <add> <add>function parent() { <add> var spawn = require('child_process').spawn; <add> var child = spawn(process.execPath, [__filename, 'child']); <add> var out = ''; <add> var err = ''; <add> <add> child.stdout.setEncoding('utf8'); <add> child.stderr.setEncoding('utf8'); <add> <add> child.stdout.on('data', function(c) { <add> out += c; <add> }); <add> child.stderr.on('data', function(c) { <add> err += c; <add> }); <add> <add> child.on('close', function(code, signal) { <add> assert(code); <add> assert.equal(out, 'foo'); <add> assert(/process\.stdout cannot be closed/.test(err)); <add> console.log('ok'); <add> }); <add>}
2
Python
Python
remove unused update_shared argument
dc3a623d0008c1362a2f26369f777b5ceef8958b
<ide><path>spacy/cli/train.py <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> for batch in minibatch(train_docs, size=batch_sizes): <ide> docs, golds = zip(*batch) <ide> nlp.update(docs, golds, sgd=optimizer, <del> drop=next(dropout_rates), losses=losses, <del> update_shared=True) <add> drop=next(dropout_rates), losses=losses) <ide> pbar.update(sum(len(doc) for doc in docs)) <ide> <ide> with nlp.use_params(optimizer.averages):
1
Ruby
Ruby
add pkgetc method
8e318d81bcbf88d1829cdfba8c390f553c8787a1
<ide><path>Library/Homebrew/formula.rb <ide> def etc <ide> (HOMEBREW_PREFIX/"etc").extend(InstallRenamed) <ide> end <ide> <add> # A subdirectory of `etc` with the formula name suffixed. <add> # e.g. `$HOMEBREW_PREFIX/etc/openssl@1.1` <add> # Anything using `pkgetc.install` will not overwrite other files on <add> # e.g. upgrades but will write a new file named `*.default`. <add> def pkgetc <add> (HOMEBREW_PREFIX/"etc"/name).extend(InstallRenamed) <add> end <add> <ide> # The directory where the formula's variable files should be installed. <ide> # This directory is not inside the `HOMEBREW_CELLAR` so it persists <ide> # across upgrades. <ide> def link_overwrite?(path) <ide> # keg's formula is deleted. <ide> begin <ide> keg = Keg.for(path) <del> rescue NotAKegError, Errno::ENOENT # rubocop:disable Lint/SuppressedException <add> rescue NotAKegError, Errno::ENOENT <ide> # file doesn't belong to any keg. <ide> else <ide> tab_tap = Tab.for_keg(keg).tap <ide> def link_overwrite?(path) <ide> <ide> begin <ide> Formulary.factory(keg.name) <del> rescue FormulaUnavailableError # rubocop:disable Lint/SuppressedException <add> rescue FormulaUnavailableError <ide> # formula for this keg is deleted, so defer to whitelist <ide> rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError <ide> return false # this keg belongs to another formula
1
Go
Go
fix the 'repositories' file
ac392bc0d775455f71da3c71956f9f6ae7a87f6d
<ide><path>server/server.go <ide> func (srv *Server) ImageExport(job *engine.Job) engine.Status { <ide> <ide> utils.Debugf("Serializing %s", name) <ide> <add> rootRepoMap := map[string]graph.Repository{} <ide> rootRepo, err := srv.daemon.Repositories().Get(name) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> if rootRepo != nil { <add> // this is a base repo name, like 'busybox' <add> <ide> for _, id := range rootRepo { <ide> if err := srv.exportImage(job.Eng, id, tempdir); err != nil { <ide> return job.Error(err) <ide> } <ide> } <del> <del> // write repositories <del> rootRepoMap := map[string]graph.Repository{} <ide> rootRepoMap[name] = rootRepo <add> } else { <add> img, err := srv.daemon.Repositories().LookupImage(name) <add> if err != nil { <add> return job.Error(err) <add> } <add> if img != nil { <add> // This is a named image like 'busybox:latest' <add> repoName, repoTag := utils.ParseRepositoryTag(name) <add> if err := srv.exportImage(job.Eng, img.ID, tempdir); err != nil { <add> return job.Error(err) <add> } <add> // check this length, because a lookup of a truncated has will not have a tag <add> // and will not need to be added to this map <add> if len(repoTag) > 0 { <add> rootRepoMap[repoName] = graph.Repository{repoTag: img.ID} <add> } <add> } else { <add> // this must be an ID that didn't get looked up just right? <add> if err := srv.exportImage(job.Eng, name, tempdir); err != nil { <add> return job.Error(err) <add> } <add> } <add> } <add> // write repositories, if there is something to write <add> if len(rootRepoMap) > 0 { <ide> rootRepoJson, _ := json.Marshal(rootRepoMap) <ide> <ide> if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.FileMode(0644)); err != nil { <ide> return job.Error(err) <ide> } <ide> } else { <del> if err := srv.exportImage(job.Eng, name, tempdir); err != nil { <del> return job.Error(err) <del> } <add> utils.Debugf("There were no repositories to write") <ide> } <ide> <ide> fs, err := archive.Tar(tempdir, archive.Uncompressed)
1
Python
Python
set the so_reuseaddr option on the socket
9d345f583631709cfdd38b77d2947ec74d83a562
<ide><path>celery/contrib/rdb.py <ide> def get_avail_port(self, host, port, search_limit=100, skew=+0): <ide> this_port = None <ide> for i in range(search_limit): <ide> _sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <add> _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <ide> this_port = port + skew + i <ide> try: <ide> _sock.bind((host, this_port))
1
Text
Text
add note about running the tests
6f509917f5af51fb50a297f7dfdfe30954979ee4
<ide><path>README.md <ide> Next, from the root directory of this repository, install D3's dependencies: <ide> <ide> You can see the list of dependencies in package.json. NPM will install the <ide> packages in the node_modules directory. <add> <add>To run the tests, use: <add> <add> make test
1