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 |
|---|---|---|---|---|---|
Python | Python | leave status responsibility to parent class | ebcc78d96cf6f4cd6e464cd6b8eccd83305900c2 | <ide><path>rest_framework/response.py
<ide> class Response(SimpleTemplateResponse):
<ide> if django.VERSION >= (1, 4):
<ide> rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_closable_objects']
<ide>
<del> def __init__(self, data=None, status=200,
<add> def __init__(self, data=None, status=None,
<ide> template_name=None, headers=None,
<ide> exception=False, content_type=None):
<ide> """ | 1 |
Text | Text | fix misleading sentence in http.md | 1706a2d7d82cf4daabb1e8e44ed43ed61befb342 | <ide><path>doc/api/http.md
<ide> This method signals to the server that all of the response headers and body
<ide> have been sent; that server should consider this message complete.
<ide> The method, `response.end()`, MUST be called on each response.
<ide>
<del>If `data` is specified, it is equivalent to calling
<add>If `data` is specified, it is similar in effect to calling
<ide> [`response.write(data, encoding)`][] followed by `response.end(callback)`.
<ide>
<ide> If `callback` is specified, it will be called when the response stream | 1 |
Text | Text | add missing link href | 8ca0eca4c8a458efa0438368590e63ace7f11ce9 | <ide><path>docs/how-to-work-on-guide-articles.md
<ide> With your help, we can create a comprehensive reference tool that will help mill
<ide> You can:
<ide>
<ide> - [Help us by Creating and Editing Guide Articles](#steps-for-creating-and-editing-guide-articles).
<del>- [Help us by reviewing pull requests for Guide Articles]()
<add>- [Help us reviewing pull requests for Guide Articles](#steps-for-reviewing-pull-requests-for-guide-articles)
<ide>
<ide> ## Steps for Creating and Editing Guide Articles
<ide> | 1 |
Javascript | Javascript | fix broken aria menu | b7cb9d06d6875790b869fd751b675ab2d78f492f | <ide><path>src/js/menu/menu-button.js
<ide> class MenuButton extends Component {
<ide>
<ide> if (this.items && this.items.length <= this.hideThreshold_) {
<ide> this.hide();
<add> this.menu.contentEl_.removeAttribute('role');
<add>
<ide> } else {
<ide> this.show();
<add> this.menu.contentEl_.setAttribute('role', 'menu');
<ide> }
<ide> }
<ide>
<ide><path>test/unit/menu.test.js
<ide> QUnit.test('should keep all the added menu items', function(assert) {
<ide> MenuButton.prototype.createItems = oldCreateItems;
<ide> });
<ide>
<add>QUnit.test('should add or remove role menu for accessibility purpose', function(assert) {
<add> const player = TestHelpers.makePlayer();
<add> const menuButton = new MenuButton(player);
<add>
<add> menuButton.createItems = () => [];
<add> menuButton.update();
<add> assert.equal(menuButton.menu.contentEl_.hasAttribute('role'), false, 'the menu does not have a role attribute when it contains no menu items');
<add>
<add> menuButton.createItems = () => [new MenuItem(player, { label: 'menu-item' })];
<add> menuButton.update();
<add> assert.equal(menuButton.menu.contentEl_.hasAttribute('role'), true, 'the menu has a role attribute when it contains menu items');
<add> assert.strictEqual(menuButton.menu.contentEl_.getAttribute('role'), 'menu', 'the menu role is `menu`');
<add>
<add> menuButton.dispose();
<add> player.dispose();
<add>});
<add>
<ide> QUnit.test('should remove old event listeners when the menu item adds to the new menu', function(assert) {
<ide> const player = TestHelpers.makePlayer();
<ide> const menuButton = new MenuButton(player, {}); | 2 |
Java | Java | serialize full pattern objects | 9306d6dbaabe21f50000406a3db982756297bce5 | <ide><path>org.springframework.aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java
<ide> /*
<del> * Copyright 2002-2008 the original author or authors.
<add> * Copyright 2002-2009 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 abstract class AbstractRegexpMethodPointcut extends StaticMethodMatcherPo
<ide> /** Regular expressions to match */
<ide> private String[] patterns = new String[0];
<ide>
<del> /** Regaular expressions <strong>not</strong> to match */
<add> /** Regular expressions <strong>not</strong> to match */
<ide> private String[] excludedPatterns = new String[0];
<ide>
<ide>
<ide> protected boolean matchesPattern(String signatureString) {
<ide> /**
<ide> * Subclasses must implement this to initialize regexp pointcuts.
<ide> * Can be invoked multiple times.
<del> * <p>This method will be invoked from the setPatterns method,
<add> * <p>This method will be invoked from the {@link #setPatterns} method,
<ide> * and also on deserialization.
<ide> * @param patterns the patterns to initialize
<ide> * @throws IllegalArgumentException in case of an invalid pattern
<ide> */
<ide> protected abstract void initPatternRepresentation(String[] patterns) throws IllegalArgumentException;
<ide>
<del> protected abstract void initExcludedPatternRepresentation(String[] excludedPatterns) throws IllegalArgumentException;
<add> /**
<add> * Subclasses must implement this to initialize regexp pointcuts.
<add> * Can be invoked multiple times.
<add> * <p>This method will be invoked from the {@link #setExcludedPatterns} method,
<add> * and also on deserialization.
<add> * @param patterns the patterns to initialize
<add> * @throws IllegalArgumentException in case of an invalid pattern
<add> */
<add> protected abstract void initExcludedPatternRepresentation(String[] patterns) throws IllegalArgumentException;
<ide>
<ide> /**
<ide> * Does the pattern at the given index match this string?
<ide> public boolean equals(Object other) {
<ide> @Override
<ide> public int hashCode() {
<ide> int result = 27;
<del> for (int i = 0; i < this.patterns.length; i++) {
<del> String pattern = this.patterns[i];
<add> for (String pattern : this.patterns) {
<ide> result = 13 * result + pattern.hashCode();
<ide> }
<del> for (int i = 0; i < this.excludedPatterns.length; i++) {
<del> String excludedPattern = this.excludedPatterns[i];
<add> for (String excludedPattern : this.excludedPatterns) {
<ide> result = 13 * result + excludedPattern.hashCode();
<ide> }
<ide> return result;
<ide> public String toString() {
<ide> ", excluded patterns " + ObjectUtils.nullSafeToString(this.excludedPatterns);
<ide> }
<ide>
<del>
<del> //---------------------------------------------------------------------
<del> // Serialization support
<del> //---------------------------------------------------------------------
<del>
<del> private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
<del> // Rely on default serialization; just initialize state after deserialization.
<del> ois.defaultReadObject();
<del>
<del> // Ask subclass to reinitialize.
<del> initPatternRepresentation(this.patterns);
<del> initExcludedPatternRepresentation(this.excludedPatterns);
<del> }
<del>
<ide> }
<ide><path>org.springframework.aop/src/main/java/org/springframework/aop/support/JdkRegexpMethodPointcut.java
<ide> /*
<del> * Copyright 2002-2007 the original author or authors.
<add> * Copyright 2002-2009 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 class JdkRegexpMethodPointcut extends AbstractRegexpMethodPointcut {
<ide> /**
<ide> * Compiled form of the patterns.
<ide> */
<del> private transient Pattern[] compiledPatterns = new Pattern[0];
<add> private Pattern[] compiledPatterns = new Pattern[0];
<ide>
<ide> /**
<ide> * Compiled form of the exclusion patterns.
<ide> */
<del> private transient Pattern[] compiledExclusionPatterns = new Pattern[0];
<add> private Pattern[] compiledExclusionPatterns = new Pattern[0];
<ide>
<ide>
<ide> /**
<ide> protected void initPatternRepresentation(String[] patterns) throws PatternSyntax
<ide> }
<ide>
<ide> /**
<del> * Returns <code>true</code> if the {@link Pattern} at index <code>patternIndex</code>
<del> * matches the supplied candidate <code>String</code>.
<add> * Initialize exclusion {@link Pattern Patterns} from the supplied <code>String[]</code>.
<ide> */
<ide> @Override
<del> protected boolean matches(String pattern, int patternIndex) {
<del> Matcher matcher = this.compiledPatterns[patternIndex].matcher(pattern);
<del> return matcher.matches();
<add> protected void initExcludedPatternRepresentation(String[] excludedPatterns) throws PatternSyntaxException {
<add> this.compiledExclusionPatterns = compilePatterns(excludedPatterns);
<ide> }
<ide>
<ide> /**
<del> * Initialize exclusion {@link Pattern Patterns} from the supplied <code>String[]</code>.
<add> * Returns <code>true</code> if the {@link Pattern} at index <code>patternIndex</code>
<add> * matches the supplied candidate <code>String</code>.
<ide> */
<ide> @Override
<del> protected void initExcludedPatternRepresentation(String[] excludedPatterns) throws IllegalArgumentException {
<del> this.compiledExclusionPatterns = compilePatterns(excludedPatterns);
<add> protected boolean matches(String pattern, int patternIndex) {
<add> Matcher matcher = this.compiledPatterns[patternIndex].matcher(pattern);
<add> return matcher.matches();
<ide> }
<ide>
<ide> /**
<ide> protected boolean matchesExclusion(String candidate, int patternIndex) {
<ide> return matcher.matches();
<ide> }
<ide>
<add>
<ide> /**
<ide> * Compiles the supplied <code>String[]</code> into an array of
<ide> * {@link Pattern} objects and returns that array.
<ide> */
<del> private Pattern[] compilePatterns(String[] source) {
<add> private Pattern[] compilePatterns(String[] source) throws PatternSyntaxException {
<ide> Pattern[] destination = new Pattern[source.length];
<ide> for (int i = 0; i < source.length; i++) {
<ide> destination[i] = Pattern.compile(source[i]); | 2 |
Javascript | Javascript | use ember.run.join internally for app#reset | 9c83112d9698823e4b9f540891a1f083d17d9503 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Ember.Application = Ember.Namespace.extend(Ember.DeferredMixin
<ide> @method reset
<ide> **/
<ide> reset: function() {
<add> this._readinessDeferrals = 1;
<add>
<ide> function handleReset() {
<ide> var router = this.__container__.lookup('router:main');
<ide> router.reset();
<ide> var Application = Ember.Application = Ember.Namespace.extend(Ember.DeferredMixin
<ide>
<ide> this.buildContainer();
<ide>
<del> this._readinessDeferrals = 1;
<del>
<ide> Ember.run.schedule('actions', this, function(){
<ide> this._initialize();
<ide> this.startRouting();
<ide> });
<ide> }
<ide>
<del> if (Ember.run.currentRunLoop) {
<del> handleReset.call(this);
<del> } else {
<del> Ember.run(this, handleReset);
<del> }
<add> Ember.run.join(this, handleReset);
<ide> },
<ide>
<ide> /** | 1 |
Python | Python | fix concatenation. closes ticket #642 | db45fc7e09d1b440cb7c273f8370ca0465c4959f | <ide><path>numpy/ma/core.py
<ide> def concatenate(arrays, axis=0):
<ide> for x in arrays:
<ide> if getmask(x) is not nomask:
<ide> break
<add> else:
<ide> return data
<ide> # OK, so we have to concatenate the masks
<ide> dm = numpy.concatenate([getmaskarray(a) for a in arrays], axis)
<ide><path>numpy/ma/tests/test_core.py
<ide> def test_fancy_dtype(self):
<ide> x[1] = masked
<ide> x['f'] = 17
<ide>
<add> def test_concat(self):
<add> x=zeros(2)
<add> y=array(ones(2),mask=[False,True])
<add>
<add> z = concatenate((x,y))
<add> assert_array_equal(z,[0,0,1,1])
<add> assert_array_equal(z.mask,[False,False,False,True])
<add>
<add> z = concatenate((y,x))
<add> assert_array_equal(z,[1,1,0,0])
<add> assert_array_equal(z.mask,[False,True,False,False])
<add>
<ide>
<ide> #..............................................................................
<ide> | 2 |
Ruby | Ruby | ask backtrace locations for their spot information | e85edcc45dfcd46e5206c09051e192da683fbfa7 | <ide><path>actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
<ide>
<ide> require "active_support/core_ext/module/attribute_accessors"
<ide> require "active_support/syntax_error_proxy"
<add>require "active_support/core_ext/thread/backtrace/location"
<ide> require "rack/utils"
<ide>
<ide> module ActionDispatch
<ide> class ExceptionWrapper
<ide> "ActionDispatch::Http::MimeNegotiation::InvalidType"
<ide> ]
<ide>
<del> attr_reader :backtrace_cleaner, :wrapped_causes, :exception_class_name
<add> attr_reader :backtrace_cleaner, :wrapped_causes, :exception_class_name, :exception
<ide>
<ide> def initialize(backtrace_cleaner, exception)
<ide> @backtrace_cleaner = backtrace_cleaner
<ide> def exception_id
<ide> end
<ide>
<ide> private
<del> attr_reader :exception
<ide>
<ide> def backtrace
<ide> @exception.backtrace_locations || []
<ide> def clean_backtrace(*args)
<ide> end
<ide>
<ide> def extract_source(trace)
<del> if error_highlight_available?
<del> begin
<del> spot = ErrorHighlight.spot(@exception, backtrace_location: trace)
<del> if spot
<del> line = spot[:first_lineno]
<del> code = extract_source_fragment_lines(spot[:script_lines], line)
<del>
<del> if line == spot[:last_lineno]
<del> code[line] = [
<del> code[line][0, spot[:first_column]],
<del> code[line][spot[:first_column]...spot[:last_column]],
<del> code[line][spot[:last_column]..-1],
<del> ]
<del> end
<del>
<del> return {
<del> code: code,
<del> line_number: line
<del> }
<del> end
<del> rescue TypeError
<add> spot = trace.spot(@exception)
<add>
<add> if spot
<add> line = spot[:first_lineno]
<add> code = extract_source_fragment_lines(spot[:script_lines], line)
<add>
<add> if line == spot[:last_lineno]
<add> code[line] = [
<add> code[line][0, spot[:first_column]],
<add> code[line][spot[:first_column]...spot[:last_column]],
<add> code[line][spot[:last_column]..-1],
<add> ]
<ide> end
<add>
<add> return {
<add> code: code,
<add> line_number: line
<add> }
<ide> end
<ide>
<ide> file, line_number = extract_file_and_line_number(trace)
<ide><path>activesupport/lib/active_support/core_ext/thread/backtrace/location.rb
<add>class Thread::Backtrace::Location
<add> if defined?(ErrorHighlight) && Gem::Version.new(ErrorHighlight::VERSION) >= Gem::Version.new("0.4.0")
<add> def spot(ex)
<add> ErrorHighlight.spot(ex, backtrace_location: self)
<add> end
<add> else
<add> def spot(ex)
<add> end
<add> end
<add>end
<ide><path>activesupport/lib/active_support/syntax_error_proxy.rb
<ide> def backtrace
<ide> end
<ide>
<ide> class BacktraceLocation < Struct.new(:path, :lineno, :to_s)
<add> def spot(_)
<add> end
<add> end
<add>
<add> class BacktraceLocationProxy < DelegateClass(Thread::Backtrace::Location)
<add> def initialize(loc, ex)
<add> super(loc)
<add> @ex = ex
<add> end
<add>
<add> def spot(_)
<add> super(@ex.__getobj__)
<add> end
<ide> end
<ide>
<ide> def backtrace_locations
<ide> parse_message_for_trace.map { |trace|
<ide> file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace
<ide> BacktraceLocation.new(file, line.to_i, trace)
<del> } + super
<add> # We have to wrap these backtrace locations because we need the
<add> # spot information to come from the originating exception, not the
<add> # proxy object that's generating these
<add> } + super.map { |loc| BacktraceLocationProxy.new(loc, self) }
<ide> end
<ide>
<ide> private | 3 |
PHP | PHP | indent the html tags | ea77dd8a19efecb2b24cde503c7f2578577c710b | <ide><path>src/Error/Debug/HtmlFormatter.php
<ide> protected function dumpHeader(): string
<ide> */
<ide> public function dump(NodeInterface $node): string
<ide> {
<del> $html = $this->export($node);
<add> $html = $this->export($node, 0);
<ide> $head = '';
<ide> if (!static::$outputHeader) {
<ide> static::$outputHeader = true;
<ide> public function dump(NodeInterface $node): string
<ide> * Convert a tree of NodeInterface objects into HTML
<ide> *
<ide> * @param \Cake\Error\Debug\NodeInterface $var The node tree to dump.
<add> * @param int $indent The current indentation level.
<ide> * @return string
<ide> */
<del> protected function export(NodeInterface $var): string
<add> protected function export(NodeInterface $var, int $indent): string
<ide> {
<ide> if ($var instanceof ScalarNode) {
<ide> switch ($var->getType()) {
<ide> protected function export(NodeInterface $var): string
<ide> }
<ide> }
<ide> if ($var instanceof ArrayNode) {
<del> return $this->exportArray($var);
<add> return $this->exportArray($var, $indent + 1);
<ide> }
<ide> if ($var instanceof ClassNode || $var instanceof ReferenceNode) {
<del> return $this->exportObject($var);
<add> return $this->exportObject($var, $indent + 1);
<ide> }
<ide> if ($var instanceof SpecialNode) {
<ide> return $this->style('special', (string)$var->getValue());
<ide> protected function export(NodeInterface $var): string
<ide> * Export an array type object
<ide> *
<ide> * @param \Cake\Error\Debug\ArrayNode $var The array to export.
<add> * @param int $indent The current indentation level.
<ide> * @return string Exported array.
<ide> */
<del> protected function exportArray(ArrayNode $var): string
<add> protected function exportArray(ArrayNode $var, int $indent): string
<ide> {
<ide> $open = '<span class="cake-dbg-array">' .
<ide> $this->style('punct', '[') .
<ide> '<samp class="cake-dbg-array-items">';
<ide> $vars = [];
<add> $break = "\n" . str_repeat(' ', $indent);
<add> $endBreak = "\n" . str_repeat(' ', $indent - 1);
<ide>
<ide> $arrow = $this->style('punct', ' => ');
<ide> foreach ($var->getChildren() as $item) {
<ide> $val = $item->getValue();
<del> $vars[] = '<span class="cake-dbg-array-item">' .
<del> $this->export($item->getKey()) . $arrow . $this->export($val) .
<add> $vars[] = $break . '<span class="cake-dbg-array-item">' .
<add> $this->export($item->getKey(), $indent) . $arrow . $this->export($val, $indent) .
<ide> $this->style('punct', ',') .
<ide> '</span>';
<ide> }
<ide>
<ide> $close = '</samp>' .
<add> $endBreak .
<ide> $this->style('punct', ']') .
<ide> '</span>';
<ide>
<ide> protected function exportArray(ArrayNode $var): string
<ide> * Handles object to string conversion.
<ide> *
<ide> * @param \Cake\Error\Debug\ClassNode|\Cake\Error\Debug\ReferenceNode $var Object to convert.
<add> * @param int $indent The current indentation level.
<ide> * @return string
<ide> * @see \Cake\Error\Debugger::exportVar()
<ide> */
<del> protected function exportObject($var): string
<add> protected function exportObject($var, int $indent): string
<ide> {
<ide> $objectId = "cake-db-object-{$this->id}-{$var->getId()}";
<ide> $out = sprintf(
<ide> '<span class="cake-dbg-object" id="%s">',
<ide> $objectId
<ide> );
<add> $break = "\n" . str_repeat(' ', $indent);
<add> $endBreak = "\n" . str_repeat(' ', $indent - 1);
<ide>
<ide> if ($var instanceof ReferenceNode) {
<ide> $link = sprintf(
<ide> protected function exportObject($var): string
<ide> $visibility = $property->getVisibility();
<ide> $name = $property->getName();
<ide> if ($visibility && $visibility !== 'public') {
<del> $props[] = '<span class="cake-dbg-prop">' .
<add> $props[] = $break .
<add> '<span class="cake-dbg-prop">' .
<ide> $this->style('visibility', $visibility) .
<ide> ' ' .
<ide> $this->style('property', $name) .
<ide> $arrow .
<del> $this->export($property->getValue()) .
<add> $this->export($property->getValue(), $indent) .
<ide> '</span>';
<ide> } else {
<del> $props[] = '<span class="cake-dbg-prop">' .
<add> $props[] = $break .
<add> '<span class="cake-dbg-prop">' .
<ide> $this->style('property', $name) .
<ide> $arrow .
<del> $this->export($property->getValue()) .
<add> $this->export($property->getValue(), $indent) .
<ide> '</span>';
<ide> }
<ide> }
<ide>
<ide> $end = '</samp>' .
<add> $endBreak .
<ide> $this->style('punct', '}') .
<ide> '</span>';
<ide>
<ide><path>tests/TestCase/Error/Debug/HtmlFormatterTest.php
<ide> public function testDump()
<ide> $this->assertGreaterThan(0, count($dom->childNodes));
<ide>
<ide> $expected = <<<TEXT
<del>object(MyObject) id:1 {stringProp => 'value'
<del>protected intProp => (int) 1
<del>protected floatProp => (float) 1.1
<del>protected boolProp => true
<del>private nullProp => null
<del>arrayProp => ['' => too much,(int) 1 => object(MyObject) id: 1 {},]}
<add>object(MyObject) id:1 {
<add> stringProp => 'value'
<add> protected intProp => (int) 1
<add> protected floatProp => (float) 1.1
<add> protected boolProp => true
<add> private nullProp => null
<add> arrayProp => [
<add> '' => too much,
<add> (int) 1 => object(MyObject) id: 1 {},
<add> ]
<add>}
<ide> TEXT;
<del> $this->assertStringContainsString(str_replace("\n", '', $expected), strip_tags($result));
<add> $this->assertStringContainsString($expected, strip_tags($result));
<ide> }
<ide> } | 2 |
Javascript | Javascript | use ember.error instead of default | 39f4e2eebb0aadf4e01cf0e85fe30356ea5169a0 | <ide><path>packages/ember-handlebars/lib/views/handlebars_bound_view.js
<ide> SimpleHandlebarsView.prototype = {
<ide> case 'destroyed':
<ide> break;
<ide> case 'inBuffer':
<del> throw new Error("Something you did tried to replace an {{expression}} before it was inserted into the DOM.");
<add> throw new Ember.Error("Something you did tried to replace an {{expression}} before it was inserted into the DOM.");
<ide> case 'hasElement':
<ide> case 'inDOM':
<ide> this.updateId = Ember.run.scheduleOnce('render', this, 'update');
<ide><path>packages/ember-views/lib/views/states/in_buffer.js
<ide> Ember.merge(inBuffer, {
<ide> // when a view is rendered in a buffer, rerendering it simply
<ide> // replaces the existing buffer with a new one
<ide> rerender: function(view) {
<del> throw new Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.");
<add> throw new Ember.Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.");
<ide> },
<ide>
<ide> // when a view is rendered in a buffer, appending a child | 2 |
Mixed | Ruby | omit marshal_dump & _dump from delegate_missing_to | 722c45f64110be876d83e7f9a22592aa954886c1 | <ide><path>activesupport/CHANGELOG.md
<del>* Allow the `on_rotation` proc used when decrypting/verifying a message to be
<del> passed at the constructor level.
<add>* Do not delegate missing `marshal_dump` and `_dump` methods via the
<add> `delegate_missing_to` extension. This avoids unintentionally adding instance
<add> variables when calling `Marshal.dump(object)`, should the delegation target of
<add> `object` be a method which would otherwise add them. Fixes #36522.
<add>
<add> *Aaron Lipman*
<add>
<add>* Allow the on_rotation proc used when decrypting/verifying a message to be
<add> be passed at the constructor level.
<ide>
<ide> Before:
<ide>
<ide><path>activesupport/lib/active_support/core_ext/module/delegation.rb
<ide> def delegate(*methods, to: nil, prefix: nil, allow_nil: nil, private: nil)
<ide> # The delegated method must be public on the target, otherwise it will
<ide> # raise +DelegationError+. If you wish to instead return +nil+,
<ide> # use the <tt>:allow_nil</tt> option.
<add> #
<add> # The <tt>marshal_dump</tt> and <tt>_dump</tt> methods are exempt from
<add> # delegation due to possible interference when calling
<add> # <tt>Marshal.dump(object)</tt>, should the delegation target method
<add> # of <tt>object</tt> add or remove instance variables.
<ide> def delegate_missing_to(target, allow_nil: nil)
<ide> target = target.to_s
<ide> target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target)
<ide> def respond_to_missing?(name, include_private = false)
<ide> # It may look like an oversight, but we deliberately do not pass
<ide> # +include_private+, because they do not get delegated.
<ide>
<add> return false if name == :marshal_dump || name == :_dump
<ide> #{target}.respond_to?(name) || super
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/module_test.rb
<ide> def initialize(kase)
<ide> end
<ide> end
<ide>
<add>class Maze
<add> attr_accessor :cavern, :passages
<add>end
<add>
<add>class Cavern
<add> delegate_missing_to :target
<add>
<add> attr_reader :maze
<add>
<add> def initialize(maze)
<add> @maze = maze
<add> end
<add>
<add> def target
<add> @maze.passages = :twisty
<add> end
<add>end
<add>
<ide> class Block
<ide> def hello?
<ide> true
<ide> def test_delegate_missing_to_respects_superclass_missing
<ide> assert_respond_to DecoratedTester.new(@david), :extra_missing
<ide> end
<ide>
<add> def test_delegate_missing_to_does_not_interfere_with_marshallization
<add> maze = Maze.new
<add> maze.cavern = Cavern.new(maze)
<add>
<add> array = [maze, nil]
<add> serialized_array = Marshal.dump(array)
<add> deserialized_array = Marshal.load(serialized_array)
<add>
<add> assert_nil deserialized_array[1]
<add> end
<add>
<ide> def test_delegate_with_case
<ide> event = Event.new(Tester.new)
<ide> assert_equal 1, event.foo | 3 |
Javascript | Javascript | add tests for socket.setnodelay | 12554e01f5ec3e19c96c0cd7f01296058edb58cf | <ide><path>test/parallel/test-net-socket-setnodelay.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>
<add>const truthyValues = [true, 1, 'true', {}, []];
<add>const falseyValues = [false, 0, ''];
<add>const genSetNoDelay = (desiredArg) => (enable) => {
<add> assert.strictEqual(enable, desiredArg);
<add>};
<add>
<add>// setNoDelay should default to true
<add>let socket = new net.Socket({
<add> handle: {
<add> setNoDelay: common.mustCall(genSetNoDelay(true))
<add> }
<add>});
<add>socket.setNoDelay();
<add>
<add>socket = new net.Socket({
<add> handle: {
<add> setNoDelay: common.mustCall(genSetNoDelay(true), truthyValues.length)
<add> }
<add>});
<add>truthyValues.forEach((testVal) => socket.setNoDelay(testVal));
<add>
<add>socket = new net.Socket({
<add> handle: {
<add> setNoDelay: common.mustCall(genSetNoDelay(false), falseyValues.length)
<add> }
<add>});
<add>falseyValues.forEach((testVal) => socket.setNoDelay(testVal));
<add>
<add>// if a handler doesn't have a setNoDelay function it shouldn't be called.
<add>// In the case below, if it is called an exception will be thrown
<add>socket = new net.Socket({
<add> handle: {
<add> setNoDelay: null
<add> }
<add>});
<add>const returned = socket.setNoDelay(true);
<add>assert.ok(returned instanceof net.Socket); | 1 |
Javascript | Javascript | fix http bench-parser.js | 62c7b2eca9d9a53ccedd6517c955285b0732d255 | <ide><path>benchmark/http/bench-parser.js
<ide> function main({ len, n }) {
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> parser.execute(header, 0, header.length);
<del> parser.reinitialize(REQUEST, i > 0);
<add> parser.initialize(REQUEST, header);
<ide> }
<ide> bench.end(n);
<ide> } | 1 |
PHP | PHP | add notsameas() validation rule | b949ffc0c417838a3b2dbca0643af1e33cd962f3 | <ide><path>src/Validation/Validator.php
<ide> public function notEquals($field, $value, $message = null, $when = null)
<ide> * @param string|null $message The error message when the rule fails.
<ide> * @param string|callable|null $when Either 'create' or 'update' or a callable that returns
<ide> * true when the validation rule should be applied.
<del> * @see \Cake\Validation\Validation::compareWith()
<add> * @see \Cake\Validation\Validation::compareFields()
<ide> * @return $this
<ide> */
<ide> public function sameAs($field, $secondField, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> return $this->add($field, 'sameAs', $extra + [
<del> 'rule' => ['compareWith', $secondField]
<add> 'rule' => ['compareFields', $secondField, true]
<add> ]);
<add> }
<add>
<add> /**
<add> * Add a rule to compare that two fields have different values.
<add> *
<add> * @param mixed $field The field you want to apply the rule to.
<add> * @param mixed $secondField The field you want to compare against.
<add> * @param string|null $message The error message when the rule fails.
<add> * @param string|callable|null $when Either 'create' or 'update' or a callable that returns
<add> * true when the validation rule should be applied.
<add> * @see \Cake\Validation\Validation::compareFields()
<add> * @return $this
<add> * @since 3.6.0
<add> */
<add> public function notSameAs($field, $secondField, $message = null, $when = null)
<add> {
<add> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<add> return $this->add($field, 'notSameAs', $extra + [
<add> 'rule' => ['compareFields', $secondField, false]
<ide> ]);
<ide> }
<ide>
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testNotEquals()
<ide> public function testSameAs()
<ide> {
<ide> $validator = new Validator();
<del> $this->assertProxyMethod($validator, 'sameAs', 'other', ['other'], 'compareWith');
<add> $this->assertProxyMethod($validator, 'sameAs', 'other', ['other', true], 'compareFields');
<ide> $this->assertNotEmpty($validator->errors(['username' => 'foo']));
<ide> }
<ide>
<add> /**
<add> * Tests the notSameAs proxy method
<add> *
<add> * @return void
<add> */
<add> public function testNotSameAs()
<add> {
<add> $validator = new Validator();
<add> $this->assertProxyMethod($validator, 'notSameAs', 'other', ['other', false], 'compareFields');
<add> $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'foo']));
<add> }
<add>
<ide> /**
<ide> * Tests the containsNonAlphaNumeric proxy method
<ide> * | 2 |
Python | Python | fix docstrings for kubernetes code | 9f37af25ae7eb85fa8dbb70b7dbb23bbd5505323 | <ide><path>airflow/kubernetes/pod_generator.py
<ide> def construct_pod( # pylint: disable=too-many-arguments
<ide> return reduce(PodGenerator.reconcile_pods, pod_list)
<ide>
<ide> @staticmethod
<del> def serialize_pod(pod: k8s.V1Pod):
<add> def serialize_pod(pod: k8s.V1Pod) -> dict:
<ide> """
<ide>
<ide> Converts a k8s.V1Pod into a jsonified object
<ide>
<del> @param pod:
<del> @return:
<add> :param pod: k8s.V1Pod object
<add> :return: Serialized version of the pod returned as dict
<ide> """
<ide> api_client = ApiClient()
<ide> return api_client.sanitize_for_serialization(pod)
<ide> def deserialize_model_file(path: str) -> k8s.V1Pod:
<ide> def deserialize_model_dict(pod_dict: dict) -> k8s.V1Pod:
<ide> """
<ide> Deserializes python dictionary to k8s.V1Pod
<del> @param pod_dict:
<del> @return:
<add>
<add> :param pod_dict: Serialized dict of k8s.V1Pod object
<add> :return: De-serialized k8s.V1Pod
<ide> """
<ide> api_client = ApiClient()
<ide> return api_client._ApiClient__deserialize_model(pod_dict, k8s.V1Pod) # pylint: disable=W0212
<ide><path>airflow/utils/db.py
<ide> def _get_alembic_config():
<ide> def check_migrations(timeout):
<ide> """
<ide> Function to wait for all airflow migrations to complete.
<del> @param timeout:
<del> @return:
<add>
<add> :param timeout: Timeout for the migration in seconds
<add> :return: None
<ide> """
<ide> from alembic.runtime.migration import MigrationContext
<ide> from alembic.script import ScriptDirectory
<ide> def resetdb():
<ide> def drop_airflow_models(connection):
<ide> """
<ide> Drops all airflow models.
<del> @param connection:
<del> @return: None
<add>
<add> :param connection: SQLAlchemy Connection
<add> :return: None
<ide> """
<ide> from airflow.models.base import Base
<ide>
<ide> def drop_airflow_models(connection):
<ide> def drop_flask_models(connection):
<ide> """
<ide> Drops all Flask models.
<del> @param connection:
<del> @return:
<add>
<add> :param connection: SQLAlchemy Connection
<add> :return: None
<ide> """
<ide> from flask_appbuilder.models.sqla import Base
<ide>
<ide> def drop_flask_models(connection):
<ide> def check(session=None):
<ide> """
<ide> Checks if the database works.
<add>
<ide> :param session: session of the sqlalchemy
<ide> """
<ide> session.execute('select 1 as is_alive;')
<ide><path>tests/executors/test_kubernetes_executor.py
<ide> def test_not_adopt_unassigned_task(self, mock_kube_client):
<ide> """
<ide> We should not adopt any tasks that were not assigned by the scheduler.
<ide> This ensures that there is no contention over pod management.
<del> @param mock_kube_client:
<del> @return:
<ide> """
<ide>
<ide> executor = self.kubernetes_executor | 3 |
Text | Text | upgrade release guide to match current practices | 42e99b2c6417cb1cbbbab8f3d32c62232aa3d043 | <ide><path>RELEASING_RAILS.md
<ide> Do not release with a Red CI. You can find the CI status here:
<ide> https://buildkite.com/rails/rails
<ide> ```
<ide>
<del>### Is Sam Ruby happy? If not, make him happy.
<del>
<del>Sam Ruby keeps a [test suite](https://github.com/rubys/awdwr) that makes
<del>sure the code samples in his book
<del>([Agile Web Development with Rails](https://pragprog.com/titles/rails6))
<del>all work. These are valuable system tests
<del>for Rails. You can check the status of these tests here:
<del>
<del>[https://intertwingly.net/projects/dashboard.html](https://intertwingly.net/projects/dashboard.html)
<del>
<del>Do not release with Red AWDwR tests.
<del>
<ide> ### Do we have any Git dependencies? If so, contact those authors.
<ide>
<ide> Having Git dependencies indicates that we depend on unreleased code.
<ide> Obviously Rails cannot be released when it depends on unreleased code.
<ide> Contact the authors of those particular gems and work out a release date that
<ide> suits them.
<ide>
<del>### Contact the security team (either tenderlove or rafaelfranca)
<del>
<del>Let them know of your plans to release. There may be security issues to be
<del>addressed, and that can impact your release date.
<del>
<del>### Notify implementors.
<del>
<del>Ruby implementors have high stakes in making sure Rails works. Be kind and
<del>give them a heads up that Rails will be released soonish.
<del>
<del>This is only required for major and minor releases, bugfix releases aren't a
<del>big enough deal, and are supposed to be backward compatible.
<del>
<del>Send a message just giving a heads up about the upcoming release to these
<del>lists:
<del>
<del>* team@jruby.org
<del>* community@rubini.us
<del>* [rubyonrails-core](https://discuss.rubyonrails.org/c/rubyonrails-core)
<del>
<del>Implementors will love you and help you.
<del>
<del>## 3 Days before release
<del>
<del>This is when you should release the release candidate. Here are your tasks
<del>for today:
<del>
<del>### Is the CI green? If not, make it green.
<add>### Announce your plans to the rest of the team on Campfire
<ide>
<del>### Is Sam Ruby happy? If not, make him happy.
<del>
<del>### Contact the security team. CVE emails must be sent on this day.
<del>
<del>### Create a release branch.
<del>
<del>From the stable branch, create a release branch. For example, if you're
<del>releasing Rails 3.0.10, do this:
<del>
<del>```
<del>[aaron@higgins rails (3-0-stable)]$ git checkout -b 3-0-10
<del>Switched to a new branch '3-0-10'
<del>[aaron@higgins rails (3-0-10)]$
<del>```
<add>Let them know of your plans to release.
<ide>
<ide> ### Update each CHANGELOG.
<ide>
<ide> If you're doing a stable branch release, you should also ensure that all of
<ide> the CHANGELOG entries in the stable branch are also synced to the main
<ide> branch.
<ide>
<add>## Day of release
<add>
<ide> ### Put the new version in the RAILS_VERSION file.
<ide>
<ide> Include an RC number if appropriate, e.g. `6.0.0.rc1`.
<ide> blog.
<ide>
<ide> ### Post the announcement to the Rails Twitter account.
<ide>
<del>## Time between release candidate and actual release
<del>
<del>Check the rails-core mailing list and the GitHub issue list for regressions in
<del>the RC.
<del>
<del>If any regressions are found, fix the regressions and repeat the release
<del>candidate process. We will not release the final until 72 hours after the
<del>last release candidate has been pushed. This means that if users find
<del>regressions, the scheduled release date must be postponed.
<del>
<del>When you fix the regressions, do not create a new branch. Fix them on the
<del>stable branch, then cherry pick the commit to your release branch. No other
<del>commits should be added to the release branch besides regression fixing commits.
<del>
<del>## Day of release
<del>
<del>Many of these steps are the same as for the release candidate, so if you need
<del>more explanation on a particular step, see the RC steps.
<del>
<del>Today, do this stuff in this order:
<del>
<del>* Apply security patches to the release branch
<del>* Update CHANGELOG with security fixes
<del>* Update RAILS_VERSION to remove the rc
<del>* Build and test the gem
<del>* Release the gems
<del>* If releasing a new stable version:
<del> - Trigger stable docs generation (see below)
<del> - Update the version in the home page
<del>* Email security lists
<del>* Email general announcement lists
<add>## Security releases
<ide>
<ide> ### Emailing the Rails security announce list
<ide> | 1 |
Text | Text | add note about public folder with standalone mode | 411a9b84d8f7dec29ddb0d249c161400bda5f02d | <ide><path>docs/advanced-features/output-file-tracing.md
<ide> module.exports = {
<ide>
<ide> This will create a folder at `.next/standalone` which can then be deployed on it's own without installing `node_modules`.
<ide>
<del>Additionally, a minimal `server.js` file is also output which can be used instead of `next start`. This minimal server does not copy the `.next/static` directory by default as this should ideally be handled by a CDN instead, although it can be copied to the `standalone` folder manually and the `server.js` file will serve it automatically.
<add>Additionally, a minimal `server.js` file is also output which can be used instead of `next start`. This minimal server does not copy the `public` or `.next/static` folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the `standalone` folder manually and the `server.js` file will serve it automatically.
<ide>
<ide> ## Caveats
<ide> | 1 |
PHP | PHP | add merge parameter to helpers/options | 83c6f57b49feb00f655e2d1c7e3b5ceed6f7a0df | <ide><path>src/View/ViewBuilder.php
<ide> public function plugin($name = null)
<ide> * The helpers to use
<ide> *
<ide> * @param array|null $helpers Helpers to use.
<add> * @param bool $merge Whether or not to merge existing data with the new data.
<ide> * @return array|$this
<ide> */
<del> public function helpers(array $helpers = null)
<add> public function helpers(array $helpers = null, $merge = true)
<ide> {
<ide> if ($helpers === null) {
<ide> return $this->helpers;
<ide> }
<del>
<del> $this->helpers = array_merge($this->helpers, $helpers);
<add> if ($merge) {
<add> $helpers = array_merge($this->helpers, $helpers);
<add> }
<add> $this->helpers = $helpers;
<ide> return $this;
<ide> }
<ide>
<ide> public function layout($name = null)
<ide> * Set additional options for the view.
<ide> *
<ide> * @param array|null $options Either an array of options or null to get current options.
<add> * @param bool $merge Whether or not to merge existing data with the new data.
<ide> * @return array|$this
<ide> */
<del> public function options(array $options = null)
<add> public function options(array $options = null, $merge = true)
<ide> {
<ide> if ($options === null) {
<ide> return $this->options;
<ide> }
<del> $this->options = array_merge($this->options, $options);
<add> if ($merge) {
<add> $options = array_merge($this->options, $options);
<add> }
<add> $this->options = $options;
<ide> return $this;
<ide> }
<ide>
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> public function testArrayProperties($property, $value)
<ide> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this');
<ide> $this->assertSame($value, $builder->{$property}(), 'Getter gets value.');
<ide> }
<add>
<add> /**
<add> * Test array property accessor/mutator methods.
<add> *
<add> * @dataProvider arrayPropertyProvider
<add> * @return void
<add> */
<add> public function testArrayPropertyMerge($property, $value)
<add> {
<add> $builder = new ViewBuilder();
<add> $builder->{$property}($value);
<add>
<add> $builder->{$property}(['Merged'], true);
<add> $this->assertSame(array_merge($value, ['Merged']), $builder->{$property}(), 'Should merge');
<add>
<add> $builder->{$property}($value, false);
<add> $this->assertSame($value, $builder->{$property}(), 'Should replace');
<add> }
<add>
<add> /**
<add> * test building with all the options.
<add> *
<add> * @return void
<add> */
<add> public function testBuildComplete()
<add> {
<add> $this->markTestIncomplete('not done');
<add> }
<add>
<add> /**
<add> * test missing view class
<add> *
<add> * @expectedException \Cake\View\Exception\MissingViewException
<add> * @expectedExceptionMessage View class "Foo" is missing.
<add> * @return void
<add> */
<add> public function testBuildMissingViewClass()
<add> {
<add> $this->markTestIncomplete('not done');
<add> }
<ide> } | 2 |
Javascript | Javascript | fix inspect performance bug | f413f56c3606fa6f01f0a7341fb4136965890fb7 | <ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> }
<ide> }
<ide>
<add> // Using an array here is actually better for the average case than using
<add> // a Set. `seen` will only check for the depth and will never grow too large.
<add> if (ctx.seen.indexOf(value) !== -1)
<add> return ctx.stylize('[Circular]', 'special');
<add>
<ide> let keys;
<ide> let symbols = Object.getOwnPropertySymbols(value);
<ide>
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> }
<ide> }
<ide>
<del> // Using an array here is actually better for the average case than using
<del> // a Set. `seen` will only check for the depth and will never grow too large.
<del> if (ctx.seen.indexOf(value) !== -1)
<del> return ctx.stylize('[Circular]', 'special');
<del>
<ide> if (recurseTimes != null) {
<ide> if (recurseTimes < 0)
<ide> return ctx.stylize(`[${constructor || tag || 'Object'}]`, 'special'); | 1 |
Javascript | Javascript | fix direction of verticalswipejump gestures | 09801aac302c4fa741f92ee2c6ffe906c6118a5b | <ide><path>Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js
<ide> 'use strict';
<ide>
<ide> var Dimensions = require('Dimensions');
<del>var PixelRatio = require('PixelRatio');
<ide> var I18nManager = require('I18nManager');
<add>var PixelRatio = require('PixelRatio');
<ide>
<ide> var buildStyleInterpolator = require('buildStyleInterpolator');
<ide>
<ide> var NavigatorSceneConfigs = {
<ide> ...BaseConfig,
<ide> gestures: {
<ide> jumpBack: {
<del> ...BaseDownUpGesture,
<add> ...BaseUpDownGesture,
<ide> overswipe: BaseOverswipeConfig,
<ide> edgeHitWidth: null,
<ide> isDetachable: true,
<ide> var NavigatorSceneConfigs = {
<ide> ...BaseConfig,
<ide> gestures: {
<ide> jumpBack: {
<del> ...BaseUpDownGesture,
<add> ...BaseDownUpGesture,
<ide> overswipe: BaseOverswipeConfig,
<ide> edgeHitWidth: null,
<ide> isDetachable: true, | 1 |
Ruby | Ruby | fix paramswrapper docs errors | c894fff60a9146754fc9f7c4ddf992634c2bedd3 | <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> module ActionController
<ide> # Wraps parameters hash into nested hash. This will allow client to submit
<ide> # POST request without having to specify a root element in it.
<ide> #
<del> # By default, this functionality won't be enabled by default. You can enable
<add> # By default this functionality won't be enabled. You can enable
<ide> # it globally by setting +ActionController::Base.wrap_parameters+:
<ide> #
<ide> # ActionController::Base.wrap_parameters = [:json]
<ide> module ClassMethods
<ide> #
<ide> # ==== Examples
<ide> # wrap_parameters :format => :xml
<del> # # enables the parmeter wrappes for XML format
<add> # # enables the parmeter wrapper for XML format
<ide> #
<ide> # wrap_parameters :person
<ide> # # wraps parameters into +params[:person]+ hash | 1 |
PHP | PHP | add hint to mail fake | c19afaf30f67838b6b3d2da0afcbff98ff6029f3 | <ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php
<ide> public function assertSent($mailable, $callback = null)
<ide> return $this->assertSentTimes($mailable, $callback);
<ide> }
<ide>
<add> $message = "The expected [{$mailable}] mailable was not sent.";
<add>
<add> if (count($this->queuedMailables) > 0) {
<add> $message .= ' Did you mean to use assertQueued() instead?';
<add> }
<add>
<ide> PHPUnit::assertTrue(
<ide> $this->sent($mailable, $callback)->count() > 0,
<del> "The expected [{$mailable}] mailable was not sent."
<add> $message
<ide> );
<ide> }
<ide> | 1 |
PHP | PHP | fix indentation and add test group | d503d192c592470a6c57bf167ef28168912eaf4b | <ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testBeforeRenderViewVariables()
<ide> /**
<ide> * Tests deprecated view properties work
<ide> *
<add> * @group deprecated
<ide> * @param $property Deprecated property name
<ide> * @param $getter Getter name
<ide> * @param $setter Setter name
<ide> public function testBeforeRenderViewVariables()
<ide> */
<ide> public function testDeprecatedViewProperty($property, $getter, $setter, $value)
<ide> {
<del> $controller = new AnotherTestController();
<del> error_reporting(E_ALL ^ E_USER_DEPRECATED);
<del> $controller->$property = $value;
<del> $this->assertSame($value, $controller->$property);
<del> $this->assertSame($value, $controller->viewBuilder()->{$getter}());
<add> $controller = new AnotherTestController();
<add> error_reporting(E_ALL ^ E_USER_DEPRECATED);
<add> $controller->$property = $value;
<add> $this->assertSame($value, $controller->$property);
<add> $this->assertSame($value, $controller->viewBuilder()->{$getter}());
<ide> }
<ide>
<ide> /**
<ide> * Tests deprecated view properties message
<ide> *
<add> * @group deprecated
<ide> * @param $property Deprecated property name
<ide> * @param $getter Getter name
<ide> * @param $setter Setter name
<ide> public function testDeprecatedViewProperty($property, $getter, $setter, $value)
<ide> */
<ide> public function testDeprecatedViewPropertySetterMessage($property, $getter, $setter, $value)
<ide> {
<del> error_reporting(E_ALL);
<del> $controller = new AnotherTestController();
<del> $controller->$property = $value;
<add> error_reporting(E_ALL);
<add> $controller = new AnotherTestController();
<add> $controller->$property = $value;
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | update param doc for wherenotnull() | 3ec56b8810bc40016252977c69ba27057dcecf7d | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function orWhereNull($column)
<ide> /**
<ide> * Add a "where not null" clause to the query.
<ide> *
<del> * @param string $column
<add> * @param string|array $columns
<ide> * @param string $boolean
<ide> * @return \Illuminate\Database\Query\Builder|static
<ide> */
<del> public function whereNotNull($column, $boolean = 'and')
<add> public function whereNotNull($columns, $boolean = 'and')
<ide> {
<del> return $this->whereNull($column, $boolean, true);
<add> return $this->whereNull($columns, $boolean, true);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | remove util properties from common | 3202456baae108b56b82515ced02ceebf2f8d8a7 | <ide><path>test/common.js
<ide> var fs = require('fs');
<ide> var assert = require('assert');
<ide> var os = require('os');
<ide> var child_process = require('child_process');
<add>var util = require('util');
<add>
<ide>
<ide> exports.testDir = path.dirname(__filename);
<ide> exports.fixturesDir = path.join(exports.testDir, 'fixtures');
<ide> exports.hasIPv6 = Object.keys(ifaces).some(function(name) {
<ide> });
<ide> });
<ide>
<del>var util = require('util');
<del>for (var i in util) exports[i] = util[i];
<del>//for (var i in exports) global[i] = exports[i];
<del>
<ide> function protoCtrChain(o) {
<ide> var result = [];
<ide> for (; o; o = o.__proto__) { result.push(o.constructor); } | 1 |
Ruby | Ruby | add two cross links to methods in docs [skip ci] | e8a881a753c5b8f029924e1b79229540f8908714 | <ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> def redirect_to(options = {}, response_options = {})
<ide> # * <tt>:fallback_location</tt> - The default fallback location that will be used on missing +Referer+ header.
<ide> # * <tt>:allow_other_host</tt> - Allow or disallow redirection to the host that is different to the current host, defaults to true.
<ide> #
<del> # All other options that can be passed to <tt>redirect_to</tt> are accepted as
<add> # All other options that can be passed to #redirect_to are accepted as
<ide> # options and the behavior is identical.
<ide> def redirect_back(fallback_location:, allow_other_host: true, **args)
<ide> referer = request.headers["Referer"]
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def save!(*args, **options, &block)
<ide> #
<ide> # To enforce the object's +before_destroy+ and +after_destroy+
<ide> # callbacks or any <tt>:dependent</tt> association
<del> # options, use <tt>#destroy</tt>.
<add> # options, use #destroy.
<ide> def delete
<ide> _delete_row if persisted?
<ide> @destroyed = true | 2 |
Javascript | Javascript | take full advantage of caching between builds | f01457e8fc10f68eafe1a1e68c3117eccf25df9c | <ide><path>packages/next/build/webpack.js
<ide> function optimizationConfig ({dir, dev, isServer, totalPages}) {
<ide> }
<ide>
<ide> // Terser is a better uglifier
<del> config.minimizer = [new TerserPlugin({
<del> parallel: true,
<del> sourceMap: false,
<del> cache: true
<del> })]
<add> config.minimizer = [
<add> new TerserPlugin({
<add> parallel: true,
<add> sourceMap: false,
<add> cache: true,
<add> cacheKeys: (keys) => {
<add> // path changes per build because we add buildId
<add> // because the input is already hashed the path is not needed
<add> delete keys.path
<add> return keys
<add> }
<add> })
<add> ]
<ide>
<ide> // Only enabled in production
<ide> // This logic will create a commons bundle
<ide> export default async function getBaseWebpackConfig (dir: string, {dev = false, i
<ide> dev && new webpack.NoEmitOnErrorsPlugin(),
<ide> dev && new UnlinkFilePlugin(),
<ide> dev && new CaseSensitivePathPlugin(), // Since on macOS the filesystem is case-insensitive this will make sure your path are case-sensitive
<add> !dev && new webpack.HashedModuleIdsPlugin(),
<ide> // Removes server/client code by minifier
<ide> new webpack.DefinePlugin({
<ide> 'process.browser': JSON.stringify(!isServer)
<ide><path>packages/next/build/webpack/loaders/next-babel-loader.js
<ide> module.exports = babelLoader.custom(babel => {
<ide> dev: opts.dev
<ide> }
<ide> const loader = Object.assign({
<add> cacheCompression: false,
<ide> cacheDirectory: true
<ide> }, opts)
<ide> delete loader.isServer
<ide><path>test/integration/size-limit/test/index.test.js
<ide> describe('Production response size', () => {
<ide> console.log(`Response Sizes:\n${responseSizes.map(obj => ` ${obj.url}: ${obj.bytes} (bytes)`).join('\n')} \nOverall: ${responseSizeKilobytes} KB`)
<ide>
<ide> // These numbers are without gzip compression!
<del> expect(responseSizeKilobytes).toBeLessThanOrEqual(203) // Kilobytes
<add> expect(responseSizeKilobytes).toBeLessThanOrEqual(207) // Kilobytes
<ide> })
<ide> }) | 3 |
Text | Text | suggest eager load in ci in the c2z howto guide | 14940def0d908aae9a59f9ecf25b2f013026b925 | <ide><path>guides/source/classic_to_zeitwerk_howto.md
<ide> Please make sure to depend on at least Bootsnap 1.4.4.
<ide> Check Zeitwerk Compliance in the Test Suite
<ide> -------------------------------------------
<ide>
<del>The Rake task `zeitwerk:check` just eager loads, because doing so triggers built-in validations in Zeitwerk.
<add>The task `zeitwerk:check` is handy while migrating. Once the project is compliant, it is recommended to automate this check. In order to do so, it is enough to eager load the application, which is all the task does, indeed.
<ide>
<del>You can add the equivalent of this to your test suite to make sure the application always loads correctly regardless of test coverage:
<add>### Continuous Integration
<ide>
<del>### minitest
<add>If your project has continuous integration in place, it is a good idea to eager load the application when the suite runs there. If the application cannot be eager loaded for whatever reason, you want to know in CI, better than in production, right?
<add>
<add>CIs typically set some environment variable to indicate the test suite is running there. For example, it could be `CI`:
<add>
<add>```ruby
<add># config/environments/test.rb
<add>config.eager_load = ENV["CI"].present?
<add>```
<add>
<add>Starting with Rails 7, newly generated applications are configured that way by default.
<add>
<add>### Bare Test Suites
<add>
<add>If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`:
<add>
<add>#### minitest
<ide>
<ide> ```ruby
<ide> require "test_helper"
<ide> class ZeitwerkComplianceTest < ActiveSupport::TestCase
<ide> end
<ide> ```
<ide>
<del>### RSpec
<add>#### RSpec
<ide>
<ide> ```ruby
<ide> require "rails_helper" | 1 |
Text | Text | update displacy api docs [ci skip] | cb41a33d14fc3974dbfd5a60d9a92ed970d25792 | <ide><path>website/docs/api/top-level.md
<ide> If a setting is not present in the options, the default value will be used.
<ide> | -------- | ---- | ------------------------------------------------------------------------------------- | ------- |
<ide> | `ents` | list | Entity types to highlight (`None` for all types). | `None` |
<ide> | `colors` | dict | Color overrides. Entity types in uppercase should be mapped to color names or values. | `{}` |
<add>| `template` <Tag variant="new">2.2</Tag> | unicode | Optional template to overwrite the HTML used to render entity spans. Should be a format string and can use `{bg}`, `{text}` and `{label}`. | see [`templates.py`](https://github.com/explosion/spaCy/blob/master/spacy/displacy/templates.py) |
<ide>
<ide> By default, displaCy comes with colors for all
<ide> [entity types supported by spaCy](/api/annotation#named-entities). If you're
<ide> using custom entity types, you can use the `colors` setting to add your own
<del>colors for them.
<add>colors for them. Your application or model package can also expose a [`spacy_displacy_colors` entry point](/usage/saving-loading#entry-points-displacy) to add custom labels and their colors automatically.
<ide>
<ide> ## Utility functions {#util source="spacy/util.py"}
<ide> | 1 |
Python | Python | add timehistory callback to bert | 7d86c3171d1a89c728fb21d8f64f63bd107de0d2 | <ide><path>official/modeling/model_training_utils.py
<ide> def _run_callbacks_on_batch_end(batch, logs):
<ide> train_steps(train_iterator,
<ide> tf.convert_to_tensor(steps, dtype=tf.int32))
<ide> train_loss = _float_metric_value(train_loss_metric)
<add> _run_callbacks_on_batch_end(current_step, {'loss': train_loss})
<ide> current_step += steps
<del> _run_callbacks_on_batch_end(current_step - 1, {'loss': train_loss})
<ide>
<ide> # Updates training logging.
<ide> training_status = 'Train Step: %d/%d / loss = %s' % (
<ide><path>official/nlp/bert/common_flags.py
<ide> def define_common_bert_flags():
<ide> flags.DEFINE_bool('hub_module_trainable', True,
<ide> 'True to make keras layers in the hub module trainable.')
<ide>
<del> flags_core.define_log_steps()
<del>
<ide> # Adds flags for mixed precision and multi-worker training.
<ide> flags_core.define_performance(
<ide> num_parallel_calls=False,
<ide><path>official/nlp/bert/run_classifier.py
<ide> def metric_fn():
<ide> epochs,
<ide> steps_per_epoch,
<ide> eval_steps,
<del> custom_callbacks=custom_callbacks)
<add> custom_callbacks=None)
<ide>
<ide> # Use user-defined loop to start training.
<ide> logging.info('Training using customized training loop TF 2.0 with '
<ide> def run_bert(strategy,
<ide> if not strategy:
<ide> raise ValueError('Distribution strategy has not been specified.')
<ide>
<del> if FLAGS.log_steps:
<del> custom_callbacks = [keras_utils.TimeHistory(
<del> batch_size=FLAGS.train_batch_size,
<del> log_steps=FLAGS.log_steps,
<del> logdir=FLAGS.model_dir,
<del> )]
<del> else:
<del> custom_callbacks = None
<del>
<ide> trained_model = run_bert_classifier(
<ide> strategy,
<ide> model_config,
<ide> def run_bert(strategy,
<ide> train_input_fn,
<ide> eval_input_fn,
<ide> run_eagerly=FLAGS.run_eagerly,
<del> use_keras_compile_fit=FLAGS.use_keras_compile_fit,
<del> custom_callbacks=custom_callbacks)
<add> use_keras_compile_fit=FLAGS.use_keras_compile_fit)
<ide>
<ide> if FLAGS.model_export_path:
<ide> # As Keras ModelCheckpoint callback used with Keras compile/fit() API
<ide><path>official/nlp/bert/run_squad.py
<ide> from official.nlp.bert import tokenization
<ide> from official.nlp.data import squad_lib as squad_lib_wp
<ide> from official.utils.misc import distribution_utils
<del>from official.utils.misc import keras_utils
<ide>
<ide>
<ide> flags.DEFINE_string('vocab_file', None,
<ide> def main(_):
<ide> all_reduce_alg=FLAGS.all_reduce_alg,
<ide> tpu_address=FLAGS.tpu)
<ide> if FLAGS.mode in ('train', 'train_and_predict'):
<del> if FLAGS.log_steps:
<del> custom_callbacks = [keras_utils.TimeHistory(
<del> batch_size=FLAGS.train_batch_size,
<del> log_steps=FLAGS.log_steps,
<del> logdir=FLAGS.model_dir,
<del> )]
<del> else:
<del> custom_callbacks = None
<del>
<del> train_squad(
<del> strategy,
<del> input_meta_data,
<del> custom_callbacks=custom_callbacks,
<del> run_eagerly=FLAGS.run_eagerly,
<del> )
<add> train_squad(strategy, input_meta_data, run_eagerly=FLAGS.run_eagerly)
<ide> if FLAGS.mode in ('predict', 'train_and_predict'):
<ide> predict_squad(strategy, input_meta_data)
<ide> | 4 |
Javascript | Javascript | update gruntfile to pass jshint | 5f2b8fb8313fc9a83221e93e3c8210a5ae2783a8 | <ide><path>Gruntfile.js
<ide> module.exports = function(grunt) {
<ide> // npm install https://github.com/gruntjs/grunt-contrib-jshint/archive/7fd70e86c5a8d489095fa81589d95dccb8eb3a46.tar.gz
<ide> jshint: {
<ide> src: {
<del> src: ["src/js/*.js", "Gruntfile.js", "test/unit/*.js"],
<add> src: ['src/js/*.js', 'Gruntfile.js', 'test/unit/*.js'],
<ide> options: {
<del> jshintrc: ".jshintrc"
<add> jshintrc: '.jshintrc'
<ide> }
<ide> }
<ide> },
<ide> module.exports = function(grunt) {
<ide> minified: ['test/minified.html']
<ide> },
<ide> watch: {
<del> files: [ "src/**/*.js", "test/unit/*.js" ],
<del> tasks: "dev"
<add> files: [ 'src/**/*.js', 'test/unit/*.js' ],
<add> tasks: 'dev'
<ide> }
<ide> // Copy is broken. Waiting for an update to use.
<ide> // copy: {
<ide> module.exports = function(grunt) {
<ide> // },
<ide> });
<ide>
<del> grunt.loadNpmTasks("grunt-contrib-jshint");
<del> grunt.loadNpmTasks("grunt-contrib-qunit");
<del> grunt.loadNpmTasks("grunt-contrib-watch");
<del> grunt.loadNpmTasks("grunt-contrib-clean");
<del> grunt.loadNpmTasks("grunt-contrib-copy");
<add> grunt.loadNpmTasks('grunt-contrib-jshint');
<add> grunt.loadNpmTasks('grunt-contrib-qunit');
<add> grunt.loadNpmTasks('grunt-contrib-watch');
<add> grunt.loadNpmTasks('grunt-contrib-clean');
<add> grunt.loadNpmTasks('grunt-contrib-copy');
<ide>
<ide> // Default task.
<ide> grunt.registerTask('default', ['jshint', 'build', 'minify', 'dist']);
<ide> module.exports = function(grunt) {
<ide> path:['src/js/'],
<ide> dep:[],
<ide> exclude:[],
<del> output_mode:'list',
<add> output_mode:'list'
<ide> }, function(err,results){
<ide> if (err) {
<del> grunt.warn({ message: err })
<add> grunt.warn({ message: err });
<ide> grunt.log.writeln(err);
<ide> done(false);
<ide> }
<ide> module.exports = function(grunt) {
<ide> grunt.file.write(dest, '');
<ide>
<ide> if (this.data.sourcelist) {
<del> files = files.concat(grunt.file.read(this.data.sourcelist).split(','))
<add> files = files.concat(grunt.file.read(this.data.sourcelist).split(','));
<ide> }
<ide> if (this.file.src) {
<ide> files = files.concat(this.file.src); | 1 |
Javascript | Javascript | fix comment typo | 1b8645ccae0659da5bf6d3f999a8b24d147df83e | <ide><path>examples/js/cameras/CombinedCamera.js
<ide> THREE.CombinedCamera.prototype.setFov = function( fov ) {
<ide>
<ide> };
<ide>
<del>// For mantaining similar API with PerspectiveCamera
<add>// For maintaining similar API with PerspectiveCamera
<ide>
<ide> THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
<ide> | 1 |
Javascript | Javascript | require posts to have a date | 40f70673c65de19183bfd9e32151383d23e7edf1 | <ide><path>tools/blog/generate.js
<ide> function parseFile(file, contents) {
<ide> }, {});
<ide> if (post.status && post.status !== 'publish') return null;
<ide> post.body = c;
<add> post.src = file;
<ide> return post;
<ide> }
<ide>
<ide> function buildPermalink(key, post) {
<ide>
<ide> data.post = post;
<ide>
<del> var d = post.date = new Date(post.date);
<add> if (!post.date) throw new Error('post date is required ' + post.src);
<add> else post.date = new Date(post.date);
<add> var d = post.date;
<ide>
<ide> var y = d.getYear() + 1900;
<ide> var m = d.getMonth() + 1; | 1 |
Ruby | Ruby | pass the request object to the application | b18f22d15c28fc5fe634928d59148c932bba4696 | <ide><path>actionpack/lib/action_dispatch/journey/router.rb
<ide> def serve(req)
<ide>
<ide> req.path_parameters = set_params.merge parameters
<ide>
<del> status, headers, body = route.app.call(req.env)
<add> status, headers, body = route.app.serve(req)
<ide>
<ide> if 'pass' == headers['X-Cascade']
<ide> req.script_name = script_name
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def matches?(req)
<ide> end
<ide> end
<ide>
<del> def call(env)
<del> req = @request.new(env)
<del> matches?(req) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
<add> def serve(req)
<add> matches?(req) ? @app.call(req.env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
<ide> ensure
<ide> req.reset_parameters
<ide> end
<ide><path>actionpack/test/journey/router_test.rb
<ide> def test_X_Cascade
<ide> end
<ide>
<ide> def test_clear_trailing_slash_from_script_name_on_root_unanchored_routes
<add> route_set = Routing::RouteSet.new
<add> mapper = Routing::Mapper.new route_set
<add>
<ide> strexp = Router::Strexp.new("/", {}, ['/', '.', '?'], false)
<ide> path = Path::Pattern.new strexp
<ide> app = lambda { |env| [200, {}, ['success!']] }
<del> @router.routes.add_route(app, path, {}, {}, {})
<add> mapper.get '/weblog', :to => app
<ide>
<ide> env = rack_env('SCRIPT_NAME' => '', 'PATH_INFO' => '/weblog')
<del> resp = @router.serve rails_env env
<add> resp = route_set.call env
<ide> assert_equal ['success!'], resp.last
<ide> assert_equal '', env['SCRIPT_NAME']
<ide> end | 3 |
Javascript | Javascript | use cached vectors | e289d72af7a917d2583c234e74832623feb12f79 | <ide><path>examples/jsm/csm/Frustum.js
<ide> export default class Frustum {
<ide> // 2 --- 1
<ide> // clip space spans from [-1, 1]
<ide>
<del> this.vertices.near[ 0 ] = new Vector3( 1, 1, - 1 );
<del> this.vertices.near[ 1 ] = new Vector3( 1, - 1, - 1 );
<del> this.vertices.near[ 2 ] = new Vector3( - 1, - 1, - 1 );
<del> this.vertices.near[ 3 ] = new Vector3( - 1, 1, - 1 );
<add> this.vertices.near[ 0 ].set( 1, 1, - 1 );
<add> this.vertices.near[ 1 ].set( 1, - 1, - 1 );
<add> this.vertices.near[ 2 ].set( - 1, - 1, - 1 );
<add> this.vertices.near[ 3 ].set( - 1, 1, - 1 );
<ide> this.vertices.near.forEach( function( v ) {
<ide>
<ide> v.applyMatrix4( inverseProjectionMatrix );
<ide>
<ide> } );
<ide>
<del> this.vertices.far[ 0 ] = new Vector3( 1, 1, 1 );
<del> this.vertices.far[ 1 ] = new Vector3( 1, - 1, 1 );
<del> this.vertices.far[ 2 ] = new Vector3( - 1, - 1, 1 );
<del> this.vertices.far[ 3 ] = new Vector3( - 1, 1, 1 );
<add> this.vertices.far[ 0 ].set( 1, 1, 1 );
<add> this.vertices.far[ 1 ].set( 1, - 1, 1 );
<add> this.vertices.far[ 2 ].set( - 1, - 1, 1 );
<add> this.vertices.far[ 3 ].set( - 1, 1, 1 );
<ide> this.vertices.far.forEach( function( v ) {
<ide>
<ide> v.applyMatrix4( inverseProjectionMatrix );
<ide> export default class Frustum {
<ide>
<ide> for ( let j = 0; j < 4; j ++ ) {
<ide>
<del> cascade.vertices.near[ j ] = this.vertices.near[ j ].clone();
<add> cascade.vertices.near[ j ].copy( this.vertices.near[ j ] );
<ide>
<ide> }
<ide>
<ide> } else {
<ide>
<ide> for ( let j = 0; j < 4; j ++ ) {
<ide>
<del> cascade.vertices.near[ j ] = new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] );
<add> cascade.vertices.near[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] );
<ide>
<ide> }
<ide>
<ide> export default class Frustum {
<ide>
<ide> for ( let j = 0; j < 4; j ++ ) {
<ide>
<del> cascade.vertices.far[ j ] = this.vertices.far[ j ].clone();
<add> cascade.vertices.far[ j ].copy( this.vertices.far[ j ] );
<ide>
<ide> }
<ide>
<ide> } else {
<ide>
<ide> for ( let j = 0; j < 4; j ++ ) {
<ide>
<del> cascade.vertices.far[ j ] = new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] );
<add> cascade.vertices.far[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] );
<ide>
<ide> }
<ide> | 1 |
PHP | PHP | remove error method call in welcome view | 868a33fb9cc3d70b337264ba005f16ab306cd9ed | <ide><path>application/views/home/index.php
<ide>
<ide> <div id="content">
<ide> You have successfully installed Laravel.
<del> <?php Cache::driver('adslkadsl'); ?>
<add>
<ide> <br /><br />
<ide>
<ide> Perhaps you would like to <a href="http://laravel.com/docs">peruse the documentation</a> or <a href="http://github.com/taylorotwell/laravel">contribute on GitHub</a>? | 1 |
Python | Python | add --std=c99 in setup.py, not distutils | 18af8e00711f62a5aa2c9b0c4f1225be49877a38 | <ide><path>numpy/distutils/ccompiler.py
<ide> def CCompiler_customize(self, dist, need_cxx=0):
<ide> 'g++' in self.compiler[0] or
<ide> 'clang' in self.compiler[0]):
<ide> self._auto_depends = True
<del> if 'gcc' in self.compiler[0] and not need_cxx:
<del> # add std=c99 flag for gcc
<del> # TODO: does this need to be more specific?
<del> self.compiler.append('-std=c99')
<del> self.compiler_so.append('-std=c99')
<ide> elif os.name == 'posix':
<ide> import tempfile
<ide> import shutil
<ide><path>numpy/distutils/tests/test_ccompiler.py
<del>from distutils.ccompiler import new_compiler
<del>
<del>from numpy.distutils.numpy_distribution import NumpyDistribution
<del>
<del>def test_ccompiler():
<del> '''
<del> scikit-image/scikit-image issue 4369
<del> We unconditionally add ``-std-c99`` to the gcc compiler in order
<del> to support c99 with very old gcc compilers. However the same call
<del> is used to get the flags for the c++ compiler, just with a kwarg.
<del> Make sure in this case, where it would not be legal, the option is **not** added
<del> '''
<del> dist = NumpyDistribution()
<del> compiler = new_compiler()
<del> compiler.customize(dist)
<del> if hasattr(compiler, 'compiler') and 'gcc' in compiler.compiler[0]:
<del> assert 'c99' in ' '.join(compiler.compiler)
<del>
<del> compiler = new_compiler()
<del> compiler.customize(dist, need_cxx=True)
<del> if hasattr(compiler, 'compiler') and 'gcc' in compiler.compiler[0]:
<del> assert 'c99' not in ' '.join(compiler.compiler)
<ide><path>setup.py
<ide> import sys
<ide> import subprocess
<ide> import textwrap
<add>import sysconfig
<ide>
<ide>
<ide> if sys.version_info[:2] < (3, 6):
<ide> def run(self):
<ide> sdist.run(self)
<ide>
<ide>
<add>def get_build_overrides():
<add> """
<add> Custom build commands to add `--std=c99` to compilation
<add> """
<add> from numpy.distutils.command.build_clib import build_clib
<add> from numpy.distutils.command.build_ext import build_ext
<add>
<add> def _is_using_gcc(obj):
<add> is_gcc = False
<add> if obj.compiler.compiler_type == 'unix':
<add> cc = sysconfig.get_config_var("CC")
<add> if not cc:
<add> cc = ""
<add> compiler_name = os.path.basename(cc)
<add> is_gcc = "gcc" in compiler_name
<add> return is_gcc
<add>
<add> class new_build_clib(build_clib):
<add> def build_a_library(self, build_info, lib_name, libraries):
<add> if _is_using_gcc(self):
<add> args = build_info.get('extra_compiler_args') or []
<add> args.append('--std=c99')
<add> build_info['extra_compiler_args'] = args
<add> build_clib.build_a_library(self, build_info, lib_name, libraries)
<add>
<add> class new_build_ext(build_ext):
<add> def build_extension(self, ext):
<add> if _is_using_gcc(self):
<add> if '--std=c99' not in ext.extra_compile_args:
<add> ext.extra_compile_args.append('--std=c99')
<add> build_ext.build_extension(self, ext)
<add> return new_build_clib, new_build_ext
<add>
<add>
<ide> def generate_cython():
<ide> cwd = os.path.abspath(os.path.dirname(__file__))
<ide> print("Cythonizing sources")
<ide> def setup_package():
<ide> 'f2py%s.%s = numpy.f2py.f2py2e:main' % sys.version_info[:2],
<ide> ]
<ide>
<add> cmdclass={"sdist": sdist_checked,
<add> }
<ide> metadata = dict(
<ide> name = 'numpy',
<ide> maintainer = "NumPy Developers",
<ide> def setup_package():
<ide> classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f],
<ide> platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"],
<ide> test_suite='nose.collector',
<del> cmdclass={"sdist": sdist_checked,
<del> },
<add> cmdclass=cmdclass,
<ide> python_requires='>=3.5',
<ide> zip_safe=False,
<ide> entry_points={
<ide> def setup_package():
<ide> generate_cython()
<ide>
<ide> metadata['configuration'] = configuration
<add> # Customize extension building
<add> cmdclass['build_clib'], cmdclass['build_ext'] = get_build_overrides()
<ide> else:
<ide> # Version number is added to metadata inside configuration() if build
<ide> # is run. | 3 |
Java | Java | add perftest dev support manager | 4d1a56813c7975c848631de331e424587054fd57 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java
<ide> import android.content.Context;
<ide> import androidx.annotation.Nullable;
<ide> import com.facebook.react.common.SurfaceDelegateFactory;
<add>import com.facebook.react.common.build.ReactBuildConfig;
<ide> import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
<ide> import com.facebook.react.devsupport.interfaces.DevSupportManager;
<ide> import com.facebook.react.devsupport.interfaces.RedBoxHandler;
<ide> public DevSupportManager create(
<ide> if (!enableOnCreate) {
<ide> return new DisabledDevSupportManager();
<ide> }
<add> if (!ReactBuildConfig.DEBUG) {
<add> return new PerftestDevSupportManager(applicationContext);
<add> }
<ide> try {
<ide> // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to
<ide> // Class.forName() with a static string. So instead we generate a quasi-dynamic string to
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java
<add>/*
<add> * Copyright (c) Meta Platforms, Inc. and affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.devsupport;
<add>
<add>import android.content.Context;
<add>
<add>/**
<add> * Interface for accessing and interacting with development features related to performance testing.
<add> * Communication is enabled via the Inspector, but everything else is disabled.
<add> */
<add>public final class PerftestDevSupportManager extends DisabledDevSupportManager {
<add> private final DevServerHelper mDevServerHelper;
<add> private final DevInternalSettings mDevSettings;
<add> private final InspectorPackagerConnection.BundleStatus mBundleStatus;
<add>
<add> public PerftestDevSupportManager(Context applicationContext) {
<add> mDevSettings =
<add> new DevInternalSettings(
<add> applicationContext,
<add> new DevInternalSettings.Listener() {
<add> @Override
<add> public void onInternalSettingsChanged() {}
<add> });
<add> mBundleStatus = new InspectorPackagerConnection.BundleStatus();
<add> mDevServerHelper =
<add> new DevServerHelper(
<add> mDevSettings,
<add> applicationContext.getPackageName(),
<add> new InspectorPackagerConnection.BundleStatusProvider() {
<add> @Override
<add> public InspectorPackagerConnection.BundleStatus getBundleStatus() {
<add> return mBundleStatus;
<add> }
<add> });
<add> }
<add>
<add> @Override
<add> public DevInternalSettings getDevSettings() {
<add> return mDevSettings;
<add> }
<add>
<add> @Override
<add> public void startInspector() {
<add> mDevServerHelper.openInspectorConnection();
<add> }
<add>
<add> @Override
<add> public void stopInspector() {
<add> mDevServerHelper.closeInspectorConnection();
<add> }
<add>} | 2 |
Ruby | Ruby | remove circle from html_void_elements set | 8d51706c20a21c8f675391892eaaa12031b85fe4 | <ide><path>actionview/lib/action_view/helpers/tag_helper.rb
<ide> class TagBuilder # :nodoc:
<ide> include CaptureHelper
<ide> include OutputSafetyHelper
<ide>
<del> HTML_VOID_ELEMENTS = %i(area base br col circle embed hr img input keygen link meta param source track wbr).to_set
<add> HTML_VOID_ELEMENTS = %i(area base br col embed hr img input keygen link meta param source track wbr).to_set
<ide> SVG_SELF_CLOSING_ELEMENTS = %i(animate animateMotion animateTransform circle ellipse line path polygon polyline rect set stop use view).to_set
<ide>
<ide> def initialize(view_context)
<ide><path>actionview/test/template/tag_helper_test.rb
<ide> def test_tag_builder
<ide> def test_tag_builder_void_tag
<ide> assert_equal "<br>", tag.br
<ide> assert_equal "<br class=\"some_class\">", tag.br(class: "some_class")
<del> assert_equal "<svg><use href=\"#cool-icon\" /></svg>", tag.svg { tag.use("href" => "#cool-icon") }
<ide> end
<ide>
<ide> def test_tag_builder_void_tag_with_forced_content
<ide> assert_equal "<br>some content</br>", tag.br("some content")
<ide> end
<ide>
<add> def test_tag_builder_self_closing_tag
<add> assert_equal "<svg><use href=\"#cool-icon\" /></svg>", tag.svg { tag.use("href" => "#cool-icon") }
<add> assert_equal "<svg><circle cx=\"5\" cy=\"5\" r=\"5\" /></svg>", tag.svg { tag.circle(cx: "5", cy: "5", r: "5") }
<add> end
<add>
<add> def test_tag_builder_self_closing_tag_with_content
<add> assert_equal "<svg><circle><desc>A circle</desc></circle></svg>", tag.svg { tag.circle { tag.desc "A circle" } }
<add> end
<add>
<ide> def test_tag_builder_is_singleton
<ide> assert_equal tag, tag
<ide> end | 2 |
Ruby | Ruby | move constantize from conversions to inflections | 51be8dbdedd1279d74cd7a7e277c5042f278b8a2 | <ide><path>activemodel/lib/active_model/observing.rb
<ide> require 'active_support/core_ext/array/wrap'
<ide> require 'active_support/core_ext/module/aliasing'
<ide> require 'active_support/core_ext/string/inflections'
<del>require 'active_support/core_ext/string/conversions'
<ide>
<ide> module ActiveModel
<ide> module Observing
<ide><path>activesupport/lib/active_support/core_ext/string/conversions.rb
<ide> def to_datetime
<ide> d[5] += d.pop
<ide> ::DateTime.civil(*d)
<ide> end
<del>
<del> # +constantize+ tries to find a declared constant with the name specified
<del> # in the string. It raises a NameError when the name is not in CamelCase
<del> # or is not initialized.
<del> #
<del> # Examples
<del> # "Module".constantize # => Module
<del> # "Class".constantize # => Class
<del> def constantize
<del> ActiveSupport::Inflector.constantize(self)
<del> end
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/string/inflections.rb
<ide> def singularize
<ide> ActiveSupport::Inflector.singularize(self)
<ide> end
<ide>
<add> # +constantize+ tries to find a declared constant with the name specified
<add> # in the string. It raises a NameError when the name is not in CamelCase
<add> # or is not initialized.
<add> #
<add> # Examples
<add> # "Module".constantize # => Module
<add> # "Class".constantize # => Class
<add> def constantize
<add> ActiveSupport::Inflector.constantize(self)
<add> end
<add>
<ide> # By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
<ide> # is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
<ide> # | 3 |
Ruby | Ruby | treat secrets as binary | be4ebc47807948ed8d40c04d0a134f7de1ec0fc2 | <ide><path>railties/lib/rails/secrets.rb
<ide> def preprocess(path)
<ide>
<ide> def writing(contents)
<ide> tmp_path = File.join(Dir.tmpdir, File.basename(path))
<del> File.write(tmp_path, contents)
<add> IO.binwrite(tmp_path, contents)
<ide>
<ide> yield tmp_path
<ide>
<del> updated_contents = File.read(tmp_path)
<add> updated_contents = IO.binread(tmp_path)
<ide>
<ide> write(updated_contents) if updated_contents != contents
<ide> ensure
<ide><path>railties/test/secrets_test.rb
<ide> def teardown
<ide> end
<ide> end
<ide>
<add> test "can read secrets written in binary" do
<add> run_secrets_generator do
<add> secrets = <<-end_of_secrets
<add> production:
<add> api_key: 00112233445566778899aabbccddeeff…
<add> end_of_secrets
<add>
<add> Rails::Secrets.write(secrets.force_encoding(Encoding::ASCII_8BIT))
<add>
<add> Rails::Secrets.read_for_editing do |tmp_path|
<add> assert_match(/production:\n\s*api_key: 00112233445566778899aabbccddeeff…\n/, File.read(tmp_path))
<add> end
<add>
<add> assert_equal "00112233445566778899aabbccddeeff…\n", `bin/rails runner -e production "puts Rails.application.secrets.api_key"`
<add> end
<add> end
<add>
<add> test "can read secrets written in non-binary" do
<add> run_secrets_generator do
<add> secrets = <<-end_of_secrets
<add> production:
<add> api_key: 00112233445566778899aabbccddeeff…
<add> end_of_secrets
<add>
<add> Rails::Secrets.write(secrets)
<add>
<add> Rails::Secrets.read_for_editing do |tmp_path|
<add> assert_equal(secrets.force_encoding(Encoding::ASCII_8BIT), IO.binread(tmp_path))
<add> end
<add>
<add> assert_equal "00112233445566778899aabbccddeeff…\n", `bin/rails runner -e production "puts Rails.application.secrets.api_key"`
<add> end
<add> end
<add>
<ide> private
<ide> def run_secrets_generator
<ide> Dir.chdir(app_path) do | 2 |
PHP | PHP | remove tests that are now dead | a7f9b51d44dfe3c04fcec4186df487357fa648e2 | <ide><path>lib/Cake/Test/TestCase/TestSuite/TestFixtureTest.php
<ide> public function testInitStaticFixture() {
<ide> $this->assertEmpty($schema->indexes());
<ide> }
<ide>
<del>/**
<del> * test that init() correctly sets the fixture table when the connection
<del> * or model have prefixes defined.
<del> *
<del> * @return void
<del> */
<del> public function testInitDbPrefix() {
<del> $this->markTestSkipped('Skipped for now as table prefixes need to be re-worked.');
<del>
<del> $db = ConnectionManager::getDataSource('test');
<del> $Source = new TestFixtureTestFixture();
<del> $Source->drop($db);
<del> $Source->create($db);
<del> $Source->insert($db);
<del>
<del> $Fixture = new TestFixtureTestFixture();
<del> $expected = array('id', 'name', 'created');
<del> $this->assertEquals($expected, array_keys($Fixture->fields));
<del>
<del> $config = $db->config;
<del> $config['prefix'] = 'fixture_test_suite_';
<del> ConnectionManager::create('fixture_test_suite', $config);
<del>
<del> $Fixture->fields = $Fixture->records = null;
<del> $Fixture->import = array('table' => 'fixture_tests', 'connection' => 'test', 'records' => true);
<del> $Fixture->init();
<del> $this->assertEquals(count($Fixture->records), count($Source->records));
<del> $Fixture->create(ConnectionManager::getDataSource('fixture_test_suite'));
<del>
<del> $Fixture = new TestFixtureImportFixture();
<del> $Fixture->fields = $Fixture->records = $Fixture->table = null;
<del> $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test');
<del> $Fixture->init();
<del> $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields));
<del> $this->assertEquals('fixture_tests', $Fixture->table);
<del>
<del> $keys = array_flip(ClassRegistry::keys());
<del> $this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
<del>
<del> $Fixture->drop(ConnectionManager::getDataSource('fixture_test_suite'));
<del> $Source->drop($db);
<del> }
<del>
<del>/**
<del> * test that fixtures don't duplicate the test db prefix.
<del> *
<del> * @return void
<del> */
<del> public function testInitDbPrefixDuplication() {
<del> $this->markTestSkipped('Skipped for now as table prefixes need to be re-worked.');
<del>
<del> $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite');
<del> $db = ConnectionManager::getDataSource('test');
<del> $backPrefix = $db->config['prefix'];
<del> $db->config['prefix'] = 'cake_fixture_test_';
<del> ConnectionManager::create('fixture_test_suite', $db->config);
<del> $newDb = ConnectionManager::getDataSource('fixture_test_suite');
<del> $newDb->config['prefix'] = 'cake_fixture_test_';
<del>
<del> $Source = new TestFixtureTestFixture();
<del> $Source->create($db);
<del> $Source->insert($db);
<del>
<del> $Fixture = new TestFixtureImportFixture();
<del> $Fixture->fields = $Fixture->records = $Fixture->table = null;
<del> $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test');
<del>
<del> $Fixture->init();
<del> $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields));
<del> $this->assertEquals('fixture_tests', $Fixture->table);
<del>
<del> $Source->drop($db);
<del> $db->config['prefix'] = $backPrefix;
<del> }
<del>
<del>/**
<del> * test init with a model that has a tablePrefix declared.
<del> *
<del> * @return void
<del> */
<del> public function testInitModelTablePrefix() {
<del> $this->markTestSkipped('Skipped for now as table prefixes need to be re-worked.');
<del>
<del> $Source = new TestFixtureTestFixture();
<del> $Source->create($this->db);
<del> $Source->insert($this->db);
<del>
<del> $Fixture = new TestFixtureTestFixture();
<del> unset($Fixture->table);
<del> $Fixture->fields = $Fixture->records = null;
<del> $Fixture->import = array('model' => 'FixturePrefixTest', 'connection' => 'test', 'records' => false);
<del> $Fixture->init();
<del> $this->assertEquals('fixture_tests', $Fixture->table);
<del>
<del> $keys = array_flip(ClassRegistry::keys());
<del> $this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
<del>
<del> $Source->drop($this->db);
<del> }
<del>
<ide> /**
<ide> * test import fixture initialization
<ide> *
<ide> public function testInitImport() {
<ide> $this->assertEquals($expected, $fixture->schema()->columns());
<ide> }
<ide>
<del>/**
<del> * test that importing with records works. Make sure to try with postgres as its
<del> * handling of aliases is a workaround at best.
<del> *
<del> * @return void
<del> */
<del> public function testImportWithRecords() {
<del> $this->markTestSkipped('Skipped for now as table prefixes need to be re-worked.');
<del> Configure::write('App.namespace', 'TestApp');
<del> $Fixture = new ImportFixture();
<del> $Fixture->fields = $Fixture->records = null;
<del> $Fixture->import = [
<del> 'model' => 'Post',
<del> 'connection' => 'test',
<del> 'records' => true
<del> ];
<del> $Fixture->init();
<del> $expected = [
<del> 'id',
<del> 'author_id',
<del> 'title',
<del> 'body',
<del> 'published',
<del> 'created',
<del> 'updated',
<del> ];
<del> $this->assertEquals($expected, array_keys($Fixture->fields));
<del> $this->assertFalse(empty($Fixture->records[0]), 'No records loaded on importing fixture.');
<del> $this->assertTrue(isset($Fixture->records[0]['title']), 'No title loaded for first record');
<del> }
<del>
<ide> /**
<ide> * test create method
<ide> * | 1 |
Text | Text | improve a hint in the new js rpg project | d350b14c129fa4f25a9f5993d28b6714b8a66038 | <ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8f14fe6d1fc72454648c7.md
<ide> You should set `monsterStats.style.display` to `none`.
<ide> assert.match(update.toString(), /monsterStats\.style\.display\s*=\s*('|")none\1/);
<ide> ```
<ide>
<del>This should be the first line of the `update` function.
<add>You should add your code in the first line of the `update` function.
<ide>
<ide> ```js
<ide> assert.match(update.toString(), /update\s*\(\s*location\s*\)\s*\{\s*monsterStats\.style\.display\s*=\s*('|")none\1/); | 1 |
Javascript | Javascript | remove unused catch bindings | a74b4a062fd6cf8ba5fb0a17078f855b072841cd | <ide><path>test/common/index.js
<ide> function canCreateSymLink() {
<ide> try {
<ide> const output = execSync(`${whoamiPath} /priv`, { timout: 1000 });
<ide> return output.includes('SeCreateSymbolicLinkPrivilege');
<del> } catch (e) {
<add> } catch {
<ide> return false;
<ide> }
<ide> }
<ide> function isAlive(pid) {
<ide> try {
<ide> process.kill(pid, 'SIGCONT');
<ide> return true;
<del> } catch (e) {
<add> } catch {
<ide> return false;
<ide> }
<ide> }
<ide> function getTTYfd() {
<ide> if (ttyFd === undefined) {
<ide> try {
<ide> return fs.openSync('/dev/tty');
<del> } catch (e) {
<add> } catch {
<ide> // There aren't any tty fd's available to use.
<ide> return -1;
<ide> }
<ide> function runWithInvalidFD(func) {
<ide> // be an valid one.
<ide> try {
<ide> while (fs.fstatSync(fd--) && fd > 0);
<del> } catch (e) {
<add> } catch {
<ide> return func(fd);
<ide> }
<ide>
<ide><path>test/doctool/test-doctool-html.js
<ide> const common = require('../common');
<ide> // The doctool currently uses js-yaml from the tool/node_modules/eslint/ tree.
<ide> try {
<ide> require('../../tools/node_modules/eslint/node_modules/js-yaml');
<del>} catch (e) {
<add>} catch {
<ide> common.skip('missing js-yaml (eslint not present)');
<ide> }
<ide>
<ide><path>test/doctool/test-doctool-json.js
<ide> const common = require('../common');
<ide> // The doctool currently uses js-yaml from the tool/node_modules/eslint/ tree.
<ide> try {
<ide> require('../../tools/node_modules/eslint/node_modules/js-yaml');
<del>} catch (e) {
<add>} catch {
<ide> common.skip('missing js-yaml (eslint not present)');
<ide> }
<ide>
<ide><path>test/fixtures/catch-stdout-error.js
<ide> function write() {
<ide> try {
<ide> process.stdout.write('Hello, world\n');
<del> } catch (ex) {
<add> } catch {
<ide> throw new Error('this should never happen');
<ide> }
<ide> setImmediate(function() {
<ide><path>test/internet/test-dgram-broadcast-multi-process.js
<ide> if (process.argv[2] !== 'child') {
<ide> const buf = messages[i++];
<ide>
<ide> if (!buf) {
<del> try { sendSocket.close(); } catch (e) {}
<add> try { sendSocket.close(); } catch {}
<ide> return;
<ide> }
<ide>
<ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> if (process.argv[2] !== 'child') {
<ide> const buf = messages[i++];
<ide>
<ide> if (!buf) {
<del> try { sendSocket.close(); } catch (e) {}
<add> try { sendSocket.close(); } catch {}
<ide> return;
<ide> }
<ide>
<ide><path>test/known_issues/test-url-parse-conformance.js
<ide> tests.forEach((test) => {
<ide> assert.strictEqual(test.pathname, parsed.pathname || '/');
<ide> assert.strictEqual(test.search, parsed.search || '');
<ide> assert.strictEqual(test.hash, parsed.hash || '');
<del> } catch (err) {
<add> } catch {
<ide> // For now, we're just interested in the number of failures.
<ide> failed++;
<ide> }
<ide> }
<del> } catch (err) {
<add> } catch {
<ide> // If Parse failed and it wasn't supposed to, treat it as a failure.
<ide> if (!test.failure)
<ide> failed++;
<ide><path>test/message/vm_dont_display_runtime_error.js
<ide> try {
<ide> filename: 'test.vm',
<ide> displayErrors: false
<ide> });
<del>} catch (e) {}
<add>} catch {}
<ide>
<ide> console.error('middle');
<ide>
<ide><path>test/message/vm_dont_display_syntax_error.js
<ide> try {
<ide> filename: 'test.vm',
<ide> displayErrors: false
<ide> });
<del>} catch (e) {}
<add>} catch {}
<ide>
<ide> console.error('middle');
<ide>
<ide><path>test/parallel/test-assert.js
<ide> assert.throws(
<ide> },
<ide> Array
<ide> );
<del> } catch (e) {
<add> } catch {
<ide> threw = true;
<ide> }
<ide> assert.ok(threw, 'wrong constructor validation');
<ide><path>test/parallel/test-crypto-cipher-decipher.js
<ide> testCipher2(Buffer.from('0123456789abcdef'));
<ide> // not assert. See https://github.com/nodejs/node-v0.x-archive/issues/4886.
<ide> {
<ide> const c = crypto.createCipher('aes-256-cbc', 'secret');
<del> try { c.final('xxx'); } catch (e) { /* Ignore. */ }
<del> try { c.final('xxx'); } catch (e) { /* Ignore. */ }
<del> try { c.final('xxx'); } catch (e) { /* Ignore. */ }
<add> try { c.final('xxx'); } catch { /* Ignore. */ }
<add> try { c.final('xxx'); } catch { /* Ignore. */ }
<add> try { c.final('xxx'); } catch { /* Ignore. */ }
<ide> const d = crypto.createDecipher('aes-256-cbc', 'secret');
<del> try { d.final('xxx'); } catch (e) { /* Ignore. */ }
<del> try { d.final('xxx'); } catch (e) { /* Ignore. */ }
<del> try { d.final('xxx'); } catch (e) { /* Ignore. */ }
<add> try { d.final('xxx'); } catch { /* Ignore. */ }
<add> try { d.final('xxx'); } catch { /* Ignore. */ }
<add> try { d.final('xxx'); } catch { /* Ignore. */ }
<ide> }
<ide>
<ide> // Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482:
<ide><path>test/parallel/test-file-write-stream2.js
<ide> process.on('exit', function() {
<ide> function removeTestFile() {
<ide> try {
<ide> fs.unlinkSync(filepath);
<del> } catch (e) {}
<add> } catch {}
<ide> }
<ide>
<ide>
<ide><path>test/parallel/test-fs-realpath-pipe.js
<ide> for (const code of [
<ide> if (require('fs').realpathSync('/dev/stdin')) {
<ide> process.exit(2);
<ide> }
<del> } catch (e) {
<add> } catch {
<ide> process.exit(1);
<ide> }`
<ide> ]) {
<ide><path>test/parallel/test-fs-realpath.js
<ide> function test_simple_relative_symlink(realpath, realpathSync, callback) {
<ide> [
<ide> [entry, `../${path.basename(tmpDir)}/cycles/root.js`]
<ide> ].forEach(function(t) {
<del> try { fs.unlinkSync(t[0]); } catch (e) {}
<add> try { fs.unlinkSync(t[0]); } catch {}
<ide> console.log('fs.symlinkSync(%j, %j, %j)', t[1], t[0], 'file');
<ide> fs.symlinkSync(t[1], t[0], 'file');
<ide> unlink.push(t[0]);
<ide> function test_simple_absolute_symlink(realpath, realpathSync, callback) {
<ide> [
<ide> [entry, expected]
<ide> ].forEach(function(t) {
<del> try { fs.unlinkSync(t[0]); } catch (e) {}
<add> try { fs.unlinkSync(t[0]); } catch {}
<ide> console.error('fs.symlinkSync(%j, %j, %j)', t[1], t[0], type);
<ide> fs.symlinkSync(t[1], t[0], type);
<ide> unlink.push(t[0]);
<ide> function test_deep_relative_file_symlink(realpath, realpathSync, callback) {
<ide> expected);
<ide> const linkPath1 = path.join(targetsAbsDir,
<ide> 'nested-index', 'one', 'symlink1.js');
<del> try { fs.unlinkSync(linkPath1); } catch (e) {}
<add> try { fs.unlinkSync(linkPath1); } catch {}
<ide> fs.symlinkSync(linkData1, linkPath1, 'file');
<ide>
<ide> const linkData2 = '../one/symlink1.js';
<ide> const entry = path.join(targetsAbsDir,
<ide> 'nested-index', 'two', 'symlink1-b.js');
<del> try { fs.unlinkSync(entry); } catch (e) {}
<add> try { fs.unlinkSync(entry); } catch {}
<ide> fs.symlinkSync(linkData2, entry, 'file');
<ide> unlink.push(linkPath1);
<ide> unlink.push(entry);
<ide> function test_deep_relative_dir_symlink(realpath, realpathSync, callback) {
<ide> const path1b = path.join(targetsAbsDir, 'nested-index', 'one');
<ide> const linkPath1b = path.join(path1b, 'symlink1-dir');
<ide> const linkData1b = path.relative(path1b, expected);
<del> try { fs.unlinkSync(linkPath1b); } catch (e) {}
<add> try { fs.unlinkSync(linkPath1b); } catch {}
<ide> fs.symlinkSync(linkData1b, linkPath1b, 'dir');
<ide>
<ide> const linkData2b = '../one/symlink1-dir';
<ide> const entry = path.join(targetsAbsDir,
<ide> 'nested-index', 'two', 'symlink12-dir');
<del> try { fs.unlinkSync(entry); } catch (e) {}
<add> try { fs.unlinkSync(entry); } catch {}
<ide> fs.symlinkSync(linkData2b, entry, 'dir');
<ide> unlink.push(linkPath1b);
<ide> unlink.push(entry);
<ide> function test_cyclic_link_protection(realpath, realpathSync, callback) {
<ide> [path.join(tmpDir, '/cycles/realpath-3b'), '../cycles/realpath-3c'],
<ide> [path.join(tmpDir, '/cycles/realpath-3c'), '../cycles/realpath-3a']
<ide> ].forEach(function(t) {
<del> try { fs.unlinkSync(t[0]); } catch (e) {}
<add> try { fs.unlinkSync(t[0]); } catch {}
<ide> fs.symlinkSync(t[1], t[0], 'dir');
<ide> unlink.push(t[0]);
<ide> });
<ide> function test_cyclic_link_overprotection(realpath, realpathSync, callback) {
<ide> const link = `${folder}/cycles`;
<ide> let testPath = cycles;
<ide> testPath += '/folder/cycles'.repeat(10);
<del> try { fs.unlinkSync(link); } catch (ex) {}
<add> try { fs.unlinkSync(link); } catch {}
<ide> fs.symlinkSync(cycles, link, 'dir');
<ide> unlink.push(link);
<ide> assertEqualPath(realpathSync(testPath), path.resolve(expected));
<ide> function test_relative_input_cwd(realpath, realpathSync, callback) {
<ide> ].forEach(function(t) {
<ide> const fn = t[0];
<ide> console.error('fn=%j', fn);
<del> try { fs.unlinkSync(fn); } catch (e) {}
<add> try { fs.unlinkSync(fn); } catch {}
<ide> const b = path.basename(t[1]);
<ide> const type = (b === 'root.js' ? 'file' : 'dir');
<ide> console.log('fs.symlinkSync(%j, %j, %j)', t[1], fn, type);
<ide> function test_deep_symlink_mix(realpath, realpathSync, callback) {
<ide> $tmpDir/targets/cycles/root.js (hard)
<ide> */
<ide> const entry = tmp('node-test-realpath-f1');
<del> try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {}
<del> try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {}
<add> try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch {}
<add> try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch {}
<ide> fs.mkdirSync(tmp('node-test-realpath-d2'), 0o700);
<ide> try {
<ide> [
<ide> function test_deep_symlink_mix(realpath, realpathSync, callback) {
<ide> [`${targetsAbsDir}/nested-index/two/realpath-c`,
<ide> `${tmpDir}/cycles/root.js`]
<ide> ].forEach(function(t) {
<del> try { fs.unlinkSync(t[0]); } catch (e) {}
<add> try { fs.unlinkSync(t[0]); } catch {}
<ide> fs.symlinkSync(t[1], t[0]);
<ide> unlink.push(t[0]);
<ide> });
<ide> function test_abs_with_kids(realpath, realpathSync, cb) {
<ide> ['/a/b/c/x.txt',
<ide> '/a/link'
<ide> ].forEach(function(file) {
<del> try { fs.unlinkSync(root + file); } catch (ex) {}
<add> try { fs.unlinkSync(root + file); } catch {}
<ide> });
<ide> ['/a/b/c',
<ide> '/a/b',
<ide> '/a',
<ide> ''
<ide> ].forEach(function(folder) {
<del> try { fs.rmdirSync(root + folder); } catch (ex) {}
<add> try { fs.rmdirSync(root + folder); } catch {}
<ide> });
<ide> }
<ide> function setup() {
<ide><path>test/parallel/test-listen-fd-detached-inherit.js
<ide> function test() {
<ide> process.kill(child.pid, 'SIGKILL');
<ide> try {
<ide> parent.kill();
<del> } catch (e) {}
<add> } catch {}
<ide>
<ide> assert.strictEqual(s, 'hello from child\n');
<ide> assert.strictEqual(res.statusCode, 200);
<ide><path>test/parallel/test-listen-fd-detached.js
<ide> function test() {
<ide> process.kill(child.pid, 'SIGKILL');
<ide> try {
<ide> parent.kill();
<del> } catch (e) {}
<add> } catch {}
<ide>
<ide> assert.strictEqual(s, 'hello from child\n');
<ide> assert.strictEqual(res.statusCode, 200);
<ide><path>test/parallel/test-listen-fd-ebadf.js
<ide> let invalidFd = 2;
<ide> // Get first known bad file descriptor.
<ide> try {
<ide> while (fs.fstatSync(++invalidFd));
<del>} catch (e) {
<add>} catch {
<ide> // do nothing; we now have an invalid fd
<ide> }
<ide>
<ide><path>test/parallel/test-module-loading-error.js
<ide> if (common.isWindows) {
<ide> try {
<ide> // If MUI != 'en' we'll ignore the content of the message
<ide> localeOk = execSync(powerShellFindMUI).toString('utf8').trim() === 'en';
<del> } catch (_) {
<add> } catch {
<ide> // It's only a best effort try to find the MUI
<ide> }
<ide> }
<ide><path>test/parallel/test-promises-unhandled-rejections.js
<ide> asyncTest('Throwing an error inside a rejectionHandled handler goes to' +
<ide> setTimeout(function() {
<ide> try {
<ide> p.catch(function() {});
<del> } catch (e) {
<add> } catch {
<ide> done(new Error('fail'));
<ide> }
<ide> }, 1);
<ide><path>test/parallel/test-repl-syntax-error-handling.js
<ide> function child() {
<ide> let caught;
<ide> try {
<ide> vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false });
<del> } catch (er) {
<add> } catch {
<ide> caught = true;
<ide> }
<ide> assert(caught);
<ide><path>test/parallel/test-require-deps-deprecation.js
<ide> common.expectWarning('DeprecationWarning', deprecatedModules.map((m) => {
<ide> for (const m of deprecatedModules) {
<ide> try {
<ide> require(m);
<del> } catch (err) {}
<add> } catch {}
<ide> }
<ide>
<ide> // Instead of checking require, check that resolve isn't pointing toward a
<ide><path>test/parallel/test-stdout-close-catch.js
<ide> child.stderr.on('data', function(c) {
<ide> child.on('close', common.mustCall(function(code) {
<ide> try {
<ide> output = JSON.parse(output);
<del> } catch (er) {
<add> } catch {
<ide> console.error(output);
<ide> process.exit(1);
<ide> }
<ide><path>test/parallel/test-stdout-to-file.js
<ide> function test(size, useBuffer, cb) {
<ide>
<ide> try {
<ide> fs.unlinkSync(tmpFile);
<del> } catch (e) {}
<add> } catch {}
<ide>
<ide> console.log(`${size} chars to ${tmpFile}...`);
<ide>
<ide><path>test/parallel/test-vm-low-stack-space.js
<ide> const vm = require('vm');
<ide> function a() {
<ide> try {
<ide> return a();
<del> } catch (e) {
<add> } catch {
<ide> // Throw an exception as near to the recursion-based RangeError as possible.
<ide> return vm.runInThisContext('() => 42')();
<ide> }
<ide> assert.strictEqual(a(), 42);
<ide> function b() {
<ide> try {
<ide> return b();
<del> } catch (e) {
<add> } catch {
<ide> // This writes a lot of noise to stderr, but it still works.
<ide> return vm.runInNewContext('() => 42')();
<ide> }
<ide><path>test/parallel/test-vm-module-errors.js
<ide> async function checkModuleState() {
<ide> const m = new SourceTextModule('import "foo";');
<ide> try {
<ide> await m.link(common.mustCall(() => ({})));
<del> } catch (err) {
<add> } catch {
<ide> assert.strictEqual(m.linkingStatus, 'errored');
<ide> m.instantiate();
<ide> }
<ide> async function checkLinking() {
<ide> const erroredModule = new SourceTextModule('import "foo";');
<ide> try {
<ide> await erroredModule.link(common.mustCall(() => ({})));
<del> } catch (err) {
<add> } catch {
<ide> // ignored
<ide> } finally {
<ide> assert.strictEqual(erroredModule.linkingStatus, 'errored');
<ide><path>test/parallel/test-vm-parse-abort-on-uncaught-exception.js
<ide> const vm = require('vm');
<ide>
<ide> try {
<ide> new vm.Script({ toString() { throw new Error('foo'); } }, {});
<del>} catch (err) {}
<add>} catch {}
<ide>
<ide> try {
<ide> new vm.Script('[', {});
<del>} catch (err) {}
<add>} catch {}
<ide><path>test/pummel/test-fs-watch-non-recursive.js
<ide> const testsubdir = path.join(testDir, 'testsubdir');
<ide> const filepath = path.join(testsubdir, 'watch.txt');
<ide>
<ide> function cleanup() {
<del> try { fs.unlinkSync(filepath); } catch (e) { }
<del> try { fs.rmdirSync(testsubdir); } catch (e) { }
<add> try { fs.unlinkSync(filepath); } catch { }
<add> try { fs.rmdirSync(testsubdir); } catch { }
<ide> }
<ide> process.on('exit', cleanup);
<ide> cleanup();
<ide>
<del>try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {}
<add>try { fs.mkdirSync(testsubdir, 0o700); } catch {}
<ide>
<ide> // Need a grace period, else the mkdirSync() above fires off an event.
<ide> setTimeout(function() {
<ide><path>test/pummel/test-vm-memleak.js
<ide> assert(ok, 'Run this test with --max_old_space_size=32.');
<ide> const interval = setInterval(function() {
<ide> try {
<ide> vm.runInNewContext('throw 1;');
<del> } catch (e) {
<add> } catch {
<ide> }
<ide>
<ide> const rss = process.memoryUsage().rss;
<ide><path>test/pummel/test-vm-race.js
<ide> do {
<ide> try {
<ide> script.runInContext(context, { timeout: 5 });
<ide> ++sandbox.timeout;
<del> } catch (err) {
<add> } catch {
<ide> --sandbox.timeout;
<ide> }
<ide> } while (Date.now() < giveUp);
<ide><path>test/sequential/test-fs-readfile-tostring-fail.js
<ide> stream.on('finish', common.mustCall(function() {
<ide> function destroy() {
<ide> try {
<ide> fs.unlinkSync(file);
<del> } catch (err) {
<add> } catch {
<ide> // it may not exist
<ide> }
<ide> } | 30 |
Text | Text | add an example angular integration | fce3ad23b9f0a8b596385b81bd925120382c2256 | <ide><path>docs/guides/angular.md
<add># Video.js and Angular integration
<add>
<add>Here's a basic Angular player implementation.
<add>
<add>It just instantiates the Video.js player on `OnInit` and destroys it on `OnDestroy`.
<add>
<add>```ts
<add>// vjs-player.component.ts
<add>import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
<add>import videojs from 'video.js';
<add>
<add>@Component({
<add> selector: 'app-vjs-player',
<add> template: `
<add> <video #target class="video-js" controls muted playsinline preload="none"></video>
<add> `,
<add> styleUrls: [
<add> './vjs-player.component.css'
<add> ],
<add> encapsulation: ViewEncapsulation.None,
<add>})
<add>export class VjsPlayerComponent implements OnInit, OnDestroy {
<add> @ViewChild('target') target: ElementRef;
<add> // see options: https://github.com/videojs/video.js/blob/master/docs/guides/options.md
<add> @Input() options: {
<add> fluid: boolean,
<add> aspectRatio: string,
<add> autoplay: boolean,
<add> sources: {
<add> src: string,
<add> type: string,
<add> }[],
<add> };
<add> player: videojs.Player;
<add>
<add> constructor(
<add> private elementRef: ElementRef,
<add> ) { }
<add>
<add> ngOnInit() {
<add> // instantiate Video.js
<add> this.player = videojs(this.target.nativeElement, this.options, function onPlayerReady() {
<add> console.log('onPlayerReady', this);
<add> });
<add> }
<add>
<add> ngOnDestroy() {
<add> // destroy player
<add> if (this.player) {
<add> this.player.dispose();
<add> }
<add> }
<add>}
<add>```
<add>Don't forget to include the Video.js CSS, located at `video.js/dist/video-js.css`.
<add>```css
<add>/* vjs-player.component.css */
<add>@import '~video.js/dist/video-js.css';
<add>```
<add>
<add>You can then use it like this.
<add>
<add>```html
<add><app-vjs-player [options]="{ autoplay: true, controls: true, sources: [{ src: '/path/to/video.mp4', type: 'video/mp4' }]}"></app-vjs-player>
<add>``` | 1 |
Python | Python | fix none tensor check | 36e0a33d85e0ab30ca2f7220a437e80e66e87f18 | <ide><path>keras/layers/convolutional.py
<ide> def compute_output_shape(self, input_shape):
<ide> return tf.TensorShape([input_shape[0], length, input_shape[2]])
<ide>
<ide> def call(self, inputs):
<del> if tf.not_equal(tf.size(inputs), 0) and sum(self.cropping) >= inputs.shape[1]:
<add> if inputs.shape[1] is not None and sum(self.cropping) >= inputs.shape[1]:
<ide> raise ValueError('cropping parameter of Cropping layer must be '
<ide> 'greater than the input shape. Recieved: inputs.shape='
<ide> f'{inputs.shape}, and cropping={self.cropping}') | 1 |
Text | Text | update doc to remove workspaceview | ddb16dcc6f5cdbf4af9b1accce289faa551e48b7 | <ide><path>docs/your-first-package.md
<ide> Register the command in _lib/ascii-art.coffee_:
<ide> ```coffeescript
<ide> module.exports =
<ide> activate: ->
<del> atom.workspaceView.command "ascii-art:convert", => @convert()
<add> atom.commands.add 'atom-workspace', "ascii-art:convert", => @convert()
<ide>
<ide> convert: ->
<ide> # This assumes the active pane item is an editor
<ide> editor = atom.workspace.getActivePaneItem()
<ide> editor.insertText('Hello, World!')
<ide> ```
<ide>
<del>The `atom.workspaceView.command` method takes a command name and a callback. The
<del>callback executes when the command is triggered. In this case, when the command
<del>is triggered the callback will call the `convert` method and insert 'Hello,
<del>World!'.
<add>The `atom.commands.add` method takes a selector, command name, and a callback.
<add>The callback executes when the command is triggered on an element matching the
<add>selector. In this case, when the command is triggered the callback will call the
<add>`convert` method and insert 'Hello, World!'.
<ide>
<ide> ## Reload the Package
<ide> | 1 |
Text | Text | fix typo in building.md | 55cb28026530c8ecf4b813ead91378f71bbd3dc8 | <ide><path>BUILDING.md
<ide> To test if Node.js was built correctly:
<ide> > Release\node -e "console.log('Hello from Node.js', process.version)"
<ide> ```
<ide>
<del>### Android / Android-based devices (e.g., Firefox OS)
<add>### Android / Android-based devices (e.g. Firefox OS)
<ide>
<ide> Although these instructions for building on Android are provided, please note
<ide> that Android is not an officially supported platform at this time. Patches to | 1 |
PHP | PHP | correct doc block | f353f7cc7803ddc88b875b410db9a2a3ad6f04c3 | <ide><path>src/Console/ConsoleOptionParser.php
<ide> class ConsoleOptionParser {
<ide> /**
<ide> * Construct an OptionParser so you can define its behavior
<ide> *
<del> * @param string $command|null The command name this parser is for. The command name is used for generating help.
<add> * @param string|null $command The command name this parser is for. The command name is used for generating help.
<ide> * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
<ide> * this to false will prevent the addition of `--verbose` & `--quiet` options.
<ide> */ | 1 |
Java | Java | remove no-op code in uri encoding | b142f8e66000bbf4ff86866fa47a6941bf06b453 | <ide><path>spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> static String encodeUriComponent(String source, Charset charset, Type type) {
<ide> byte[] bytes = source.getBytes(charset);
<ide> boolean original = true;
<ide> for (byte b : bytes) {
<del> if (b < 0) {
<del> b += 256;
<del> }
<ide> if (!type.isAllowed(b)) {
<ide> original = false;
<ide> break;
<ide> static String encodeUriComponent(String source, Charset charset, Type type) {
<ide>
<ide> ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
<ide> for (byte b : bytes) {
<del> if (b < 0) {
<del> b += 256;
<del> }
<ide> if (type.isAllowed(b)) {
<ide> bos.write(b);
<ide> } | 1 |
PHP | PHP | add methods to docblock for ide completion | 4907553c330784cc273789cb7db35de81a8d1a9c | <ide><path>src/Mailer/Mailer.php
<ide> use Cake\Datasource\ModelAwareTrait;
<ide> use Cake\Event\EventListenerInterface;
<ide> use Cake\Mailer\Exception\MissingActionException;
<del>use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> * Mailer base class.
<ide> * The onRegistration method converts the application event into a mailer method.
<ide> * Our mailer could either be registered in the application bootstrap, or
<ide> * in the Table class' initialize() hook.
<add> *
<add> * @method Email to($email = null, $name = null)
<add> * @method Email from($email = null, $name = null)
<add> * @method Email sender($email = null, $name = null)
<add> * @method Email replyTo($email = null, $name = null)
<add> * @method Email readReceipt($email = null, $name = null)
<add> * @method Email returnPath($email = null, $name = null)
<add> * @method Email addTo($email, $name = null)
<add> * @method Email cc($email = null, $name = null)
<add> * @method Email addCc($email, $name = null)
<add> * @method Email bcc($email = null, $name = null)
<add> * @method Email addBcc($email, $name = null)
<add> * @method Email charset($charset = null)
<add> * @method Email headerCharset($charset = null)
<add> * @method Email subject($subject = null)
<add> * @method Email setHeaders(array $headers)
<add> * @method Email addHeaders(array $headers)
<add> * @method Email getHeaders(array $include = [])
<add> * @method Email template($template = false, $layout = false)
<add> * @method Email viewRender($viewClass = null)
<add> * @method Email viewVars($viewVars = null)
<add> * @method Email theme($theme = null)
<add> * @method Email helpers($helpers = null)
<add> * @method Email emailFormat($format = null)
<add> * @method Email transport($name = null)
<add> * @method Email messageId($message = null)
<add> * @method Email domain($domain = null)
<add> * @method Email attachments($attachments = null)
<add> * @method Email addAttachments($attachments)
<add> * @method Email message($type = null)
<add> * @method Email profile($config = null)
<add> * @method Email send($content = null)
<add> * @method Email reset()
<ide> */
<ide> abstract class Mailer implements EventListenerInterface
<ide> { | 1 |
Python | Python | fix indentation to match args in optimizer classes | 5986eda374a691fe5880ea54c55d935c08259a68 | <ide><path>keras/optimizers/optimizer_experimental/optimizer.py
<ide> def from_config(cls, config):
<ide>
<ide>
<ide> base_optimizer_keyword_args = """name: String. The name to use
<del> for momentum accumulator weights created by
<del> the optimizer.
<del> clipnorm: Float. If set, the gradient of each weight is individually
<del> clipped so that its norm is no higher than this value.
<del> clipvalue: Float. If set, the gradient of each weight is clipped to be no
<del> higher than this value.
<del> global_clipnorm: Float. If set, the gradient of all weights is clipped so
<del> that their global norm is no higher than this value.
<del> use_ema: Boolean, defaults to False. If True, exponential moving average
<del> (EMA) is applied. EMA consists of computing an exponential moving
<del> average of the weights of the model (as the weight values change after
<del> each training batch), and periodically overwriting the weights with
<del> their moving average.
<del> ema_momentum: Float, defaults to 0.99. Only used if `use_ema=True`. This is
<del> the momentum to use when computing the EMA of the model's weights:
<del> `new_average = ema_momentum * old_average + (1 - ema_momentum) *
<del> current_variable_value`.
<del> ema_overwrite_frequency: Int or None, defaults to None. Only used if
<del> `use_ema=True`. Every `ema_overwrite_frequency` steps of iterations, we
<del> overwrite the model variable by its moving average. If None, the optimizer
<del> does not overwrite model variables in the middle of training, and you
<del> need to explicitly overwrite the variables at the end of training
<del> by calling `optimizer.finalize_variable_values()` (which updates the model
<del> variables in-place). When using the built-in `fit()` training loop, this
<del> happens automatically after the last epoch, and you don't need to do
<del> anything.
<del> jit_compile: Boolean, defaults to True. If True, the optimizer will use XLA
<del> compilation. If no GPU device is found, this flag will be ignored.
<del> **kwargs: keyword arguments only used for backward compatibility."""
<add> for momentum accumulator weights created by
<add> the optimizer.
<add> clipnorm: Float. If set, the gradient of each weight is individually
<add> clipped so that its norm is no higher than this value.
<add> clipvalue: Float. If set, the gradient of each weight is clipped to be no
<add> higher than this value.
<add> global_clipnorm: Float. If set, the gradient of all weights is clipped so
<add> that their global norm is no higher than this value.
<add> use_ema: Boolean, defaults to False. If True, exponential moving average
<add> (EMA) is applied. EMA consists of computing an exponential moving
<add> average of the weights of the model (as the weight values change after
<add> each training batch), and periodically overwriting the weights with
<add> their moving average.
<add> ema_momentum: Float, defaults to 0.99. Only used if `use_ema=True`. This is
<add> the momentum to use when computing the EMA of the model's weights:
<add> `new_average = ema_momentum * old_average + (1 - ema_momentum) *
<add> current_variable_value`.
<add> ema_overwrite_frequency: Int or None, defaults to None. Only used if
<add> `use_ema=True`. Every `ema_overwrite_frequency` steps of iterations, we
<add> overwrite the model variable by its moving average. If None, the optimizer
<add> does not overwrite model variables in the middle of training, and you
<add> need to explicitly overwrite the variables at the end of training
<add> by calling `optimizer.finalize_variable_values()` (which updates the model
<add> variables in-place). When using the built-in `fit()` training loop, this
<add> happens automatically after the last epoch, and you don't need to do
<add> anything.
<add> jit_compile: Boolean, defaults to True. If True, the optimizer will use XLA
<add> compilation. If no GPU device is found, this flag will be ignored.
<add> **kwargs: keyword arguments only used for backward compatibility."""
<ide>
<ide>
<ide> # pylint: disable=g-classes-have-attributes | 1 |
PHP | PHP | allow utf8mb4 characters in the url | ccdbbe1f344bd8072b9f645c1e1a55178d9c3ec3 | <ide><path>src/Validation/Validation.php
<ide> public static function range($check, $lower = null, $upper = null)
<ide> public static function url($check, $strict = false)
<ide> {
<ide> static::_populateIp();
<del> $alpha = '0-9\p{L}\p{N}';
<add>
<add> $emoji = '\x{1F300}-\x{1F6FF}';
<add> $alpha = '0-9(\p{L}\p{N}' . $emoji;
<ide> $hex = '(%[0-9a-f]{2})';
<ide> $subDelimiters = preg_quote('/!"$&\'()*+,-.@_:;=~[]', '/');
<ide> $path = '([' . $subDelimiters . $alpha . ']|' . $hex . ')';
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testUrl()
<ide> $this->assertTrue(Validation::url('http://www.electrohome.ro/images/239537750-284232-215_300[1].jpg'));
<ide> $this->assertTrue(Validation::url('http://www.eräume.foo'));
<ide> $this->assertTrue(Validation::url('http://äüö.eräume.foo'));
<add> $this->assertTrue(Validation::url('http://www.domain.com/👹'), 'utf8Extended path failed');
<ide>
<ide> $this->assertTrue(Validation::url('http://cakephp.org:80'));
<ide> $this->assertTrue(Validation::url('http://cakephp.org:443')); | 2 |
Text | Text | add api challenges - arabic translation | 18022f78bbc6d13e03e4767f79deef9a15ca9364 | <ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.arabic.md
<add>---
<add>id: 5a8b073d06fa14fcfde687aa
<add>title: Exercise Tracker
<add>localeTitle: متتبع التمرين
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إنشاء تطبيق جافا سكريبت كامل للمكدس يشبه وظيفيًا ما يلي: <a href='https://fuschia-custard.glitch.me/' target='_blank'>https://fuschia-custard.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-exercisetracker/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني إنشاء مستخدم عن طريق نشر اسم مستخدم بيانات النموذج إلى / api / exercise / new-user وسيتم إرجاع كائن باسم المستخدم و <code>_id</code> .
<add> testString: ''
<add> - text: يمكنني الحصول على مجموعة من جميع المستخدمين عن طريق الحصول على api / exercise / users مع نفس المعلومات عند إنشاء مستخدم.
<add> testString: ''
<add> - text: "يمكنني إضافة تمرين إلى أي مستخدم عن طريق نشر بيانات userId (_id) ، والوصف ، والمدة ، والتاريخ الاختياري إلى / api / exercise / add. إذا لم يتم تقديم تاريخ ، فسيستخدم التاريخ الحالي. سيعرض التطبيق كائن المستخدم مع إضافة حقول التمرين ".
<add> testString: ''
<add> - text: يمكنني استرداد سجل تمرين كامل لأي مستخدم من خلال الحصول على / api / exercise / log بمعلمة userId (_id). سيقوم التطبيق بإرجاع كائن المستخدم مع سجل صفيف المضافة وعدد (العدد الكلي للتمرين).
<add> testString: ''
<add> - text: "يمكنني استرداد جزء من سجل أي مستخدم عن طريق تمرير المعلمات الاختيارية من وإلى أو الحد. (تنسيق التاريخ yyyy-mm-dd ، limit = int) "
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bd0f
<add>title: File Metadata Microservice
<add>localeTitle: الملف الفوقية ميكروسيرفيسي
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا ما يلي: <a href='https://purple-paladin.glitch.me/' target='_blank'>https://purple-paladin.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-filemetadata/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-filemetadata/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني إرسال كائن FormData يتضمن تحميل ملف.
<add> testString: ''
<add> - text: "عند إرسال شيء ما ، سأتلقى حجم الملف بالبايت ضمن استجابة JSON".
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bdff
<add>title: Request Header Parser Microservice
<add>localeTitle: طلب رأس محلل ميكروسيرفيسي
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا هذا: <a href='https://dandelion-roar.glitch.me/' target='_blank'>https://dandelion-roar.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-headerparser/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-headerparser/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يمكنني الحصول على عنوان IP ولغة ونظام التشغيل لمتصفحي."
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/timestamp-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bdef
<add>title: Timestamp Microservice
<add>localeTitle: Timestamp Microservice
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا ما يلي: <a href='https://curse-arrow.glitch.me/' target='_blank'>https://curse-arrow.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-timestamp/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-timestamp/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يجب أن يتعامل مع تاريخ صالح ، ويعيد الطابع الزمني الصحيح لـ unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.unix, 1482624000000, ''Should be a valid unix timestamp''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع تاريخ صالح ، وإرجاع سلسلة UTC الصحيحة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'')+ ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.utc, ''Sun, 25 Dec 2016 00:00:00 GMT'', ''Should be a valid UTC date string''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع تاريخ unix صالح ، ويعيد الطابع الزمني الصحيح لـ unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/1482624000000'').then(data => { assert.equal(data.unix, 1482624000000) ; }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن ترجع رسالة الخطأ المتوقعة لتاريخ غير صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/this-is-not-a-date'').then(data => { assert.equal(data.error.toLowerCase(), ''invalid date'');}, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب معالجة معلمة تاريخ فارغة ، وإرجاع الوقت الحالي بتنسيق unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); assert.approximately(data.unix, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع معلمة تاريخ فارغة ، وإرجاع الوقت الحالي بتنسيق UTC"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); var serverTime = (new Date(data.utc)).getTime(); assert.approximately(serverTime, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bd0e
<add>title: URL Shortener Microservice
<add>localeTitle: URL Shortener Microservice
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا هذا: <a href='https://thread-paper.glitch.me/' target='_blank'>https://thread-paper.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-urlshortener/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-urlshortener/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني تمرير عنوان URL كمعلمة وسيتلقى عنوان URL مختصرًا في استجابة JSON.
<add> testString: ''
<add> - text: "إذا قمت بتمرير عنوان URL غير صالح لا يتبع تنسيق http://www.example.com الصالح ، فستتضمن استجابة JSON خطأً بدلاً من ذلك".
<add> testString: ''
<add> - text: "عندما أزور عنوان URL المختصر هذا ، سيعيد توجيهي إلى الرابط الأصلي."
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf4
<add>title: Chain Middleware to Create a Time Server
<add>localeTitle: سلسلة Middleware لإنشاء خادم الوقت
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الوسيطة يمكن تركيبه في مسار محدد باستخدام <code>app.METHOD(path, middlewareFunction)</code> . الوسيطة يمكن أيضا أن تكون بالسلاسل داخل تعريف الطريق.
<add>انظر إلى المثال التالي:
<add><blockquote style=";text-align:right;direction:rtl">app.get('/user', function(req, res, next) {<br> req.user = getTheUserSync(); // Hypothetical synchronous operation<br> next();<br>}, function(req, res) {<br> res.send(req.user);<br>})</blockquote>
<add>هذه الطريقة مفيدة لتقسيم عمليات الخادم إلى وحدات أصغر. وهذا يؤدي إلى بنية أفضل للتطبيق ، وإمكانية إعادة استخدام الرمز في أماكن مختلفة. يمكن استخدام هذا الأسلوب أيضًا لإجراء بعض التحقق من صحة البيانات. في كل نقطة من مكدس البرامج الوسيطة يمكنك منع تنفيذ التحكم في السلسلة والسلسة الحالية إلى وظائف مصممة خصيصًا للتعامل مع الأخطاء. أو يمكنك تمرير التحكم إلى المسار المطابق التالي ، للتعامل مع الحالات الخاصة. سنرى كيف في قسم Express المتقدمة.
<add>في مسار <code>app.get('/now', ...)</code> سلسلة وظيفة الوسيطة والمعالج النهائي. في وظيفة الوسيطة ، يجب إضافة الوقت الحالي إلى كائن الطلب في مفتاح <code>req.time</code> . يمكنك استخدام <code>new Date().toString()</code> . في المعالج ، <code>{time: req.time}</code> باستخدام كائن JSON ، مع أخذ البنية <code>{time: req.time}</code> .
<add>تلميح: لن يمر الاختبار إذا لم تقم بربط الوسيطة. إذا قمت بتركيب الوظيفة في مكان آخر ، سيفشل الاختبار ، حتى إذا كانت نتيجة الإخراج صحيحة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يكون نقطة النهاية / الآن الوسيطة المثبتة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { assert.equal(data.stackLength, 2, ''"/now" route has no mounted middleware''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن تقوم نقطة النهاية / الآن بإرجاع وقت يكون +/- 20 ثانية من الآن
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { var now = new Date(); assert.isAtMost(Math.abs(new Date(data.time) - now), 20000, ''the returned time is not between +- 20 secs from now''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-data-from-post-requsts.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf8
<add>title: Get Data from POST Requests
<add>localeTitle: الحصول على البيانات من طلبات POST
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بتحميل معالج POST على المسار <code>/name</code> . انها نفس الطريق كما كان من قبل. قمنا بإعداد نموذج في صفحة HTML الأمامية. وسوف يقدم نفس البيانات من التمرين 10 (سلسلة الاستعلام). إذا تم تكوين محلل الجسم بشكل صحيح ، يجب أن تجد المعلمات في الكائن <code>req.body</code> . إلقاء نظرة على المثال المعتاد للمكتبة:
<add><blockquote style=";text-align:right;direction:rtl">route: POST '/library'<br>urlencoded_body: userId=546&bookId=6754 <br>req.body: {userId: '546', bookId: '6754'}</blockquote>
<add>رد باستخدام نفس كائن JSON كما كان من قبل: <code>{name: 'firstname lastname'}</code> . اختبر إذا كانت نقطة النهاية تعمل باستخدام نموذج html الذي قدمناه في صفحة التطبيق الأولى.
<add>نصيحة: هناك العديد من طرق http الأخرى بخلاف GET و POST. وبموجب الاتفاقية هناك تناظر بين الفعل http ، والعملية التي ستنفذها على الخادم. التعيين التقليدي هو:
<add>POST (أحيانًا PUT) - إنشاء مورد جديد باستخدام المعلومات المرسلة مع الطلب ،
<add>GET - قراءة مورد موجود بدون تعديله ،
<add>PUT أو PATCH (أحيانًا POST) - تحديث مورد باستخدام البيانات تم الإرسال ،
<add>DELETE => حذف مورد.
<add>هناك أيضًا طريقتين أخريين تستخدمان للتفاوض على اتصال بالخادم. باستثناء GET ، يمكن أن تحتوي جميع الطرق الأخرى المذكورة أعلاه على حمولة (أي البيانات في نص الطلب). يعمل الوسيطة محلل الجسم مع هذه الأساليب كذلك.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Mick'', last: ''Jagger''}).then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Keith'', last: ''Richards''}).then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf6
<add>title: Get Query Parameter Input from the Client
<add>localeTitle: الحصول على إدخال معلمة طلب البحث من العميل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>طريقة شائعة أخرى للحصول على مدخلات من العميل هي بتشفير البيانات بعد مسار المسار ، باستخدام سلسلة استعلام. تكون سلسلة الاستعلام محددة بعلامة استفهام (؟) ، وتتضمن أزواج الحقل = القيمة. يتم فصل كل زوجين بواسطة علامة العطف (&). يمكن لـ Express تحليل البيانات من سلسلة الاستعلام ، <code>req.query</code> الكائن <code>req.query</code> . لا يمكن أن تكون بعض الأحرف في عناوين URL ، يجب أن يتم ترميزها <a href='https://en.wikipedia.org/wiki/Percent-encoding' target='_blank'>بتنسيق مختلف</a> قبل أن تتمكن من إرسالها. إذا كنت تستخدم واجهة برمجة التطبيقات من جافا سكريبت ، فيمكنك استخدام طرق محددة لتشفير / فك تشفير هذه الأحرف.
<add><blockquote style=";text-align:right;direction:rtl">route_path: '/library'<br>actual_request_URL: '/library?userId=546&bookId=6754' <br>req.query: {userId: '546', bookId: '6754'}</blockquote>
<add>إنشاء نقطة نهاية API ، محملة على <code>GET /name</code> . الرد باستخدام مستند JSON ، مع أخذ البنية <code>{ name: 'firstname lastname'}</code> . يجب ترميز معلمات الاسم الأول والأخير في سلسلة استعلام على سبيل المثال: <code>?first=firstname&last=lastname</code> .
<add>نصيحة: سنقوم في التمرين التالي بتلقي بيانات من طلب POST ، على نفس مسار مسار <code>/name</code> . إذا كنت تريد يمكنك استخدام الطريقة <code>app.route(path).get(handler).post(handler)</code> . تسمح لك هذه البنية بسلسلة معالجات الأفعال المختلفة على نفس مسار المسار. يمكنك حفظ جزء من الكتابة ، والحصول على رمز أنظف.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?first=Mick&last=Jagger'').then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن تستجيب نقطة نهاية APi الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?last=Richards&first=Keith'').then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-route-parameter-input-from-the-client.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf5
<add>title: Get Route Parameter Input from the Client
<add>localeTitle: الحصول على إدخال معلمة المسار من العميل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>عند إنشاء واجهة برمجة التطبيقات ، يتعين علينا السماح للمستخدمين بالاتصال بنا بما يريدون الحصول عليه من خدمتنا. على سبيل المثال ، إذا كان العميل يطلب معلومات حول مستخدم مخزّن في قاعدة البيانات ، فيحتاج إلى طريقة لإعلامنا بالمستخدم الذي يهتم به. تتمثل إحدى الطرق الممكنة لتحقيق هذه النتيجة في استخدام معلمات المسار. تدعى معلمات المسار أجزاء من عنوان URL ، مفصولة بشرائط مائلة (/). يلتقط كل مقطع قيمة جزء عنوان URL الذي يطابق موقعه. يمكن العثور على القيم التي تم التقاطها في كائن <code>req.params</code> .
<add><blockquote style=";text-align:right;direction:rtl">route_path: '/user/:userId/book/:bookId'<br>actual_request_URL: '/user/546/book/6754' <br>req.params: {userId: '546', bookId: '6754'}</blockquote>
<add>إنشاء ملقم صدى ، التي شنت على الطريق <code>GET /:word/echo</code> . الرد باستخدام كائن JSON ، مع أخذ بنية <code>{echo: word}</code> . يمكنك العثور على الكلمة المراد تكرارها على <code>req.params.word</code> . يمكنك اختبار مسارك من شريط العناوين بالمتصفح ، وزيارة بعض المسارات المطابقة ، على سبيل المثال your-app-rootpath / freecodecamp / echo
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن يكرر خادم الصدى الكلمات بشكل صحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/eChOtEsT/echo'').then(data => { assert.equal(data.echo, ''eChOtEsT'', ''Test 1: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن يكرر خادم الصدى الكلمات بشكل صحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/ech0-t3st/echo'').then(data => { assert.equal(data.echo, ''ech0-t3st'', ''Test 2: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf3
<add>title: Implement a Root-Level Request Logger Middleware
<add>localeTitle: تنفيذ برنامج Logware Logger Logger على مستوى الجذر
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>قبل أن نقدم وظيفة الوسيطة <code>express.static()</code> . الآن حان الوقت لنرى ما هي الوسيطة ، بمزيد من التفصيل. دالات الوسيطية هي الدوال التي تأخذ 3 حجج: كائن الطلب ، كائن الاستجابة ، والدالة التالية في دورة طلب-استجابة التطبيق. هذه الوظائف تنفيذ بعض التعليمات البرمجية التي يمكن أن يكون لها آثار جانبية على التطبيق ، وعادة ما تضيف المعلومات إلى الكائنات استجابة أو طلب. يمكنهم أيضًا إنهاء دورة إرسال الاستجابة ، عند استيفاء بعض الشروط. إذا لم يرسلوا الاستجابة ، فعند الانتهاء من ذلك ، يبدأون تنفيذ الوظيفة التالية في المكدس. يتم تشغيل هذا استدعاء الوسيطة الثالثة <code>next()</code> . مزيد من المعلومات في <a href='http://expressjs.com/en/guide/using-middleware.html' target='_blank'>الوثائق السريعة</a> .
<add>انظر إلى المثال التالي:
<add><blockquote style=";text-align:right;direction:rtl">function(req, res, next) {<br> console.log("I'm a middleware...");<br> next();<br>}</blockquote>
<add>دعونا نفترض أننا شنت هذه الوظيفة على الطريق. عندما يطابق أحد الطلبات المسار ، فإنه يعرض السلسلة "أنا برنامج وسيط ...". ثم ينفذ الوظيفة التالية في المكدس.
<add>في هذا التمرين ، سنقوم ببناء برنامج وسيط بمستوى الجذر. كما رأينا في التحدي 4 ، لتركيب وظيفة الوسيطة على مستوى الجذر يمكننا استخدام طريقة <code>app.use(<mware-function>)</code> . في هذه الحالة ، سيتم تنفيذ الوظيفة لجميع الطلبات ، ولكن يمكنك أيضًا تعيين شروط أكثر تحديدًا. على سبيل المثال ، إذا كنت تريد تنفيذ دالة فقط لطلبات POST ، فيمكنك استخدام <code>app.post(<mware-function>)</code> . توجد أساليب مماثلة لجميع الأفعال http (GET، DELETE، PUT،…).
<add>بناء بسيط المسجل. لكل طلب ، يجب عليه تسجيل الدخول في وحدة التحكم سلسلة أخذ التنسيق التالي: <code>method path - ip</code> . قد يبدو المثال: <code>GET /json - ::ffff:127.0.0.1</code> . لاحظ أن هناك مسافة بين <code>method</code> و <code>path</code> وأن اندفاعة فصل <code>path</code> و <code>ip</code> وتحيط به مساحة على جانبي. يمكنك الحصول على طريقة الطلب (الفعل المتشعب) ، ومسار المسار النسبي ، <code>req.method</code> المتصل من كائن الطلب ، باستخدام <code>req.method</code> ، <code>req.path</code> و <code>req.ip</code> تذكر الاتصال <code>next()</code> عند الانتهاء ، أو أن الخادم الخاص بك سيكون عالقاً إلى الأبد. تأكد من فتح "السجلات" ، وشاهد ما سيحدث عند وصول بعض الطلبات ...
<add>تلميح: يقوم Express بتقييم الوظائف بالترتيب الذي تظهر به في التعليمة البرمجية. هذا صحيح على الوسيطة أيضا. إذا كنت تريد أن تعمل في جميع المسارات ، فيجب تثبيتها قبلها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تكون البرامج الوسيطة لمسجل المستوى الجذر نشطة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/root-middleware-logger'').then(data => { assert.isTrue(data.passed, ''root-level logger is not working as expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bed
<add>title: Meet the Node console
<add>localeTitle: تعرف على وحدة التحكم في العقدة
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>أثناء عملية التطوير ، من المهم أن تكون قادراً على التحقق من ما يجري في التعليمات البرمجية. العقدة هي مجرد بيئة جافا سكريبت. مثل جافا سكريبت من جانب العميل ، يمكنك استخدام وحدة التحكم لعرض معلومات تصحيح الأخطاء المفيدة. على جهازك المحلي ، سترى إخراج وحدة التحكم في جهاز طرفي. على خلل ، يمكنك فتح السجلات في الجزء السفلي من الشاشة. يمكنك تبديل لوحة السجل بزر "سجلات" الزر (أعلى اليسار ، تحت اسم التطبيق).
<add>للبدء ، ما عليك سوى طباعة "Hello World" الكلاسيكية في وحدة التحكم. نوصي بإبقاء لوحة السجلات مفتوحة أثناء العمل على مواجهة هذه التحديات. قراءة السجلات يمكنك أن تكون على علم بطبيعة الأخطاء التي قد تحدث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>قم بتعديل الملف <code>myApp.js</code> لتسجيل "Hello World" إلى وحدة التحكم.
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يكون <code>"Hello World"</code> في وحدة التحكم
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/hello-console'').then(data => { assert.isTrue(data.passed, ''"Hello World" is not in the server console''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-an-html-file.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bef
<add>title: Serve an HTML File
<add>localeTitle: تخدم ملف HTML
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يمكننا الرد باستخدام ملف باستخدام الطريقة <code>res.sendFile(path)</code> .
<add>يمكنك وضعه داخل <code>app.get('/', ...)</code> توجيه <code>app.get('/', ...)</code> . وراء الكواليس ، تقوم هذه الطريقة بتعيين الرؤوس المناسبة لإرشاد المتصفح الخاص بك حول كيفية التعامل مع الملف الذي تريد إرساله ، وفقًا لنوعه. ثم سوف يقرأ ويرسل الملف. هذه الطريقة تحتاج إلى مسار ملف مطلق. نوصي باستخدام المتغير العام <code>__dirname</code> لحساب المسار.
<add>سبيل المثال <code>absolutePath = __dirname + relativePath/file.ext</code> .
<add>الملف المطلوب إرساله هو <code>/views/index.html</code> . جرِّب "إظهار تطبيقك" ، يجب أن تشاهد عنوان HTML كبيرًا (ونموذجًا سنستخدمه لاحقًا ...) ، دون تطبيق أي أسلوب.
<add>ملاحظة: يمكنك تحرير حل التحدي السابق ، أو إنشاء حل جديد. إذا قمت بإنشاء حل جديد ، فضع في اعتبارك أن Express يقيم المسارات من الأعلى إلى الأسفل. ينفذ المعالج للمباراة الأولى. يجب عليك التعليق على الحل السابق ، أو سيستمر الخادم في الاستجابة باستخدام سلسلة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك ملف المشاهدات / index.html
<add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.match(data, /<h1>.*<\/h1>/, ''Your app does not serve the expected HTML''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-json-on-a-specific-route.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf1
<add>title: Serve JSON on a Specific Route
<add>localeTitle: خدمة JSON على طريق معين
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بينما يخدم خادم HTML (الذي خمنته!) HTML ، فإن واجهة برمجة التطبيقات تخدم البيانات. تسمح واجهة برمجة التطبيقات (Rpresentational State Transfer) <dfn>REST</dfn> بتبادل البيانات بطريقة بسيطة ، دون الحاجة إلى معرفة العملاء لأي تفاصيل حول الخادم. يحتاج العميل فقط إلى معرفة مصدر المورد (عنوان URL) والإجراء الذي يريد تنفيذه عليه (الفعل). يتم استخدام الفعل GET عندما تقوم بجلب بعض المعلومات ، دون تعديل أي شيء. في هذه الأيام ، يكون تنسيق البيانات المفضل لنقل المعلومات عبر الويب هو JSON. ببساطة ، JSON هي طريقة ملائمة لتمثيل كائن JavaScript كسلسلة ، بحيث يمكن نقله بسهولة.
<add>لنقم بإنشاء واجهة برمجة تطبيقات بسيطة عن طريق إنشاء مسار يستجيب مع JSON على المسار <code>/json</code> . يمكنك القيام بذلك كالمعتاد ، مع طريقة <code>app.get()</code> . داخل معالج المسار ، استخدم الطريقة <code>res.json()</code> ، وتمريرها في كائن كوسيطة. تغلق هذه الطريقة حلقة الطلب-الاستجابة ، وتعيد البيانات. وراء الكواليس ، يقوم بتحويل كائن جافا سكريبت صالح إلى سلسلة ، ثم يقوم بتعيين الرؤوس المناسبة لإخبار المتصفح أنك تخدم JSON ، ويرسل البيانات مرة أخرى. يحتوي الكائن الصحيح على البنية المعتادة <code>{key: data}</code> . يمكن البيانات با رقم ، سلسلة ، كائن متداخل أو مصفوفة. يمكن أن تكون البيانات أيضًا متغيرًا أو نتيجة استدعاء دالة ؛ في هذه الحالة سيتم تقييمه قبل تحويله إلى سلسلة.
<add>خدمة الكائن <code>{"message": "Hello json"}</code> كاستجابة في تنسيق JSON ، إلى طلبات GET إلى المسار <code>/json</code> . ثم أشر المتصفح الخاص بك إلى التطبيق الخاص بك-رابط / json ، يجب أن تشاهد الرسالة على الشاشة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يجب أن تخدم نقطة النهاية <code>/json</code> كائن json <code>{"message": "Hello json"}</code> "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/json'').then(data => { assert.equal(data.message, ''Hello json'', ''The \''/json\'' endpoint does not serve the right data''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-static-assets.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bf0
<add>title: Serve Static Assets
<add>localeTitle: خدمة الأصول الثابتة
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يحتوي خادم HTML عادة على واحد أو أكثر من الدلائل التي يمكن الوصول إليها من قبل المستخدم. يمكنك وضع الأصول الثابتة التي يحتاج إليها التطبيق الخاص بك (أوراق الأنماط ، البرامج النصية ، الصور). في Express يمكنك وضع هذه الوظيفة باستخدام الوسيطة <code>express.static(path)</code> ، حيث تكون المعلمة هي المسار المطلق للمجلد الذي يحتوي على الأصول. إذا كنت لا تعرف ما هي الوسيطة ، فلا تقلق. سنناقشها فيما بعد بالتفصيل. في المقام الأول الوسيطة هي وظائف تعترض معالجات الطريق ، تضيف نوعا من المعلومات. تحتاج الوسيطة <code>app.use(path, middlewareFunction)</code> باستخدام طريقة <code>app.use(path, middlewareFunction)</code> . وسيطة المسار الأول اختيارية. إذا لم تنجح ، سيتم تنفيذ الوسيطة لجميع الطلبات.
<add><code>app.use()</code> البرامج الوسيطة <code>express.static()</code> لكافة الطلبات باستخدام <code>app.use()</code> . المسار المطلق لمجلد الأصول هو <code>__dirname + /public</code> .
<add>يجب أن يكون تطبيقك الآن قادرًا على تقديم ورقة أنماط CSS. من خارج المجلد العام سوف تظهر محملة إلى الدليل الجذر. من المفترض أن تبدو صفحتك الأولى أفضل قليلاً الآن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك ملفات مواد العرض من الدليل <code>/public</code>
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/style.css'').then(data => { assert.match(data, /body\s*\{[^\}]*\}/, ''Your app does not serve static assets''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/start-a-working-express-server.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bee
<add>title: Start a Working Express Server
<add>localeTitle: بدء تشغيل ملقم Express العمل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في أول سطرين من الملف myApp.js يمكنك أن ترى كيف أنه من السهل إنشاء كائن تطبيق Express. يحتوي هذا الكائن على عدة طرق ، وسوف نتعلم الكثير منها في هذه التحديات. إحدى الطرق الأساسية هي <code>app.listen(port)</code> . فإنه يخبر الخادم الخاص بك للاستماع على منفذ معين ، ووضعها في حالة تشغيل. يمكنك رؤيتها في أسفل الملف. من داخل التعليقات لأننا نحتاج إلى تشغيل التطبيق في الخلفية لأسباب اختبار. كل التعليمات البرمجية التي قد ترغب في إضافتها تنتقل بين هذين الجزأين الأساسيين. يقوم Glitch بتخزين رقم المنفذ في <code>process.env.PORT</code> متغير البيئة. قيمتها <code>3000</code> .
<add>دعونا نخدم أول سلسلة لدينا! في Express ، تأخذ المسارات البنية التالية: <code>app.METHOD(PATH, HANDLER)</code> . الطريقة هي طريقة http في الأحرف الصغيرة. PATH هو مسار نسبي على الخادم (يمكن أن يكون عبارة عن سلسلة أو حتى تعبير عادي). HANDLER هي وظيفة يقوم Express باستدعاءها عند مطابقة المسار.
<add>تأخذ معالجات <code>function(req, res) {...}</code> الشكل <code>function(req, res) {...}</code> ، حيث req هي كائن الطلب ، و res هو كائن الاستجابة. على سبيل المثال ، المعالج
<add><blockquote style=";text-align:right;direction:rtl">function(req, res) {<br> res.send('Response String');<br>}</blockquote>
<add>سيخدم السلسلة "سلسلة الاستجابة".
<add>استخدم طريقة <code>app.get()</code> لعرض سلسلة Hello Express ، لطلبات GET التي تطابق مسار / root. تأكد من عمل التعليمات البرمجية الخاصة بك بالنظر إلى السجلات ، ثم انظر النتائج في المستعرض الخاص بك ، والنقر فوق الزر 'إظهار Live' في واجهة المستخدم Glitch UI.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك السلسلة "Hello Express"
<add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.equal(data, ''Hello Express'', ''Your app does not serve the text "Hello Express"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf7
<add>title: Use body-parser to Parse POST Requests
<add>localeTitle: استخدام محلل body to Parse POST الطلبات
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بالإضافة إلى GET هناك فعل http شائع آخر ، هو POST. POST هي الطريقة الافتراضية المستخدمة لإرسال بيانات العميل بنماذج HTML. في REST convention يستخدم POST لإرسال البيانات لإنشاء عناصر جديدة في قاعدة البيانات (مستخدم جديد ، أو مشاركة مدونة جديدة). لا توجد لدينا قاعدة بيانات في هذا المشروع ، لكننا سنتعلم كيفية التعامل مع طلبات POST على أي حال.
<add>في هذا النوع من الطلبات لا تظهر البيانات في عنوان URL ، تكون مخفية في نص الطلب. هذا جزء من طلب HTML ، ويسمى أيضًا الحمولة. نظرًا لأن HTML يعتمد على النص ، حتى إذا لم تكن ترى البيانات ، فهذا لا يعني أنها سرية. يتم عرض المحتوى الأساسي لطلب HTTP POST أدناه:
<add><blockquote style=";text-align:right;direction:rtl">POST /path/subpath HTTP/1.0<br>From: john@example.com<br>User-Agent: someBrowser/1.0<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 20<br>name=John+Doe&age=25</blockquote>
<add>كما ترى ، يتم تشفير الجسم مثل سلسلة الاستعلام. هذا هو التنسيق الافتراضي المستخدم في نماذج HTML. مع Ajax يمكننا أيضا استخدام JSON لتكون قادرة على التعامل مع البيانات التي لديها بنية أكثر تعقيدا. هناك أيضًا نوع آخر من الترميز: multipart / form-data. هذا واحد يستخدم لتحميل الملفات الثنائية.
<add>في هذا التمرين ، سنستخدم هيئة urlencoded.
<add>لتحليل البيانات الواردة من طلبات POST ، يجب عليك تثبيت حزمة: محلل الجسم. تتيح لك هذه الحزمة استخدام سلسلة من البرامج الوسيطة ، والتي يمكن أن تفك شفرة البيانات بتنسيقات مختلفة. شاهد المستندات <a href="https://github.com/expressjs/body-parser" target="_blank" >هنا</a> .
<add>قم بتثبيت وحدة تحليل الجسم في الحزمة. json. ثم تطلب ذلك في الجزء العلوي من الملف. قم بتخزينه في متغير اسمه bodyParser.
<add>يتم إرجاع الوسيطة لمعالجة البيانات المشفرة بواسطة <code>bodyParser.urlencoded({extended: false})</code> . <code>extended=false</code> هو خيار تكوين يخبر المحلل باستخدام التشفير التقليدي. عند استخدامه ، يمكن أن تكون القيم سلاسل أو صفائف فقط. النسخة الموسعة تسمح بمرونة أكبر للبيانات ، ولكن يفوقها JSON. تمرير إلى <code>app.use()</code> الدالة التي تم إرجاعها بواسطة استدعاء الأسلوب السابق. كالعادة ، يجب تركيب الوسيطة قبل كل الطرق التي تحتاجها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب تركيب الوسيطة 'body-parser'
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/add-body-parser'').then(data => { assert.isAbove(data.mountedAt, 0, ''"body-parser" is not mounted correctly'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf2
<add>title: Use the .env File
<add>localeTitle: استخدم ملف .env
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الملف <code>.env</code> عبارة عن ملف مخفي يستخدم لتمرير متغيرات البيئة إلى التطبيق الخاص بك. هذا الملف سري ، لا أحد ولكن يمكنك الوصول إليه ، ويمكن استخدامه لتخزين البيانات التي تريد الاحتفاظ بها خاصة أو مخفية. على سبيل المثال ، يمكنك تخزين مفاتيح API من الخدمات الخارجية أو عنوان URI الخاص بقاعدة البيانات. يمكنك أيضًا استخدامه لتخزين خيارات التهيئة. عن طريق إعداد خيارات التكوين ، يمكنك تغيير سلوك التطبيق الخاص بك ، دون الحاجة إلى إعادة كتابة بعض التعليمات البرمجية.
<add>يمكن الوصول إلى متغيرات البيئة من التطبيق مثل <code>process.env.VAR_NAME</code> . الكائن <code>process.env</code> هو كائن عقدة عمومي ، ويتم تمرير المتغيرات كسلسلة. حسب الاصطلاح ، أسماء المتغيرات كلها أحرف كبيرة ، مع الكلمات مفصولة تسطير سفلي. <code>.env</code> عبارة عن ملف shell ، لذلك لا تحتاج إلى التفاف الأسماء أو القيم بين علامتي اقتباس. من المهم أيضًا ملاحظة أنه لا يمكن توفير مسافة حول علامة equals عند تعيين قيم للمتغيرات ، مثل <code>VAR_NAME=value</code> . عادة ، ستضع كل تعريف متغير على سطر منفصل.
<add>دعونا إضافة متغير بيئة كخيار التكوين. قم بتخزين متغير <code>MESSAGE_STYLE=uppercase</code> في ملف <code>.env</code> . ثم أخبر معالج مسار GET <code>/json</code> الذي قمت بإنشائه في التحدي الأخير لتحويل رسالة كائن الاستجابة إلى أحرف كبيرة إذا كانت <code>process.env.MESSAGE_STYLE</code> تساوي <code>uppercase</code> . يجب أن يصبح كائن الاستجابة <code>{"message": "HELLO JSON"}</code> .
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتغير استجابة نقطة النهاية <code>/json</code> طبقًا لمتغير البيئة <code>MESSAGE_STYLE</code>
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/use-env-vars'').then(data => { assert.isTrue(data.passed, ''The response of "/json" does not change according to MESSAGE_STYLE''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-description-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb3367417b2b2512bfc
<add>title: Add a Description to Your package.json
<add>localeTitle: أضف وصفًا إلى الحزمة. json
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الجزء التالي من حزمة جيدة. json هو حقل الوصف ، حيث ينتمي وصف قصير ولكن غني بالمعلومات عن مشروعك.
<add>إذا كنت تخطط في يوم ما لنشر حزمة إلى npm ، تذكر أن هذه هي السلسلة التي يجب أن تبيع فكرتك للمستخدم عندما يقررون تثبيت الحزمة الخاصة بك أم لا. ومع ذلك ، هذه ليست حالة الاستخدام الوحيدة للوصف: إنها طريقة رائعة لتلخيص ما يفعله المشروع ، لا يقل أهمية عن مشاريع Node.js العادية لمساعدة مطورين آخرين ، أو مشرفين مستقبليين أو حتى مستقبلك على فهم المشروع. بسرعة.
<add>بغض النظر عن ما كنت تخطط لمشروعك، وأوصت بالتأكيد وصفا. دعونا نضيف شيئًا مشابهًا لهذا:
<add><code>"description": "A project that does something awesome",</code>
<add>إرشادات
<add>أضف وصفًا إلى الحزمة package.json في مشروع Glitch.
<add>تذكر لاستخدام علامات الاقتباس المزدوجة لأسماء المجال ( ") والفواصل (،) للفصل بين الحقول.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "وصف" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.description, ''"description" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-license-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bfe
<add>title: Add a License to Your package.json
<add>localeTitle: إضافة ترخيص إلى الحزمة الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>حقل الترخيص هو المكان الذي تبلغ المستخدمين فيه بمشروعك المسموح لهم القيام به.
<add>بعض التراخيص المشتركة لمشاريع مفتوحة المصدر تشمل MIT و BSD. يعد http://choosealicense.com موردًا رائعًا إذا كنت تريد معرفة المزيد حول الترخيص الذي يمكن أن يناسب مشروعك.
<add>معلومات الترخيص غير مطلوبة. ستمنحك قوانين حقوق الطبع والنشر في معظم البلدان ملكية ما تنشئه افتراضيًا. ومع ذلك ، فمن الأفضل دائمًا تحديد ما يمكن للمستخدمين فعله وما لا يمكنهم فعله.
<add>مثال
<add><code>"license": "MIT",</code>
<add>تعليمات
<add>قم بتعبئة حقل الترخيص في الحزمة. json من مشروع Glitch الخاص بك كما تجد مناسبة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "ترخيص" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.license, ''"license" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-version-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bff
<add>title: Add a Version to Your package.json
<add>localeTitle: أضف إصدارًا إلى الحزمة الخاصة بك. json
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الإصدار مع اسم واحد من الحقول المطلوبة في package.json. يصف هذا الحقل الإصدار الحالي لمشروعك.
<add>مثال
<add><code>"version": "1.2",</code>
<add>Instruction
<add>بإضافة نسخة إلى package.json في مشروع Glitch الخاص بك.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون لديك مفتاح "إصدار" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.version, ''"version" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-keywords-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bfd
<add>title: Add Keywords to Your package.json
<add>localeTitle: أضف كلمات رئيسية إلى package.json الخاص بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>حقل الكلمات الرئيسية هو المكان الذي يمكنك فيه وصف مشروعك باستخدام الكلمات الرئيسية ذات الصلة.
<add>مثال
<add><code>"keywords": [ "descriptive", "related", "words" ],</code>
<add>كما ترى ، يتم تنظيم هذا الحقل على هيئة مصفوفة من سلاسل مقتبسة مزدوجة.
<add>إرشادات
<add>أضف مصفوفة من السلاسل المناسبة إلى حقل الكلمات الرئيسية في الحزمة. json من مشروع Glitch.
<add>يجب أن تكون واحدة من الكلمات الأساسية freecodecamp.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يحتوي package.json على مفتاح "كلمات رئيسية" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.keywords, ''"keywords" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون حقل "الكلمات الرئيسية" مصفوفة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.isArray(packJson.keywords, ''"keywords" is not an array''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن تتضمن "الكلمات الرئيسية" "freecodecamp"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.include(packJson.keywords, ''freecodecamp'', ''"keywords" does not include "freecodecamp"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/expand-your-project-with-external-packages-from-npm.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512c00
<add>title: Expand Your Project with External Packages from npm
<add>localeTitle: توسيع المشروع الخاص بك مع الحزم الخارجية من npm
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>واحدة من أكبر الأسباب لاستخدام مدير الحزمة هي إدارة التبعية القوية. بدلاً من الاضطرار يدويًا إلى التأكد من حصولك على جميع الاعتمادات عندما تقوم بإعداد مشروع على كمبيوتر جديد ، يقوم npm تلقائيًا بتثبيت كل شيء لك. ولكن كيف يمكن لـ npm أن تعرف بالضبط ما يحتاجه مشروعك؟ تعرّف على قسم التبعيات في الحزمة. json.
<add>في قسم التبعيات ، يتم تخزين الحزم التي تحتاجها مشروعك باستخدام التنسيق التالي:
<add><code>"dependencies": {</code>
<add><code>"package-name": "version",</code>
<add><code>"express": "4.14.0"</code>
<add><code>}</code>
<add>إرشادات
<add>قم بإضافة الإصدار 2.14.0 من حزمة الحزم إلى حقل التبعيات الخاص بك من package.json
<add>Moment هي مكتبة مفيدة للعمل مع الوقت والتواريخ.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون إصدار "اللحظة" هو "2.14.0"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.14\.0/, ''Wrong version of "moment" installed. It should be 2.14.0''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/how-to-use-package.json-the-core-of-any-node.js-project-or-npm-package.arabic.md
<add>---
<add>id: 587d7fb3367417b2b2512bfb
<add>title: 'How to Use package.json, the Core of Any Node.js Project or npm Package'
<add>localeTitle: "كيفية استخدام package.json ، أو Core of Any Node.js Project أو npm Package"
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إن ملف package.json هو مركز أي مشروع Node.js أو حزمة npm. يخزن معلومات حول مشروعك تمامًا مثل <head> - يصف القسم في مستند HTML محتوى صفحة الويب. يتكون package.json من كائن JSON واحد حيث يتم تخزين المعلومات في "مفتاح": أزواج القيم. لا يوجد سوى حقلين مطلوبين في الحد الأدنى من package.json - الاسم والإصدار - إلا أنه من الممارسات الجيدة توفير معلومات إضافية حول مشروعك يمكن أن تكون مفيدة للمستخدمين أو مشرفين المستقبل.
<add>حقل المؤلف
<add>إذا ذهبت إلى مشروع Glitch الذي قمت بإعداده سابقًا وانظرت إلى الجانب الأيسر من شاشتك ، فستجد شجرة الملفات حيث يمكنك رؤية نظرة عامة على مختلف الملفات في مشروعك. ضمن القسم الخلفي لشجرة الملفات ، ستجد حزمة package.json - الملف الذي سنحسّنه في التحديين التاليين.
<add>أحد أكثر أجزاء المعلومات شيوعًا في هذا الملف هو حقل المؤلف الذي يحدد منشئ المشروع. يمكن أن يكون إما سلسلة أو كائن مع تفاصيل الاتصال. الهدف موصى به للمشاريع الأكبر ، ولكن في حالتنا ، سوف تفعل سلسلة بسيطة مثل المثال التالي.
<add><code>"author": "Jane Doe",</code>
<add>Instructions
<add>أضف اسمك إلى حقل المؤلف في الحزمة. json لمشروع Glitch.
<add>تذكر أنك تكتب JSON.
<add>يجب أن تستخدم جميع أسماء الحقول علامات اقتباس مزدوجة (") ، على سبيل المثال" المؤلف "
<add>يجب فصل جميع الحقول بفاصلة (،)
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "المؤلف" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.author, ''"author" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/manage-npm-dependencies-by-understanding-semantic-versioning.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c01
<add>title: Manage npm Dependencies By Understanding Semantic Versioning
<add>localeTitle: إدارة التبعيات npm عن طريق فهم الإصدار الدلالي
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إصدارات من حزم npm في قسم التبعيات من package.json الخاص بك يتبع ما يسمى بإصدار Semantic (SemVer) ، وهو معيار صناعي لإصدارات البرامج التي تهدف إلى تسهيل إدارة التبعيات. يجب أن تستخدم المكتبات وأطر العمل أو غيرها من الأدوات المنشورة على npm نظام SemVer من أجل إيصال نوع التغييرات التي يمكن للمشاريع التي تعتمد على الحزمة أن تتوقع إذا تم تحديثها.
<add>SemVer لا معنى له في مشاريع دون واجهات برمجة التطبيقات العامة - وذلك ما لم مشروع مشابه لالأمثلة أعلاه، استخدم شكل إصدارات أخرى.
<add>لماذا تحتاج لفهم SemVer؟
<add>معرفة SemVer يمكن أن تكون مفيدة عند تطوير البرمجيات التي تستخدم الاعتماد على الخارج (والتي تفعل دائما تقريبا). في يوم من الأيام ، سيوفر لك فهمك لهذه الأرقام من إدخال تغييرات مفاجئة إلى مشروعك دون فهم لماذا لا تسير الأمور "التي عملت بالأمس" فجأة.
<add>هذه هي الطريقة التي يعمل بها الإصدار الدارجة وفقًا للموقع الرسمي:
<add>بالنظر إلى رقم الإصدار MAJOR.MINOR.PATCH ، قم بزيادة:
<add>إصدار رئيسي عند إجراء تغييرات غير متوافقة على واجهة برمجة التطبيقات ، إصدار
<add>MINOR عند إضافة وظائف بطريقة متوافقة إلى الخلف و
<add>الإصدار PATCH عند إجراء إصلاحات الأخطاء المتوافقة.
<add>وهذا يعني أن PATCHes هي إصلاحات للأخطاء ، وإضافة MINORs إلى ميزات جديدة ، ولكن لا أحد منهما يكسر ما نجح من قبل. وأخيرًا ، تضيف MAJORs تغييرات لن تعمل مع الإصدارات السابقة.
<add>مثال
<add>رقم إصدار لغوي: 1.3.8
<add>إرشادات
<add>في قسم التبعيات في الحزمة الخاصة بك. json ، قم بتغيير إصدار اللحظة لمطابقة الإصدار 2 من MAJOR والإصدار 10 من MINOR والإصدار PATCH 2
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون إصدار "اللحظة" هو "2.10.2"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.10\.2/, ''Wrong version of "moment". It should be 2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/remove-a-package-from-your-dependencies.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c04
<add>title: Remove a Package from Your Dependencies
<add>localeTitle: قم بإزالة حزمة من التبعيات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>لقد قمت الآن باختبار بعض الطرق التي يمكنك من خلالها إدارة تبعيات مشروعك باستخدام قسم تبعيات package.json. لقد قمت بتضمين الحزم الخارجية عن طريق إضافتها إلى الملف وحتى إخبار npm بأنواع الإصدارات التي تريدها باستخدام أحرف خاصة مثل tilde (~) أو علامة الإقحام (^).
<add>ولكن ماذا لو كنت ترغب في إزالة حزمة خارجية لم تعد بحاجة إليها؟ كنت قد خمنت بالفعل - فقط إزالة "مفتاح" المقابلة: الزوج قيمة لذلك من الاعتماديات الخاصة بك.
<add>تنطبق هذه الطريقة نفسها على إزالة الحقول الأخرى في الحزمة الخاصة بك. json بالإضافة إلى
<add>تعليمات
<add>إزالة لحظة الحزمة من التبعيات الخاصة بك.
<add>تأكد من حصولك على كمية مناسبة من الفواصل بعد إزالتها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب ألا تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.notProperty(packJson.dependencies, ''moment'', ''"dependencies" still includes "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c03
<add>title: Use the Caret-Character to Use the Latest Minor Version of a Dependency
<add>localeTitle: استخدم حرف الإقحام لاستخدام أحدث إصدار ثانوي من التبعية
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>شبيه بالكيفية التي سمعت بها التلدة (~) التي تعلمناها في التحدي الأخير لـ npm لتثبيت أحدث PATCH للتبعية ، تسمح علامة الإقحام (^) لـ npm لتثبيت التحديثات المستقبلية أيضًا. الفرق هو أن حرف الإقحام سيسمح بتحديثات MINOR و PATCHes.
<add>في الوقت الحالي ، يجب أن يكون الإصدار الحالي من اللحظة ~ 2.10.2 والذي يسمح لـ npm بالتثبيت على أحدث إصدار 2.10.x. إذا استخدمنا بدلاً من ذلك علامة الإقحام (^) كبادئة للإصدار ، فسيتم السماح لـ npm بالتحديث إلى أي إصدار 2.xx.
<add>مثال
<add><code>"some-package-name": "^1.3.8" allows updates to any 1.xx version.</code>
<add>تعليمات
<add>استخدم حرف الإقحام (^) لبدء إصدار اللحظة في تبعياتك والسماح لـ npm بتحديثه إلى أي إصدار جديد صغير.
<add>لاحظ أنه لا يجب تغيير أرقام الإصدارات نفسها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يتطابق إصدار "اللحظة" مع "^ 2.x.x"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\^2\./, ''Wrong version of "moment". It should be ^2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/use-the-tilde-character-to-always-use-the-latest-patch-version-of-a-dependency.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c02
<add>title: Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency
<add>localeTitle: استخدم حرف التلدة إلى استخدام أحدث إصدار تصحيح من تبعية
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في التحدي الأخير ، أخبرنا npm بتضمين إصدار محدد فقط من الحزمة. هذه طريقة مفيدة لتجميد تبعياتك إذا كنت بحاجة إلى التأكد من أن الأجزاء المختلفة من مشروعك تبقى متوافقة مع بعضها البعض. ولكن في معظم حالات الاستخدام ، لا تريد أن تفوتك أي إصلاحات للأخطاء ، نظرًا لأنها غالبًا ما تتضمن تصحيحات أمنية مهمة (ورجاءً) ألا تكسر الأشياء في القيام بذلك.
<add>للسماح بتبعية npm ليتم تحديثها إلى أحدث إصدار PATCH ، يمكنك بادئة إصدار التبعية بحرف التلدة (~). في package.json ، فإن القاعدة الحالية التي نتبعها حول كيفية قيام npm بترقية اللحظة هي استخدام إصدار محدد فقط (2.10.2) ، ولكننا نريد السماح بأحدث إصدار 2.10.x.
<add>مثال
<add><code>"some-package-name": "~1.3.8" allows updates to any 1.3.x version.</code>
<add>إرشادات
<add>استخدم حرف التلدة (~) لبدء إصدار اللحظة في تبعياتك والسماح لـ npm بتحديثه إلى أي إصدار PATCH جديد.
<add>لاحظ أنه لا يجب تغيير أرقام الإصدارات نفسها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يتطابق إصدار "اللحظة" "~ 2.10.2"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\~2\.10\.2/, ''Wrong version of "moment". It should be ~2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.arabic.md
<add>---
<add>id: 587d7fb9367417b2b2512c12
<add>title: Chain Search Query Helpers to Narrow Search Results
<add>localeTitle: سلسلة بحث مساعدة المساعدين لضيق نتائج البحث
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إذا لم تقم بتمرير معاودة الاتصال كالوسيطة الأخيرة إلى Model.find () (أو إلى طرق البحث الأخرى) ، فلن يتم تنفيذ الاستعلام. يمكنك تخزين الاستعلام في متغير للاستخدام في وقت لاحق. يمكّنك هذا النوع من الكائنات من إنشاء استعلام باستخدام بناء جملة تسلسل. يتم تنفيذ البحث الفعلي db عندما تقوم بسلسلة الأسلوب .exec () أخيراً. تمرير رد الاتصال الخاص بك لهذه الطريقة الأخيرة. هناك العديد من مساعدي الاستعلام ، هنا سنستخدم الأكثر شيوعًا.
<add>العثور على الناس الذين يحبون "بوريتو". وفرزها حسب الاسم ، وحصر النتائج في مستندين ، وإخفاء عمرهم. سلسلة .find () ، .sort () ، .limit () ، .select () ، ثم .exec (). تمرير الاستدعاء (err، data) المنفذة exec ().
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تنجح مساعدين الاستعلام تسلسل
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/query-tools'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Pablo'', age: 26, favoriteFoods: [''burrito'', ''hot-dog'']}, {name: ''Bob'', age: 23, favoriteFoods: [''pizza'', ''nachos'']}, {name: ''Ashley'', age: 32, favoriteFoods: [''steak'', ''burrito'']}, {name: ''Mario'', age: 51, favoriteFoods: [''burrito'', ''prosciutto'']} ]) }).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data.length, 2, ''the data array length is not what expected''); assert.notProperty(data[0], ''age'', ''The returned first item has too many properties''); assert.equal(data[0].name, ''Ashley'', ''The returned first item name is not what expected''); assert.notProperty(data[1], ''age'', ''The returned second item has too many properties''); assert.equal(data[1].name, ''Mario'', ''The returned second item name is not what expected'');}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c07
<add>title: Create a Model
<add>localeTitle: خلق نموذج
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>أولا وقبل كل ما نحتاج إليه في المخطط. كل مخطط مخططات إلى مجموعة MongoDB. يحدد شكل المستندات داخل هذه المجموعة.
<add>المخططات هي العنصر الأساسي للنماذج. يمكن أن تكون متداخلة لإنشاء نماذج معقدة ، ولكن في هذه الحالة سنبقي الأمور بسيطة.
<add>يتيح لك نموذج إنشاء مثيلات لكائنات ، تسمى مستندات.
<add>إنشاء شخص لديه هذا النموذج الأولي:
<add><code>- Person Prototype -</code>
<add><code>--------------------</code>
<add><code>name : string [required]</code>
<add><code>age : number</code>
<add><code>favoriteFoods : array of strings (*)</code>
<add>استخدم أنواع المخطط الأساسي للنمس. إذا أردت يمكنك أيضا إضافة
<add>حقول أكثر من ذلك، استخدام المصادقون بسيطة مثل المطلوبة أو فريدة من نوعها،
<add>القيم الافتراضية والمحددة. انظر <a href='http://mongoosejs.com/docs/guide.html'>مستندات النمس</a> .
<add>[C] RUD الجزء الأول - CREATE
<add>ملاحظة: خلل هو خادم حقيقي ، والخوادم الحقيقية في التفاعلات مع ديسيبل يحدث في وظائف معالج. يتم تنفيذ هذه الوظيفة عند حدوث بعض الأحداث (على سبيل المثال ، يضرب أحد الأشخاص نقطة نهاية على واجهة برمجة التطبيقات). سنتبع نفس النهج في هذه التمارين. الدالة done () هي رد اتصال يخبرنا أنه يمكننا المتابعة بعد إكمال عملية غير متزامنة مثل الإدراج أو البحث أو التحديث أو الحذف. إنه يتبع اصطلاح "عقدة" ويجب أن يتم استدعاؤه كـ "فارغ (بيانات) فارغة" أو "تم" (خطأ) على الخطأ.
<add>تحذير - عند التفاعل مع الخدمات عن بعد ، قد تحدث أخطاء!
<add><code>/* Example */</code>
<add><code>var someFunc = function(done) {</code>
<add><code>//... do something (risky) ...</code>
<add><code>if(error) return done(error);</code>
<add><code>done(null, result);</code>
<add><code>};</code>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء مثيل من مخطط النمس
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/mongoose-model'', {name: ''Mike'', age: 28, favoriteFoods: [''pizza'', ''cheese'']}).then(data => { assert.equal(data.name, ''Mike'', ''"model.name" is not what expected''); assert.equal(data.age, ''28'', ''"model.age" is not what expected''); assert.isArray(data.favoriteFoods, ''"model.favoriteFoods" is not an Array''); assert.include(data.favoriteFoods, ''pizza'', ''"model.favoriteFoods" does not include the expected items''); assert.include(data.favoriteFoods, ''cheese'', ''"model.favoriteFoods" does not include the expected items''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c09
<add>title: Create and Save a Record of a Model
<add>localeTitle: إنشاء وحفظ سجل للنموذج
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إنشاء نسخة من المستند باستخدام مُنشئ الشخص الذي قمت بإنشائه من قبل. تمرير إلى المنشئ كائن له اسم الحقول والعمر و foodFoods المفضلة. يجب أن تكون أنواعها متوافقة مع تلك الموجودة في "مخطط الشخص". ثم استدعاء الأسلوب document.save () على مثيل المستند الذي تم إرجاعه. تمرير إليه رد اتصال باستخدام عقدة العقد. هذا نمط شائع ، كل طرق CRUD التالية تأخذ وظيفة رد اتصال مثل هذا كوسيطة أخيرة.
<add><code>/* Example */</code>
<add><code>// ...</code>
<add><code>person.save(function(err, data) {</code>
<add><code>// ...do your stuff here...</code>
<add><code>});</code>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء عنصر db وحفظه
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/create-and-save-person'').then(data => { assert.isString(data.name, ''"item.name" should be a String''); assert.isNumber(data.age, ''28'', ''"item.age" should be a Number''); assert.isArray(data.favoriteFoods, ''"item.favoriteFoods" should be an Array''); assert.equal(data.__v, 0, ''The db item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0a
<add>title: Create Many Records with model.create()
<add>localeTitle: إنشاء العديد من السجلات باستخدام model.create ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بعض الأحيان تحتاج إلى إنشاء العديد من الأمثلة من النماذج الخاصة بك ، على سبيل المثال عند إنشاء قاعدة بيانات بالبيانات الأولية. تأخذ مجموعة Model.create () مصفوفة من الكائنات مثل [{name: 'John'، ...}، {...}، ...] باعتبارها أول وسيطة ، وحفظها كلها في db. قم بإنشاء العديد من الأشخاص باستخدام Model.create () ، باستخدام الدالة arrayOfPeople.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء العديد من عناصر db في وقت واحد
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/create-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''John'', age: 24, favoriteFoods: [''pizza'', ''salad'']}, {name: ''Mary'', age: 21, favoriteFoods: [''onions'', ''chicken'']}])}).then(data => { assert.isArray(data, ''the response should be an array''); assert.equal(data.length, 2, ''the response does not contain the expected number of items''); assert.equal(data[0].name, ''John'', ''The first item is not correct''); assert.equal(data[0].__v, 0, ''The first item should be not previously edited''); assert.equal(data[1].name, ''Mary'', ''The second item is not correct''); assert.equal(data[1].__v, 0, ''The second item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c11
<add>title: Delete Many Documents with model.remove()
<add>localeTitle: حذف العديد من المستندات باستخدام model.remove ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>Model.remove () مفيد لحذف جميع الوثائق التي تطابق معايير محددة. احذف جميع الأشخاص الذين يكون اسمهم "Mary" ، باستخدام Model.remove (). قم بنقله إلى مستند استعلام باستخدام مجموعة حقول "الاسم" ، وبالطبع رد اتصال.
<add>ملاحظة: لا يقوم Model.remove () بإرجاع المستند المحذوف ، ولكن كائن JSON يحتوي على نتيجة العملية وعدد العناصر المتأثرة. لا تنسَ تمريرها إلى معاودة الاتصال () ، لأننا نستخدمها في الاختبارات.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح حذف العديد من العناصر في وقت واحد
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/remove-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Mary'', age: 16, favoriteFoods: [''lollipop'']}, {name: ''Mary'', age: 21, favoriteFoods: [''steak'']}])}).then(data => { assert.isTrue(!!data.ok, ''The mongo stats are not what expected''); assert.equal(data.n, 2, ''The number of items affected is not what expected''); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c10
<add>title: Delete One Document Using model.findByIdAndRemove
<add>localeTitle: حذف مستند واحد باستخدام model.findByIdAndRemove
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>احذف شخصًا واحدًا من _id. يجب استخدام أحد الأساليب findByIdAndRemove () أو findOneAndRemove (). هم مثل أساليب التحديث السابقة. يمرر المستند الذي تمت إزالته إلى cb. كالعادة ، استخدم الدالة argument personId كمفتاح بحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح حذف عنصر
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/remove-one-person'', {name:''Jason Bourne'', age: 36, favoriteFoods:[''apples'']}).then(data => { assert.equal(data.name, ''Jason Bourne'', ''item.name is not what expected''); assert.equal(data.age, 36, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''apples''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c06
<add>title: Install and Set Up Mongoose
<add>localeTitle: تثبيت وإعداد النمس
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إضافة mongodb والنمس إلى package.json المشروع. ثم تتطلب النمس. قم بتخزين URI قاعدة بيانات قاعدة البيانات الخاصة بك في ملف .env الخاص كـ MONGO_URI. الاتصال بقاعدة البيانات باستخدام mongoose.connect ( <Your URI> )
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تكون "" mongodb "التبعية في package.json"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongodb''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون التبعية "النمس" في package.json "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongoose''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب ربط "النمس" بقاعدة بيانات "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/is-mongoose-ok'').then(data => {assert.isTrue(data.isMongooseOk, ''mongoose is not connected'')}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c0e
<add>title: 'Perform Classic Updates by Running Find, Edit, then Save'
<add>localeTitle: "قم بإجراء التحديثات الكلاسيكية عن طريق تشغيل بحث ، تحرير ، ثم حفظ"
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في الأيام الخوالي ، كان هذا هو ما تحتاج إلى القيام به إذا كنت ترغب في تحرير مستند وتكون قادرًا على استخدامه بطريقة ما ، على سبيل المثال إرساله مرة أخرى في استجابة الخادم. لدى Mongoose طريقة تحديث مخصصة: Model.update (). يتم ربطه بالسائق المنخفض المستوى من طراز mongo. يمكنه تحرير الكثير من الوثائق التي تتطابق مع معايير معينة ، لكنه لا يرسل الوثيقة المحدثة ، فقط رسالة "الحالة". وعلاوة على ذلك ، فإنه يجعل عمليات التحقق من صحة النموذج صعبة ، لأنه فقط يدعو مباشرة سائق المونجو.
<add>البحث عن شخص بواسطة _id (استخدام أي من الأساليب المذكورة أعلاه) مع person المعلمة كمفتاح البحث. أضف "الهامبرغر" إلى قائمة منتجاتها المفضلة (يمكنك استخدام Array.push ()). ثم - داخل البحث عن معاودة الاتصال - حفظ () الشخص المحدثة.
<add>[*] تلميح: قد يكون هذا أمرًا صعبًا إذا كنت قد أعلنت في المخطط الخاص بك أن الأطعمة المفضلة هي صفيف ، دون تحديد النوع (أي [السلسلة]). في ذلك casefavorite السلع الافتراضية إلى نوع مختلط ، ويجب عليك وضع علامة عليه يدويًا كما تم تحريره باستخدام document.markModified ('edited-field'). (http://mongoosejs.com/docs/schematypes.html - # مختلط)
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: البحث عن تحرير عنصر يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-edit-save'', {name:''Poldo'', age: 40, favoriteFoods:[''spaghetti'']}).then(data => { assert.equal(data.name, ''Poldo'', ''item.name is not what expected''); assert.equal(data.age, 40, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''spaghetti'', ''hamburger''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 1, ''The item should be previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c0f
<add>title: Perform New Updates on a Document Using model.findOneAndUpdate()
<add>localeTitle: إجراء تحديثات جديدة على مستند باستخدام model.findOneAndUpdate ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الإصدارات الحديثة من النمس لها طرق لتبسيط تحديث الوثائق. تتصرف بعض الميزات الأكثر تقدمًا (أي خطافات ما قبل / النشر والتحقق من الصحة) بشكل مختلف مع هذا الأسلوب ، لذلك لا تزال الطريقة الكلاسيكية مفيدة في العديد من المواقف. يمكن استخدام findByIdAndUpdate () عند البحث باستخدام Id.
<add>البحث عن شخص حسب الاسم وتعيين سنها إلى 20. استخدم الدالة parameter nameName كمفتاح بحث.
<add>تلميح: نريد منك إرجاع المستند الذي تم تحديثه. للقيام بذلك ، تحتاج إلى تمرير مستند الخيارات {جديد: true} كوسيطة 3 للبحث عن OneOndUpdate (). بشكل افتراضي ، ترجع هذه الطرق الكائن غير المعدل.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: findOneAndUpdate يجب أن ينجح عنصر
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-update'', {name:''Dorian Gray'', age: 35, favoriteFoods:[''unknown'']}).then(data => { assert.equal(data.name, ''Dorian Gray'', ''item.name is not what expected''); assert.equal(data.age, 20, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''unknown''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''findOneAndUpdate does not increment version by design !!!''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-dataarabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0b
<add>title: Use model.find() to Search Your Database
<add>localeTitle: استخدم model.find () للبحث في قاعدة البيانات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>البحث عن جميع الأشخاص الذين لديهم اسم معين ، باستخدام Model.find () -> [شخص]
<add>في أبسط استخدام له ، يقبل Model.find () مستند استعلام (كائن JSON) كالوسيطة الأولى ، ثم رد اتصال. تقوم بإرجاع مجموعة من التطابقات. وهو يدعم مجموعة واسعة للغاية من خيارات البحث. التحقق من ذلك في المستندات. استخدم الوسيطة function personName كمفتاح البحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: البحث عن العناصر المقابلة لمعايير يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-all-by-name'', {name: ''r@nd0mN4m3'', age: 24, favoriteFoods: [''pizza'']}).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data[0].name, ''r@nd0mN4m3'', ''item.name is not what expected''); assert.equal(data[0].__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0d
<add>title: Use model.findById() to Search Your Database By _id
<add>localeTitle: استخدم model.findById () للبحث في قاعدة البيانات الخاصة بك بواسطة _id
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>عند حفظ مستند ، يقوم mongodb تلقائيًا بإضافة حقل _id ، وتعيينه إلى مفتاح أبجدي رقمي فريد. البحث عن طريق _id هو عملية متكررة للغاية ، لذلك يوفر النمس طريقة مخصصة لذلك. ابحث عن الشخص (فقط !!) الذي لديه _id محدد ، باستخدام Model.findById () -> الشخص. استخدم الوسيطة function personId كمفتاح البحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: العثور على عنصر من خلال معرف يجب أن تنجح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/find-by-id'').then(data => { assert.equal(data.name, ''test'', ''item.name is not what expected''); assert.equal(data.age, 0, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''none''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0c
<add>title: Use model.findOne() to Return a Single Matching Document from Your Database
<add>localeTitle: استخدم model.findOne () لإرجاع مستند مطابقة مفردة من قاعدة البيانات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يتصرف model.findOne () مثل .find () ، ولكنه يقوم بإرجاع مستند واحد فقط (وليس صفيف) ، حتى إذا كان هناك عدة عناصر. من المفيد بشكل خاص عند البحث عن طريق الخصائص التي أعلنت أنها فريدة من نوعها. البحث عن شخص واحد فقط لديه طعام معين في المفضلة لها ، وذلك باستخدام Model.findOne () -> شخص. استخدم الوسيطة الدالة الغذائية كمفتاح بحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: العثور على عنصر واحد يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-by-food'', {name: ''Gary'', age: 46, favoriteFoods: [''chicken salad'']}).then(data => { assert.equal(data.name, ''Gary'', ''item.name is not what expected''); assert.deepEqual(data.favoriteFoods, [''chicken salad''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section> | 39 |
Javascript | Javascript | add unit test for common parsers method | cb3a5cc6913d81b3e16bcb3a9d5f29e5cfa1de73 | <ide><path>packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js
<add>/**
<add> * Copyright (c) Meta Platforms, Inc. and affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> * @oncall react_native
<add> */
<add>
<add>'use-strict';
<add>
<add>const {wrapNullable, unwrapNullable} = require('../parsers-commons.js');
<add>
<add>describe('wrapNullable', () => {
<add> describe('when nullable is true', () => {
<add> it('returns nullable type annotation', () => {
<add> const result = wrapNullable(true, {
<add> type: 'BooleanTypeAnnotation',
<add> });
<add> const expected = {
<add> type: 'NullableTypeAnnotation',
<add> typeAnnotation: {
<add> type: 'BooleanTypeAnnotation',
<add> },
<add> };
<add>
<add> expect(result).toEqual(expected);
<add> });
<add> });
<add> describe('when nullable is false', () => {
<add> it('returns non nullable type annotation', () => {
<add> const result = wrapNullable(false, {
<add> type: 'BooleanTypeAnnotation',
<add> });
<add> const expected = {
<add> type: 'BooleanTypeAnnotation',
<add> };
<add>
<add> expect(result).toEqual(expected);
<add> });
<add> });
<add>});
<add>
<add>describe('unwrapNullable', () => {
<add> describe('when type annotation is nullable', () => {
<add> it('returns original type annotation', () => {
<add> const result = unwrapNullable({
<add> type: 'NullableTypeAnnotation',
<add> typeAnnotation: {
<add> type: 'BooleanTypeAnnotation',
<add> },
<add> });
<add> const expected = [
<add> {
<add> type: 'BooleanTypeAnnotation',
<add> },
<add> true,
<add> ];
<add>
<add> expect(result).toEqual(expected);
<add> });
<add> });
<add> describe('when type annotation is not nullable', () => {
<add> it('returns original type annotation', () => {
<add> const result = unwrapNullable({
<add> type: 'BooleanTypeAnnotation',
<add> });
<add> const expected = [
<add> {
<add> type: 'BooleanTypeAnnotation',
<add> },
<add> false,
<add> ];
<add>
<add> expect(result).toEqual(expected);
<add> });
<add> });
<add>}); | 1 |
Go | Go | add more info for debugging | 5882a9ea171b4cade430da8428beec180d0af952 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) {
<ide> }
<ide>
<ide> if _, ok := result["bar"]; !ok {
<del> c.Fatal("Could not find volume bar set from env foo in volumes table")
<add> c.Fatalf("Could not find volume bar set from env foo in volumes table, got %q", result)
<ide> }
<ide>
<ide> deleteImages(name)
<ide> func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) {
<ide> }
<ide>
<ide> if _, ok := result["${FOO}"]; !ok {
<del> c.Fatal("Could not find volume ${FOO} set from env foo in volumes table")
<add> c.Fatalf("Could not find volume ${FOO} set from env foo in volumes table, got %q", result)
<ide> }
<ide>
<ide> deleteImages(name)
<ide> func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) {
<ide> }
<ide>
<ide> if _, ok := result[`\\\${FOO}`]; !ok {
<del> c.Fatal(`Could not find volume \\\${FOO} set from env foo in volumes table`, result)
<add> c.Fatalf(`Could not find volume \\\${FOO} set from env foo in volumes table, got %q`, result)
<ide> }
<ide>
<ide> } | 1 |
PHP | PHP | fix $previous becoming null only | bf374572d7cafa3c8a3170601224c40bc13e3bec | <ide><path>src/Datasource/Exception/PageOutOfBoundsException.php
<ide> class PageOutOfBoundsException extends Exception
<ide> protected $_messageTemplate = 'Page number %s could not be found.';
<ide>
<ide> /**
<del> * Constructor
<del> *
<del> * @param array|null $message Paging info.
<del> * @param int $code The code of the error, is also the HTTP status code for the error.
<del> * @param \Exception|null $previous The previous exception.
<add> * {@inheritDoc}
<ide> */
<del> public function __construct($message = null, $code = 404, $previous = null)
<del> {
<del> parent::__construct($message, $code, $previous = null);
<del> }
<add> protected $_defaultCode = 404;
<ide> }
<ide><path>tests/TestCase/ExceptionsTest.php
<ide> public function exceptionProvider()
<ide> ['Cake\Datasource\Exception\MissingDatasourceConfigException', 500],
<ide> ['Cake\Datasource\Exception\MissingDatasourceException', 500],
<ide> ['Cake\Datasource\Exception\MissingModelException', 500],
<add> ['Cake\Datasource\Exception\PageOutOfBoundsException', 404],
<ide> ['Cake\Datasource\Exception\RecordNotFoundException', 404],
<ide> ['Cake\Mailer\Exception\MissingActionException', 404],
<ide> ['Cake\Mailer\Exception\MissingMailerException', 500], | 2 |
Ruby | Ruby | add additional test for sharing templates | 2455d16a5a975fa5bf75bdb023df61047b055e3d | <ide><path>actionview/test/template/resolver_shared_tests.rb
<ide> def test_different_templates_when_cache_disabled
<ide> end
<ide>
<ide> def test_same_template_from_different_details_is_same_object
<del> with_file "test/hello_world.html.erb", "Hello plain text!"
<add> with_file "test/hello_world.html.erb", "Hello HTML!"
<ide>
<ide> a = context.find("hello_world", "test", false, [], locale: [:en])
<ide> b = context.find("hello_world", "test", false, [], locale: [:fr])
<ide> assert_same a, b
<ide> end
<ide>
<add> def test_templates_with_optional_locale_shares_common_object
<add> with_file "test/hello_world.text.erb", "Generic plain text!"
<add> with_file "test/hello_world.fr.text.erb", "Texte en Francais!"
<add>
<add> en = context.find_all("hello_world", "test", false, [], locale: [:en])
<add> fr = context.find_all("hello_world", "test", false, [], locale: [:fr])
<add>
<add> assert_equal 1, en.size
<add> assert_equal 2, fr.size
<add>
<add> assert_equal "Generic plain text!", en[0].source
<add> assert_equal "Texte en Francais!", fr[0].source
<add> assert_equal "Generic plain text!", fr[1].source
<add>
<add> assert_same en[0], fr[1]
<add> end
<add>
<ide> def test_virtual_path_is_preserved_with_dot
<ide> with_file "test/hello_world.html.erb", "Hello html!"
<ide> | 1 |
Text | Text | add missing definite article | 6ee361332b09f148f86149a7d9a6220bd61966e8 | <ide><path>docs/api-guide/serializers.md
<ide> Model fields which have `editable=False` set, and `AutoField` fields will be set
<ide>
<ide> **Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. Here you **must** specify the field explicitly and provide a valid default value.
<ide>
<del>A common example of this is a read-only relation to currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
<add>A common example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
<ide>
<ide> user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
<ide> | 1 |
Javascript | Javascript | fix issues with test-fs-chmod | 236b217cd705d03713c467b49d4c063f69187ddb | <ide><path>test/simple/test-fs-chmod.js
<ide> function closeSync() {
<ide>
<ide> // On Windows chmod is only able to manipulate read-only bit
<ide> if (is_windows) {
<del> mode_async = 0600; // read-write
<del> mode_sync = 0400; // read-only
<add> mode_async = 0400; // read-only
<add> mode_sync = 0600; // read-write
<ide> } else {
<ide> mode_async = 0777;
<ide> mode_sync = 0644;
<ide> }
<ide>
<del>var file = path.join(common.fixturesDir, 'a.js');
<add>var file1 = path.join(common.fixturesDir, 'a.js'),
<add> file2 = path.join(common.fixturesDir, 'a1.js');
<ide>
<del>fs.chmod(file, mode_async.toString(8), function(err) {
<add>fs.chmod(file1, mode_async.toString(8), function(err) {
<ide> if (err) {
<ide> got_error = true;
<ide> } else {
<del> console.log(fs.statSync(file).mode);
<add> console.log(fs.statSync(file1).mode);
<ide>
<ide> if (is_windows) {
<del> assert.ok((fs.statSync(file).mode & 0777) & mode_async);
<add> assert.ok((fs.statSync(file1).mode & 0777) & mode_async);
<ide> } else {
<del> assert.equal(mode_async, fs.statSync(file).mode & 0777);
<add> assert.equal(mode_async, fs.statSync(file1).mode & 0777);
<ide> }
<ide>
<del> fs.chmodSync(file, mode_sync);
<add> fs.chmodSync(file1, mode_sync);
<ide> if (is_windows) {
<del> assert.ok((fs.statSync(file).mode & 0777) & mode_sync);
<add> assert.ok((fs.statSync(file1).mode & 0777) & mode_sync);
<ide> } else {
<del> assert.equal(mode_sync, fs.statSync(file).mode & 0777);
<add> assert.equal(mode_sync, fs.statSync(file1).mode & 0777);
<ide> }
<ide> success_count++;
<ide> }
<ide> });
<ide>
<del>fs.open(file, 'a', function(err, fd) {
<add>fs.open(file2, 'a', function(err, fd) {
<ide> if (err) {
<ide> got_error = true;
<ide> console.error(err.stack);
<ide> if (fs.lchmod) {
<ide> try {
<ide> fs.unlinkSync(link);
<ide> } catch (er) {}
<del> fs.symlinkSync(file, link);
<add> fs.symlinkSync(file2, link);
<ide>
<ide> fs.lchmod(link, mode_async, function(err) {
<ide> if (err) { | 1 |
Text | Text | make challenge instruction clearer | 087640d020874bc942d571c9768ff8cb9dcda5c6 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.english.md
<ide> function findGreaterOrEqual(a, b) {
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>Use multiple <code>conditional operators</code> in the <code>checkSign</code> function to check if a number is positive, negative or zero.
<add>Use multiple <code>conditional operators</code> in the <code>checkSign</code> function to check if a number is positive, negative or zero. The function should return "positive", "negative" or "zero".
<ide> </section>
<ide>
<ide> ## Tests | 1 |
Javascript | Javascript | remove all linking apis | d09ab75b04d169a802e606195fed4ef19580e1c0 | <ide><path>server/passport-providers.js
<ide> const successRedirect = '/';
<ide> const failureRedirect = '/';
<del>const linkSuccessRedirect = '/settings';
<del>const linkFailureRedirect = '/settings';
<ide>
<ide> export default {
<ide> local: {
<ide> export default {
<ide> scope: ['email'],
<ide> failureFlash: true
<ide> },
<del> 'facebook-link': {
<del> provider: 'facebook',
<del> module: 'passport-facebook',
<del> clientID: process.env.FACEBOOK_ID,
<del> clientSecret: process.env.FACEBOOK_SECRET,
<del> authPath: '/link/facebook',
<del> callbackURL: '/link/facebook/callback',
<del> callbackPath: '/link/facebook/callback',
<del> successRedirect: linkSuccessRedirect,
<del> failureRedirect: linkFailureRedirect,
<del> scope: ['email', 'user_likes'],
<del> link: true,
<del> failureFlash: true
<del> },
<ide> 'google-login': {
<ide> provider: 'google',
<ide> authScheme: 'oauth2',
<ide> export default {
<ide> scope: ['email', 'profile'],
<ide> failureFlash: true
<ide> },
<del> 'google-link': {
<del> provider: 'google',
<del> authScheme: 'oauth2',
<del> module: 'passport-google-oauth2',
<del> clientID: process.env.GOOGLE_ID,
<del> clientSecret: process.env.GOOGLE_SECRET,
<del> authPath: '/link/google',
<del> callbackURL: '/link/google/callback',
<del> callbackPath: '/link/google/callback',
<del> successRedirect: linkSuccessRedirect,
<del> failureRedirect: linkFailureRedirect,
<del> scope: ['email', 'profile'],
<del> link: true,
<del> failureFlash: true
<del> },
<ide> 'twitter-login': {
<ide> provider: 'twitter',
<ide> authScheme: 'oauth',
<ide> export default {
<ide> consumerSecret: process.env.TWITTER_SECRET,
<ide> failureFlash: true
<ide> },
<del> 'twitter-link': {
<del> provider: 'twitter',
<del> authScheme: 'oauth',
<del> module: 'passport-twitter',
<del> authPath: '/link/twitter',
<del> callbackURL: '/link/twitter/callback',
<del> callbackPath: '/link/twitter/callback',
<del> successRedirect: linkSuccessRedirect,
<del> failureRedirect: linkFailureRedirect,
<del> consumerKey: process.env.TWITTER_KEY,
<del> consumerSecret: process.env.TWITTER_SECRET,
<del> link: true,
<del> failureFlash: true
<del> },
<ide> 'github-login': {
<ide> provider: 'github',
<ide> authScheme: 'oauth2',
<ide> export default {
<ide> clientSecret: process.env.GITHUB_SECRET,
<ide> failureFlash: true
<ide> },
<del> 'github-link': {
<del> provider: 'github',
<del> authScheme: 'oauth2',
<del> module: 'passport-github',
<del> authPath: '/link/github',
<del> callbackURL: '/auth/github/callback/link',
<del> callbackPath: '/auth/github/callback/link',
<del> successRedirect: linkSuccessRedirect,
<del> failureRedirect: linkFailureRedirect,
<del> clientID: process.env.GITHUB_ID,
<del> clientSecret: process.env.GITHUB_SECRET,
<del> link: true,
<del> failureFlash: true,
<del> successFlash: [
<del> 'We\'ve updated your profile based ',
<del> 'on your your GitHub account.'
<del> ].join('')
<del> },
<ide> 'auth0-login': {
<ide> provider: 'auth0',
<ide> module: 'passport-auth0', | 1 |
Java | Java | polish @sendto test | 7a70f7c5d8ab8542cf1666110c58b71b528030ac | <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java
<ide> public class SendToMethodReturnValueHandlerTests {
<ide>
<ide> @Captor private ArgumentCaptor<Message<?>> messageCaptor;
<ide>
<del> private MethodParameter noAnnotationsReturnType;
<del> private MethodParameter sendToReturnType;
<del> private MethodParameter sendToDefaultDestReturnType;
<del> private MethodParameter sendToWithPlaceholdersReturnType;
<del> private MethodParameter sendToUserReturnType;
<del> private MethodParameter sendToUserSingleSessionReturnType;
<del> private MethodParameter sendToUserDefaultDestReturnType;
<del> private MethodParameter sendToUserSingleSessionDefaultDestReturnType;
<del> private MethodParameter jsonViewReturnType;
<del> private MethodParameter defaultNoAnnotation;
<del> private MethodParameter defaultEmptyAnnotation;
<del> private MethodParameter defaultOverrideAnnotation;
<del> private MethodParameter userDefaultNoAnnotation;
<del> private MethodParameter userDefaultEmptyAnnotation;
<del> private MethodParameter userDefaultOverrideAnnotation;
<add> private MethodParameter noAnnotationsReturnType = param("handleNoAnnotations");
<add> private MethodParameter sendToReturnType = param("handleAndSendTo");
<add> private MethodParameter sendToDefaultDestReturnType = param("handleAndSendToDefaultDest");
<add> private MethodParameter sendToWithPlaceholdersReturnType = param("handleAndSendToWithPlaceholders");
<add> private MethodParameter sendToUserReturnType = param("handleAndSendToUser");
<add> private MethodParameter sendToUserInSessionReturnType = param("handleAndSendToUserInSession");
<add> private MethodParameter sendToUserDefaultDestReturnType = param("handleAndSendToUserDefaultDest");
<add> private MethodParameter sendToUserInSessionDefaultDestReturnType = param("handleAndSendToUserDefaultDestInSession");
<add> private MethodParameter jsonViewReturnType = param("handleAndSendToJsonView");
<add> private MethodParameter defaultNoAnnotation = param(SendToTestBean.class, "handleNoAnnotation");
<add> private MethodParameter defaultEmptyAnnotation = param(SendToTestBean.class, "handleAndSendToDefaultDest");
<add> private MethodParameter defaultOverrideAnnotation = param(SendToTestBean.class, "handleAndSendToOverride");
<add> private MethodParameter userDefaultNoAnnotation = param(SendToUserTestBean.class, "handleNoAnnotation");
<add> private MethodParameter userDefaultEmptyAnnotation = param(SendToUserTestBean.class, "handleAndSendToDefaultDest");
<add> private MethodParameter userDefaultOverrideAnnotation = param(SendToUserTestBean.class, "handleAndSendToOverride");
<add>
<add> private MethodParameter param(String methodName) {
<add> return param(getClass(), methodName);
<add> }
<add>
<add> private static MethodParameter param(Class<?> clazz, String methodName) {
<add> try {
<add> return new SynthesizingMethodParameter(clazz.getDeclaredMethod(methodName), -1);
<add> }
<add> catch (NoSuchMethodException ex) {
<add> throw new IllegalArgumentException("No such method", ex);
<add> }
<add> }
<ide>
<ide>
<ide> @Before
<ide> public void setup() throws Exception {
<ide> SimpMessagingTemplate jsonMessagingTemplate = new SimpMessagingTemplate(this.messageChannel);
<ide> jsonMessagingTemplate.setMessageConverter(new MappingJackson2MessageConverter());
<ide> this.jsonHandler = new SendToMethodReturnValueHandler(jsonMessagingTemplate, true);
<del>
<del> Method method = getClass().getDeclaredMethod("handleNoAnnotations");
<del> this.noAnnotationsReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToDefaultDestination");
<del> this.sendToDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendTo");
<del> this.sendToReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToWithPlaceholders");
<del> this.sendToWithPlaceholdersReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToUser");
<del> this.sendToUserReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToUserSingleSession");
<del> this.sendToUserSingleSessionReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToUserDefaultDestination");
<del> this.sendToUserDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToUserDefaultDestinationSingleSession");
<del> this.sendToUserSingleSessionDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = getClass().getDeclaredMethod("handleAndSendToJsonView");
<del> this.jsonViewReturnType = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToTestBean.class.getDeclaredMethod("handleNoAnnotation");
<del> this.defaultNoAnnotation = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToTestBean.class.getDeclaredMethod("handleAndSendToDefaultDestination");
<del> this.defaultEmptyAnnotation = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToTestBean.class.getDeclaredMethod("handleAndSendToOverride");
<del> this.defaultOverrideAnnotation = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToUserTestBean.class.getDeclaredMethod("handleNoAnnotation");
<del> this.userDefaultNoAnnotation = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToUserTestBean.class.getDeclaredMethod("handleAndSendToDefaultDestination");
<del> this.userDefaultEmptyAnnotation = new SynthesizingMethodParameter(method, -1);
<del>
<del> method = SendToUserTestBean.class.getDeclaredMethod("handleAndSendToOverride");
<del> this.userDefaultOverrideAnnotation = new SynthesizingMethodParameter(method, -1);
<ide> }
<ide>
<del>
<ide> @Test
<ide> public void supportsReturnType() throws Exception {
<ide> assertTrue(this.handler.supportsReturnType(this.sendToReturnType));
<ide> public void sendToUserSingleSession() throws Exception {
<ide> String sessionId = "sess1";
<ide> TestUser user = new TestUser();
<ide> Message<?> inputMessage = createMessage(sessionId, "sub1", null, null, user);
<del> this.handler.handleReturnValue(PAYLOAD, this.sendToUserSingleSessionReturnType, inputMessage);
<add> this.handler.handleReturnValue(PAYLOAD, this.sendToUserInSessionReturnType, inputMessage);
<ide>
<ide> verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
<ide>
<ide> public void sendToUserSingleSession() throws Exception {
<ide> assertEquals(MIME_TYPE, accessor.getContentType());
<ide> assertEquals("/user/" + user.getName() + "/dest1", accessor.getDestination());
<ide> assertNull("Subscription id should not be copied", accessor.getSubscriptionId());
<del> assertEquals(this.sendToUserSingleSessionReturnType,
<add> assertEquals(this.sendToUserInSessionReturnType,
<ide> accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
<ide>
<ide> accessor = getCapturedAccessor(1);
<ide> assertEquals(sessionId, accessor.getSessionId());
<ide> assertEquals("/user/" + user.getName() + "/dest2", accessor.getDestination());
<ide> assertEquals(MIME_TYPE, accessor.getContentType());
<ide> assertNull("Subscription id should not be copied", accessor.getSubscriptionId());
<del> assertEquals(this.sendToUserSingleSessionReturnType,
<add> assertEquals(this.sendToUserInSessionReturnType,
<ide> accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
<ide> }
<ide>
<ide> public void sendToUserDefaultDestinationSingleSession() throws Exception {
<ide> String sessionId = "sess1";
<ide> TestUser user = new TestUser();
<ide> Message<?> message = createMessage(sessionId, "sub1", "/app", "/dest", user);
<del> this.handler.handleReturnValue(PAYLOAD, this.sendToUserSingleSessionDefaultDestReturnType, message);
<add> this.handler.handleReturnValue(PAYLOAD, this.sendToUserInSessionDefaultDestReturnType, message);
<ide>
<ide> verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
<ide>
<ide> public void sendToUserDefaultDestinationSingleSession() throws Exception {
<ide> assertEquals("/user/" + user.getName() + "/queue/dest", accessor.getDestination());
<ide> assertEquals(MIME_TYPE, accessor.getContentType());
<ide> assertNull("Subscription id should not be copied", accessor.getSubscriptionId());
<del> assertEquals(this.sendToUserSingleSessionDefaultDestReturnType,
<add> assertEquals(this.sendToUserInSessionDefaultDestReturnType,
<ide> accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
<ide> }
<ide>
<ide> String handleNoAnnotations() {
<ide>
<ide> @SendTo
<ide> @SuppressWarnings("unused")
<del> String handleAndSendToDefaultDestination() {
<add> String handleAndSendToDefaultDest() {
<ide> return PAYLOAD;
<ide> }
<ide>
<ide> String handleAndSendToWithPlaceholders() {
<ide>
<ide> @SendToUser
<ide> @SuppressWarnings("unused")
<del> String handleAndSendToUserDefaultDestination() {
<add> String handleAndSendToUserDefaultDest() {
<ide> return PAYLOAD;
<ide> }
<ide>
<ide> @SendToUser(broadcast = false)
<ide> @SuppressWarnings("unused")
<del> String handleAndSendToUserDefaultDestinationSingleSession() {
<add> String handleAndSendToUserDefaultDestInSession() {
<ide> return PAYLOAD;
<ide> }
<ide>
<ide> String handleAndSendToUser() {
<ide>
<ide> @SendToUser(destinations = { "/dest1", "/dest2" }, broadcast = false)
<ide> @SuppressWarnings("unused")
<del> String handleAndSendToUserSingleSession() {
<add> String handleAndSendToUserInSession() {
<ide> return PAYLOAD;
<ide> }
<ide>
<ide> String handleNoAnnotation() {
<ide> }
<ide>
<ide> @SendTo
<del> String handleAndSendToDefaultDestination() {
<add> String handleAndSendToDefaultDest() {
<ide> return PAYLOAD;
<ide> }
<ide>
<ide> String handleNoAnnotation() {
<ide> }
<ide>
<ide> @SendToUser
<del> String handleAndSendToDefaultDestination() {
<add> String handleAndSendToDefaultDest() {
<ide> return PAYLOAD;
<ide> }
<ide> | 1 |
Text | Text | add sam-github as collaborator | b6201297154a08696b555420e90df676d2e7154b | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Nicu Micleușanu** ([@micnic](https://github.com/micnic)) <micnic90@gmail.com>
<ide> * **Aleksey Smolenchuk** ([@lxe](https://github.com/lxe)) <lxe@lxe.co>
<ide> * **Shigeki Ohtsu** ([@shigeki](https://github.com/shigeki)) <ohtsu@iij.ad.jp>
<add>* **Sam Roberts** ([@sam-github](https://github.com/sam-github)) <vieuxtech@gmail.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Javascript | Javascript | add cause to domexception | 00e5617533c29a6b0cfd9b5148604b441e8bd3b8 | <ide><path>lib/internal/per_context/domexception.js
<ide> const disusedNamesSet = new SafeSet()
<ide> .add('ValidationError');
<ide>
<ide> class DOMException {
<del> constructor(message = '', name = 'Error') {
<add> constructor(message = '', options = 'Error') {
<ide> ErrorCaptureStackTrace(this);
<del> internalsMap.set(this, {
<del> message: `${message}`,
<del> name: `${name}`
<del> });
<add>
<add> if (options && typeof options === 'object') {
<add> const { name } = options;
<add> internalsMap.set(this, {
<add> message: `${message}`,
<add> name: `${name}`
<add> });
<add>
<add> if ('cause' in options) {
<add> ObjectDefineProperty(this, 'cause', {
<add> __proto__: null,
<add> value: options.cause,
<add> configurable: true,
<add> writable: true,
<add> enumerable: false,
<add> });
<add> }
<add> } else {
<add> internalsMap.set(this, {
<add> message: `${message}`,
<add> name: `${options}`
<add> });
<add> }
<ide> }
<ide>
<ide> get name() {
<ide><path>test/parallel/test-domexception-cause.js
<add>'use strict';
<add>
<add>require('../common');
<add>const { strictEqual, deepStrictEqual } = require('assert');
<add>
<add>{
<add> const domException = new DOMException('no cause', 'abc');
<add> strictEqual(domException.name, 'abc');
<add> strictEqual('cause' in domException, false);
<add> strictEqual(domException.cause, undefined);
<add>}
<add>
<add>{
<add> const domException = new DOMException('with undefined cause', { name: 'abc', cause: undefined });
<add> strictEqual(domException.name, 'abc');
<add> strictEqual('cause' in domException, true);
<add> strictEqual(domException.cause, undefined);
<add>}
<add>
<add>{
<add> const domException = new DOMException('with string cause', { name: 'abc', cause: 'foo' });
<add> strictEqual(domException.name, 'abc');
<add> strictEqual('cause' in domException, true);
<add> strictEqual(domException.cause, 'foo');
<add>}
<add>
<add>{
<add> const object = { reason: 'foo' };
<add> const domException = new DOMException('with object cause', { name: 'abc', cause: object });
<add> strictEqual(domException.name, 'abc');
<add> strictEqual('cause' in domException, true);
<add> deepStrictEqual(domException.cause, object);
<add>} | 2 |
Javascript | Javascript | use lowercase properly in function names | 9b14e80fd5ff39b1b8e9833d80c2a2e3569b42d9 | <ide><path>crypto.js
<ide>
<ide> 'use strict';
<ide>
<del>var ARCFourCipher = (function aRCFourCipher() {
<add>var ARCFourCipher = (function arcFourCipher() {
<ide> function constructor(key) {
<ide> this.a = 0;
<ide> this.b = 0;
<ide> var ARCFourCipher = (function aRCFourCipher() {
<ide> }
<ide>
<ide> constructor.prototype = {
<del> encryptBlock: function aRCFourCipherEncryptBlock(data) {
<add> encryptBlock: function arcFourCipherEncryptBlock(data) {
<ide> var i, n = data.length, tmp, tmp2;
<ide> var a = this.a, b = this.b, s = this.s;
<ide> var output = new Uint8Array(n);
<ide> var NullCipher = (function nullCipher() {
<ide> return constructor;
<ide> })();
<ide>
<del>var AES128Cipher = (function aES128Cipher() {
<add>var AES128Cipher = (function aes128Cipher() {
<ide> var rcon = new Uint8Array([
<ide> 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
<ide> 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
<ide> var AES128Cipher = (function aES128Cipher() {
<ide> }
<ide>
<ide> constructor.prototype = {
<del> decryptBlock: function aES128CipherDecryptBlock(data) {
<add> decryptBlock: function aes128CipherDecryptBlock(data) {
<ide> var i, sourceLength = data.length;
<ide> var buffer = this.buffer, bufferLength = this.bufferPosition;
<ide> // waiting for IV values -- they are at the start of the stream
<ide><path>fonts.js
<ide> var CFFStrings = [
<ide>
<ide> var type1Parser = new Type1Parser();
<ide>
<del>var CFF = function cFF(name, file, properties) {
<add>var CFF = function cffCFF(name, file, properties) {
<ide> // Get the data block containing glyphs and subrs informations
<ide> var headerBlock = file.getBytes(properties.length1);
<ide> type1Parser.extractFontHeader(headerBlock, properties);
<ide> CFF.prototype = {
<ide> 'names': this.createCFFIndexHeader([name]),
<ide>
<ide> 'topDict': (function topDict(self) {
<del> return function cFFWrapTopDict() {
<add> return function cffWrapTopDict() {
<ide> var header = '\x00\x01\x01\x01';
<ide> var dict =
<ide> '\xf8\x1b\x00' + // version
<ide> CFF.prototype = {
<ide> 'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs),
<ide> true),
<ide>
<del> 'private': (function cFFWrapPrivate(self) {
<add> 'private': (function cffWrapPrivate(self) {
<ide> var data =
<ide> '\x8b\x14' + // defaultWidth
<ide> '\x8b\x15'; // nominalWidth
<ide><path>pdf.js
<ide> var AsciiHexStream = (function asciiHexStream() {
<ide> return constructor;
<ide> })();
<ide>
<del>var CCITTFaxStream = (function cCITTFaxStream() {
<add>var CCITTFaxStream = (function ccittFaxStream() {
<ide>
<ide> var ccittEOL = -2;
<ide> var twoDimPass = 0;
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide>
<ide> constructor.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlock = function cCITTFaxStreamReadBlock() {
<add> constructor.prototype.readBlock = function ccittFaxStreamReadBlock() {
<ide> while (!this.eof) {
<ide> var c = this.lookChar();
<ide> this.buf = EOF;
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> };
<ide>
<ide> constructor.prototype.addPixels =
<del> function cCITTFaxStreamAddPixels(a1, blackPixels) {
<add> function ccittFaxStreamAddPixels(a1, blackPixels) {
<ide> var codingLine = this.codingLine;
<ide> var codingPos = this.codingPos;
<ide>
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> };
<ide>
<ide> constructor.prototype.addPixelsNeg =
<del> function cCITTFaxStreamAddPixelsNeg(a1, blackPixels) {
<add> function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
<ide> var codingLine = this.codingLine;
<ide> var codingPos = this.codingPos;
<ide>
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> this.codingPos = codingPos;
<ide> };
<ide>
<del> constructor.prototype.lookChar = function cCITTFaxStreamLookChar() {
<add> constructor.prototype.lookChar = function ccittFaxStreamLookChar() {
<ide> if (this.buf != EOF)
<ide> return this.buf;
<ide>
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> return this.buf;
<ide> };
<ide>
<del> constructor.prototype.getTwoDimCode = function cCITTFaxStreamGetTwoDimCode() {
<add> constructor.prototype.getTwoDimCode = function ccittFaxStreamGetTwoDimCode() {
<ide> var code = 0;
<ide> var p;
<ide> if (this.eoblock) {
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> return EOF;
<ide> };
<ide>
<del> constructor.prototype.getWhiteCode = function cCITTFaxStreamGetWhiteCode() {
<add> constructor.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() {
<ide> var code = 0;
<ide> var p;
<ide> var n;
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> return 1;
<ide> };
<ide>
<del> constructor.prototype.getBlackCode = function cCITTFaxStreamGetBlackCode() {
<add> constructor.prototype.getBlackCode = function ccittFaxStreamGetBlackCode() {
<ide> var code, p;
<ide> if (this.eoblock) {
<ide> code = this.lookBits(13);
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> return 1;
<ide> };
<ide>
<del> constructor.prototype.lookBits = function cCITTFaxStreamLookBits(n) {
<add> constructor.prototype.lookBits = function ccittFaxStreamLookBits(n) {
<ide> var c;
<ide> while (this.inputBits < n) {
<ide> if ((c = this.str.getByte()) == null) {
<ide> var CCITTFaxStream = (function cCITTFaxStream() {
<ide> return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
<ide> };
<ide>
<del> constructor.prototype.eatBits = function cCITTFaxStreamEatBits(n) {
<add> constructor.prototype.eatBits = function ccittFaxStreamEatBits(n) {
<ide> if ((this.inputBits -= n) < 0)
<ide> this.inputBits = 0;
<ide> };
<ide>
<ide> return constructor;
<ide> })();
<ide>
<del>var LZWStream = (function lZWStream() {
<add>var LZWStream = (function lzwStream() {
<ide> function constructor(str, earlyChange) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide> var LZWStream = (function lZWStream() {
<ide>
<ide> constructor.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBits = function lZWStreamReadBits(n) {
<add> constructor.prototype.readBits = function lzwStreamReadBits(n) {
<ide> var bitsCached = this.bitsCached;
<ide> var cachedData = this.cachedData;
<ide> while (bitsCached < n) {
<ide> var LZWStream = (function lZWStream() {
<ide> return (cachedData >>> bitsCached) & ((1 << n) - 1);
<ide> };
<ide>
<del> constructor.prototype.readBlock = function lZWStreamReadBlock() {
<add> constructor.prototype.readBlock = function lzwStreamReadBlock() {
<ide> var blockSize = 512;
<ide> var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
<ide> var i, j, q;
<ide> var Catalog = (function catalogCatalog() {
<ide> return constructor;
<ide> })();
<ide>
<del>var PDFDoc = (function pDFDoc() {
<add>var PDFDoc = (function pdfDoc() {
<ide> function constructor(stream) {
<ide> assertWellFormed(stream.length > 0, 'stream must have data');
<ide> this.stream = stream;
<ide> var PDFDoc = (function pDFDoc() {
<ide> },
<ide> // Find the header, remove leading garbage and setup the stream
<ide> // starting from the header.
<del> checkHeader: function pDFDocCheckHeader() {
<add> checkHeader: function pdfDocCheckHeader() {
<ide> var stream = this.stream;
<ide> stream.reset();
<ide> if (find(stream, '%PDF-', 1024)) {
<ide> var PDFDoc = (function pDFDoc() {
<ide> }
<ide> // May not be a PDF file, continue anyway.
<ide> },
<del> setup: function pDFDocSetup(ownerPassword, userPassword) {
<add> setup: function pdfDocSetup(ownerPassword, userPassword) {
<ide> this.checkHeader();
<ide> this.xref = new XRef(this.stream,
<ide> this.startXRef,
<ide> var PDFDoc = (function pDFDoc() {
<ide> // shadow the prototype getter
<ide> return shadow(this, 'numPages', num);
<ide> },
<del> getPage: function pDFDocGetPage(n) {
<add> getPage: function pdfDocGetPage(n) {
<ide> return this.catalog.getPage(n);
<ide> }
<ide> };
<ide> var TilingPattern = (function tilingPattern() {
<ide> })();
<ide>
<ide>
<del>var PDFImage = (function pDFImage() {
<add>var PDFImage = (function pdfImage() {
<ide> function constructor(xref, res, image, inline) {
<ide> this.image = image;
<ide> if (image.getParams) {
<ide> var PDFImage = (function pDFImage() {
<ide> return constructor;
<ide> })();
<ide>
<del>var PDFFunction = (function pDFFunction() {
<add>var PDFFunction = (function pdfFunction() {
<ide> function constructor(xref, fn) {
<ide> var dict = fn.dict;
<ide> if (!dict)
<ide> var PDFFunction = (function pDFFunction() {
<ide> }
<ide>
<ide> constructor.prototype = {
<del> constructSampled: function pDFFunctionConstructSampled(str, dict) {
<add> constructSampled: function pdfFunctionConstructSampled(str, dict) {
<ide> var domain = dict.get('Domain');
<ide> var range = dict.get('Range');
<ide>
<ide> var PDFFunction = (function pDFFunction() {
<ide>
<ide> var samples = this.getSampleArray(size, outputSize, bps, str);
<ide>
<del> this.func = function pDFFunctionFunc(args) {
<del> var clip = function pDFFunctionClip(v, min, max) {
<add> this.func = function pdfFunctionFunc(args) {
<add> var clip = function pdfFunctionClip(v, min, max) {
<ide> if (v > max)
<ide> v = max;
<ide> else if (v < min)
<ide> var PDFFunction = (function pDFFunction() {
<ide> return output;
<ide> };
<ide> },
<del> getSampleArray: function pDFFunctionGetSampleArray(size, outputSize, bps,
<add> getSampleArray: function pdfFunctionGetSampleArray(size, outputSize, bps,
<ide> str) {
<ide> var length = 1;
<ide> for (var i = 0; i < size.length; i++)
<ide> var PDFFunction = (function pDFFunction() {
<ide> }
<ide> return array;
<ide> },
<del> constructInterpolated: function pDFFunctionConstructInterpolated(str,
<add> constructInterpolated: function pdfFunctionConstructInterpolated(str,
<ide> dict) {
<ide> var c0 = dict.get('C0') || [0];
<ide> var c1 = dict.get('C1') || [1];
<ide> var PDFFunction = (function pDFFunction() {
<ide> for (var i = 0; i < length; ++i)
<ide> diff.push(c1[i] - c0[i]);
<ide>
<del> this.func = function pDFFunctionConstructInterpolatedFunc(args) {
<add> this.func = function pdfFunctionConstructInterpolatedFunc(args) {
<ide> var x = args[0];
<ide>
<ide> var out = [];
<ide> var PDFFunction = (function pDFFunction() {
<ide> return out;
<ide> };
<ide> },
<del> constructStiched: function pDFFunctionConstructStiched(fn, dict, xref) {
<add> constructStiched: function pdfFunctionConstructStiched(fn, dict, xref) {
<ide> var domain = dict.get('Domain');
<ide> var range = dict.get('Range');
<ide>
<ide> var PDFFunction = (function pDFFunction() {
<ide> var bounds = dict.get('Bounds');
<ide> var encode = dict.get('Encode');
<ide>
<del> this.func = function pDFFunctionConstructStichedFunc(args) {
<del> var clip = function pDFFunctionConstructStichedFuncClip(v, min, max) {
<add> this.func = function pdfFunctionConstructStichedFunc(args) {
<add> var clip = function pdfFunctionConstructStichedFuncClip(v, min, max) {
<ide> if (v > max)
<ide> v = max;
<ide> else if (v < min)
<ide> var PDFFunction = (function pDFFunction() {
<ide> return fns[i].func([v2]);
<ide> };
<ide> },
<del> constructPostScript: function pDFFunctionConstructPostScript() {
<add> constructPostScript: function pdfFunctionConstructPostScript() {
<ide> TODO('unhandled type of function');
<del> this.func = function pDFFunctionConstructPostScriptFunc() {
<add> this.func = function pdfFunctionConstructPostScriptFunc() {
<ide> return [255, 105, 180];
<ide> };
<ide> } | 3 |
Text | Text | add link to security email directly. | 10c4f5d13338151cc4e75cefb9dfabfd8cf636be | <ide><path>SECURITY.md
<del>Visit https://vercel.com/security to view the disclosure policy.
<add># Reporting Security Issues
<add>
<add>If you believe you have found a security vulnerability in Next.js, we encourage you to let us know right away.
<add>
<add>We will investigate all legitimate reports and do our best to quickly fix the problem.
<add>
<add>Email `security@vercel.com` to disclose any security vulnerabilities.
<add>
<add>https://vercel.com/security | 1 |
Java | Java | add default viewresolver to mvc java config | dfcc1d7e8c8051004b6a8cd8329eed0f6c71efd2 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
<ide> import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
<ide> import org.springframework.web.servlet.resource.ResourceUrlProvider;
<ide> import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor;
<add>import org.springframework.web.servlet.view.InternalResourceViewResolver;
<ide> import org.springframework.web.servlet.view.ViewResolverComposite;
<ide> import org.springframework.web.util.UrlPathHelper;
<ide>
<ide> protected final void addDefaultHandlerExceptionResolvers(List<HandlerExceptionRe
<ide> * {@link org.springframework.core.Ordered#HIGHEST_PRECEDENCE
<ide> * Ordered.HIGHEST_PRECEDENCE}.
<ide> *
<add> * <p>An {@code InternalResourceViewResolver} is added by default if no other
<add> * resolvers are configured.
<add> *
<ide> * @since 4.1
<ide> */
<ide> @Bean
<ide> public ViewResolver mvcViewResolver() {
<ide> registry.setApplicationContext(this.applicationContext);
<ide> configureViewResolvers(registry);
<ide>
<add> List<ViewResolver> viewResolvers = registry.getViewResolvers();
<add> if (viewResolvers.isEmpty()) {
<add> viewResolvers.add(new InternalResourceViewResolver());
<add> }
<add>
<ide> ViewResolverComposite composite = new ViewResolverComposite();
<ide> composite.setOrder(registry.getOrder());
<del> composite.setViewResolvers(registry.getViewResolvers());
<add> composite.setViewResolvers(viewResolvers);
<ide> composite.setApplicationContext(this.applicationContext);
<ide> composite.setServletContext(this.servletContext);
<ide> return composite;
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java
<ide> import org.springframework.web.servlet.HandlerExceptionResolver;
<ide> import org.springframework.web.servlet.HandlerExecutionChain;
<ide> import org.springframework.web.servlet.ViewResolver;
<add>import org.springframework.web.servlet.view.InternalResourceViewResolver;
<ide> import org.springframework.web.servlet.view.ViewResolverComposite;
<ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping;
<ide> import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
<ide> public void viewResolvers() throws Exception {
<ide> ViewResolverComposite compositeResolver = this.wac.getBean(ViewResolverComposite.class);
<ide> assertEquals(Ordered.LOWEST_PRECEDENCE, compositeResolver.getOrder());
<ide> List<ViewResolver> resolvers = compositeResolver.getViewResolvers();
<del> assertEquals(0, resolvers.size());
<add> assertEquals(1, resolvers.size());
<add> assertEquals(InternalResourceViewResolver.class, resolvers.get(0).getClass());
<ide> }
<ide>
<ide> @Test | 2 |
Javascript | Javascript | add ember.binding#notnull to mixin | 48c37b040feaed97351a7a771a807d29cd9efb9f | <ide><path>packages/ember-metal/lib/binding.js
<ide> mixinProperties(Binding,
<ide> return binding.notEmpty(placeholder);
<ide> },
<ide>
<add> /**
<add> @see Ember.Binding.prototype.notNull
<add> */
<add> notNull: function(from, placeholder) {
<add> var C = this, binding = new C(null, from);
<add> return binding.notNull(placeholder);
<add> },
<add>
<add>
<ide> /**
<ide> @see Ember.Binding.prototype.bool
<ide> */ | 1 |
Javascript | Javascript | improve code in test-fs-readfile-error | 499efbd085975ee603f7a54edbfd7536de566d69 | <ide><path>test/parallel/test-fs-readfile-error.js
<ide> 'use strict';
<del>var common = require('../common');
<del>var assert = require('assert');
<del>var exec = require('child_process').exec;
<del>var path = require('path');
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const exec = require('child_process').exec;
<add>const path = require('path');
<ide>
<ide> // `fs.readFile('/')` does not fail on FreeBSD, because you can open and read
<ide> // the directory there.
<ide> if (process.platform === 'freebsd') {
<ide> }
<ide>
<ide> function test(env, cb) {
<del> var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js');
<del> var execPath = '"' + process.execPath + '" "' + filename + '"';
<del> var options = { env: Object.assign(process.env, env) };
<del> exec(execPath, options, function(err, stdout, stderr) {
<add> const filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js');
<add> const execPath = '"' + process.execPath + '" "' + filename + '"';
<add> const options = { env: Object.assign(process.env, env) };
<add> exec(execPath, options, common.mustCall((err, stdout, stderr) => {
<ide> assert(err);
<del> assert.equal(stdout, '');
<del> assert.notEqual(stderr, '');
<add> assert.strictEqual(stdout, '');
<add> assert.notStrictEqual(stderr, '');
<ide> cb('' + stderr);
<del> });
<add> }));
<ide> }
<ide>
<del>test({ NODE_DEBUG: '' }, common.mustCall(function(data) {
<add>test({ NODE_DEBUG: '' }, common.mustCall((data) => {
<ide> assert(/EISDIR/.test(data));
<ide> assert(!/test-fs-readfile-error/.test(data));
<ide> }));
<ide>
<del>test({ NODE_DEBUG: 'fs' }, common.mustCall(function(data) {
<add>test({ NODE_DEBUG: 'fs' }, common.mustCall((data) => {
<ide> assert(/EISDIR/.test(data));
<ide> assert(/test-fs-readfile-error/.test(data));
<ide> })); | 1 |
Ruby | Ruby | use patch found in the path | e32299e6527e51a06dbe3966dcaae0bca775808f | <ide><path>Library/Homebrew/patch.rb
<ide> def contents; end
<ide>
<ide> def apply
<ide> data = contents.gsub("HOMEBREW_PREFIX", HOMEBREW_PREFIX)
<del> cmd = "/usr/bin/patch"
<ide> args = %W[-g 0 -f -#{strip}]
<del> IO.popen("#{cmd} #{args.join(" ")}", "w") { |p| p.write(data) }
<del> raise ErrorDuringExecution.new(cmd, args) unless $CHILD_STATUS.success?
<add> Utils.popen_write("patch", *args) { |p| p.write(data) }
<add> raise ErrorDuringExecution.new("patch", args) unless $CHILD_STATUS.success?
<ide> end
<ide>
<ide> def inspect
<ide> def apply
<ide> patch_files.each do |patch_file|
<ide> ohai "Applying #{patch_file}"
<ide> patch_file = patch_dir/patch_file
<del> safe_system "/usr/bin/patch", "-g", "0", "-f", "-#{strip}", "-i", patch_file
<add> safe_system "patch", "-g", "0", "-f", "-#{strip}", "-i", patch_file
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove dead code | d61977f03ed6952342aa2ed69a8fc515c2143d94 | <ide><path>test/parallel/test-http-many-ended-pipelines.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>
<del>// No warnings should happen!
<del>const trace = console.trace;
<del>console.trace = function() {
<del> trace.apply(console, arguments);
<del> throw new Error('no tracing should happen here');
<del>};
<del>
<ide> const http = require('http');
<ide> const net = require('net');
<ide> | 1 |
Ruby | Ruby | remove the as_variable method | f8f2f9ce32965c06a7af588582ed2f0d03b4c543 | <ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def render(partial, context, options, block)
<ide> @details = extract_details(options)
<ide> @path = partial
<ide>
<del> as = as_variable(options)
<del>
<del> template = find_template(@path, template_keys(@path, as))
<add> template = find_template(@path, template_keys(@path))
<ide>
<ide> if !block && (layout = @options[:layout])
<del> layout = find_template(layout.to_s, template_keys(@path, as))
<add> layout = find_template(layout.to_s, template_keys(@path))
<ide> end
<ide>
<ide> render_partial_template(context, @locals, template, layout, block)
<ide> end
<ide>
<ide> private
<del> def template_keys(path, as)
<add> def template_keys(path)
<ide> @locals.keys
<ide> end
<ide>
<ide> def render_partial_template(view, locals, template, layout, block)
<ide> end
<ide> end
<ide>
<del> def as_variable(options)
<del> if as = options[:as]
<del> raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s)
<del> as.to_sym
<del> end
<del> end
<del>
<ide> def find_template(path, locals)
<ide> prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
<ide> @lookup_context.find_template(path, prefixes, true, locals, @details)
<ide> def merge_prefix_into_object_path(prefix, object_path)
<ide> end
<ide> end
<ide>
<del> def retrieve_variable(path, as)
<del> variable = as || begin
<del> base = path[-1] == "/" ? "" : File.basename(path)
<del> raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/
<del> $1.to_sym
<add> def retrieve_variable(path)
<add> variable = if as = @options[:as]
<add> raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s)
<add> as.to_sym
<add> else
<add> begin
<add> base = path[-1] == "/" ? "" : File.basename(path)
<add> raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/
<add> $1.to_sym
<add> end
<ide> end
<ide> [variable]
<ide> end
<ide> def each_with_info
<ide> end
<ide>
<ide> def render_collection_with_partial(collection, partial, context, options, block)
<del> as = as_variable(options)
<del>
<ide> @options = options
<ide>
<ide> @locals = options[:locals] || {}
<ide> @details = extract_details(options)
<ide> @path = partial
<ide>
<del> @collection = build_collection_iterator(collection, partial, as, context)
<add> @collection = build_collection_iterator(collection, partial, context)
<ide>
<ide> if options[:cached] && !partial
<ide> raise NotImplementedError, "render caching requires a template. Please specify a partial when rendering"
<ide> end
<ide>
<del> template = find_template(partial, template_keys(partial, as)) if partial
<add> template = find_template(partial, template_keys(partial)) if partial
<ide>
<ide> if !block && (layout = options[:layout])
<del> layout = find_template(layout.to_s, template_keys(partial, as))
<add> layout = find_template(layout.to_s, template_keys(partial))
<ide> end
<ide>
<ide> render_collection(context, template, layout)
<ide> def render_collection_derive_partial(collection, context, options, block)
<ide> end
<ide>
<ide> private
<del> def template_keys(path, as)
<del> super + retrieve_variable(path, as)
<add> def template_keys(path)
<add> super + retrieve_variable(path)
<ide> end
<ide>
<del> def retrieve_variable(path, as)
<add> def retrieve_variable(path)
<ide> vars = super
<ide> variable = vars.first
<ide> vars << :"#{variable}_counter"
<ide> vars << :"#{variable}_iteration"
<ide> vars
<ide> end
<ide>
<del> def build_collection_iterator(collection, path, as, context)
<add> def build_collection_iterator(collection, path, context)
<ide> if path
<del> SameCollectionIterator.new(collection, path, retrieve_variable(path, as))
<add> SameCollectionIterator.new(collection, path, retrieve_variable(path))
<ide> else
<ide> paths = collection.map { |o| partial_path(o, context) }
<del> paths.map! { |path| retrieve_variable(path, as).unshift(path) }
<add> paths.map! { |path| retrieve_variable(path).unshift(path) }
<ide> @path = nil
<ide> MixedCollectionIterator.new(collection, paths)
<ide> end
<ide> def render_object_derive_partial(object, context, options, block)
<ide>
<ide> private
<ide>
<del> def template_keys(path, as)
<del> super + retrieve_variable(path, as)
<add> def template_keys(path)
<add> super + retrieve_variable(path)
<ide> end
<ide>
<ide> def render_partial_template(view, locals, template, layout, block) | 1 |
Java | Java | increase timeout in stompwebsocketintegrationtests | c572d0c46972dafd6b53b3a8f2fcacfc426b7cf7 | <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java
<ide>
<ide> package org.springframework.web.socket.messaging;
<ide>
<del>import java.lang.annotation.ElementType;
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.RetentionPolicy;
<del>import java.lang.annotation.Target;
<del>import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.concurrent.CopyOnWriteArrayList;
<ide> import java.util.concurrent.CountDownLatch;
<ide> @RunWith(Parameterized.class)
<ide> public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests {
<ide>
<add> private static final long TIMEOUT = 10;
<add>
<ide> @Parameters(name = "server [{0}], client [{1}]")
<del> public static Iterable<Object[]> arguments() {
<del> return Arrays.asList(new Object[][] {
<add> public static Object[][] arguments() {
<add> return new Object[][] {
<ide> {new JettyWebSocketTestServer(), new JettyWebSocketClient()},
<ide> {new TomcatWebSocketTestServer(), new StandardWebSocketClient()},
<ide> {new UndertowTestServer(), new StandardWebSocketClient()}
<del> });
<add> };
<ide> }
<ide>
<ide>
<ide> public void sendMessageToController() throws Exception {
<ide>
<ide> SimpleController controller = this.wac.getBean(SimpleController.class);
<ide> try {
<del> assertTrue(controller.latch.await(10, TimeUnit.SECONDS));
<add> assertTrue(controller.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide> }
<ide> finally {
<ide> session.close();
<ide> public void sendMessageToControllerAndReceiveReplyViaTopic() throws Exception {
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide>
<ide> try {
<del> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide> }
<ide> finally {
<ide> session.close();
<ide> }
<ide> }
<ide>
<ide> // SPR-10930
<del>
<ide> @Test
<ide> public void sendMessageToBrokerAndReceiveReplyViaTopic() throws Exception {
<ide> TextMessage m1 = create(StompCommand.SUBSCRIBE).headers("id:subs1", "destination:/topic/foo").build();
<ide> public void sendMessageToBrokerAndReceiveReplyViaTopic() throws Exception {
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide>
<ide> try {
<del> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide>
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue("Expected STOMP MESSAGE, got " + payload, payload.startsWith("MESSAGE\n"));
<ide> public void sendMessageToBrokerAndReceiveReplyViaTopic() throws Exception {
<ide> }
<ide>
<ide> // SPR-11648
<del>
<ide> @Test
<ide> public void sendSubscribeToControllerAndReceiveReply() throws Exception {
<ide> String destHeader = "destination:/app/number";
<ide> public void sendSubscribeToControllerAndReceiveReply() throws Exception {
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide>
<ide> try {
<del> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue("Expected STOMP destination=/app/number, got " + payload, payload.contains(destHeader));
<ide> assertTrue("Expected STOMP Payload=42, got " + payload, payload.contains("42"));
<ide> public void handleExceptionAndSendToUser() throws Exception {
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide>
<ide> try {
<del> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue(payload.startsWith("MESSAGE\n"));
<ide> assertTrue(payload.contains("destination:/user/queue/error\n"));
<ide> public void webSocketScope() throws Exception {
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide>
<ide> try {
<del> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue(payload.startsWith("MESSAGE\n"));
<ide> assertTrue(payload.contains("destination:/topic/scopedBeanValue\n"));
<ide> public void webSocketScope() throws Exception {
<ide> }
<ide>
<ide>
<del> @Target({ElementType.TYPE})
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Controller
<ide> private @interface IntegrationTestController {
<ide> static class SimpleController {
<ide>
<ide> private CountDownLatch latch = new CountDownLatch(1);
<ide>
<del> @MessageMapping(value="/simple")
<add> @MessageMapping("/simple")
<ide> public void handle() {
<ide> this.latch.countDown();
<ide> }
<ide>
<del> @MessageMapping(value="/exception")
<add> @MessageMapping("/exception")
<ide> public void handleWithError() {
<ide> throw new IllegalArgumentException("Bad input");
<ide> }
<ide> public String handleException(IllegalArgumentException ex) {
<ide> @IntegrationTestController
<ide> static class IncrementController {
<ide>
<del> @MessageMapping(value="/increment")
<add> @MessageMapping("/increment")
<ide> public int handle(int i) {
<ide> return i + 1;
<ide> }
<ide> public ScopedBeanController(ScopedBean scopedBean) {
<ide> this.scopedBean = scopedBean;
<ide> }
<ide>
<del> @MessageMapping(value="/scopedBeanValue")
<add> @MessageMapping("/scopedBeanValue")
<ide> public String getValue() {
<ide> return this.scopedBean.getValue();
<ide> }
<ide> public void configureMessageBroker(MessageBrokerRegistry configurer) {
<ide> }
<ide>
<ide> @Bean
<del> @Scope(value="websocket", proxyMode=ScopedProxyMode.INTERFACES)
<add> @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.INTERFACES)
<ide> public ScopedBean scopedBean() {
<ide> return new ScopedBeanImpl("55");
<ide> } | 1 |
Text | Text | resolve typos in catdog classifier | c17bd7cd89230c06aa84de1d6de4f0d250da2476 | <ide><path>curriculum/challenges/english/11-machine-learning-with-python/machine-learning-with-python-projects/cat-and-dog-image-classifier.md
<ide> We are still developing the interactive instructional content for the machine le
<ide>
<ide> # --instructions--
<ide>
<del>For this challenge, you will complete the code to classify images of dogs and cats. You will use Tensorflow 2.0 and Keras to create a convolutional neural network that correctly classifies images of cats and dogs at least 63% of the time. (Extra credit if you get it to 70% accuracy!)
<add>For this challenge, you will complete the code to classify images of dogs and cats. You will use TensorFlow 2.0 and Keras to create a convolutional neural network that correctly classifies images of cats and dogs at least 63% of the time. (Extra credit if you get it to 70% accuracy!)
<ide>
<ide> Some of the code is given to you but some code you must fill in to complete this challenge. Read the instruction in each text cell so you will know what you have to do in each code cell.
<ide>
<ide> The `plotImages` function will be used a few times to plot images. It takes an a
<ide>
<ide> Recreate the `train_image_generator` using `ImageDataGenerator`.
<ide>
<del>Since there are a small number of training examples there is a risk of overfitting. One way to fix this problem is by creating more training data from existing training examples by using random transformations.
<add>Since there are a small number of training examples, there is a risk of overfitting. One way to fix this problem is by creating more training data from existing training examples by using random transformations.
<ide>
<ide> Add 4-6 random transformations as arguments to `ImageDataGenerator`. Make sure to rescale the same as before.
<ide>
<ide> In this cell, get the probability that each test image (from `test_data_gen`) is
<ide>
<ide> Call the `plotImages` function and pass in the test images and the probabilities corresponding to each test image.
<ide>
<del>After your run the cell, you should see all 50 test images with a label showing the percentage of "sure" that the image is a cat or a dog. The accuracy will correspond to the accuracy shown in the graph above (after running the previous cell). More training images could lead to a higher accuracy.
<add>After you run the cell, you should see all 50 test images with a label showing the percentage of "sure" that the image is a cat or a dog. The accuracy will correspond to the accuracy shown in the graph above (after running the previous cell). More training images could lead to a higher accuracy.
<ide>
<ide> ## Cell 11
<ide> | 1 |
Go | Go | fix init layer chown of existing dir ownership | 23b771782ab7236ce5024ac5773a6ded9a2af753 | <ide><path>daemon/daemon_unix.go
<ide> func setupInitLayer(initLayer string, rootUID, rootGID int) error {
<ide>
<ide> if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
<ide> if os.IsNotExist(err) {
<del> if err := idtools.MkdirAllAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
<add> if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
<ide> return err
<ide> }
<ide> switch typ {
<ide> case "dir":
<del> if err := idtools.MkdirAllAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
<add> if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
<ide> return err
<ide> }
<ide> case "file":
<ide> f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
<ide> if err != nil {
<ide> return err
<ide> }
<del> f.Close()
<ide> f.Chown(rootUID, rootGID)
<add> f.Close()
<ide> default:
<ide> if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
<ide> return err
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunInvalidReference(c *check.C) {
<ide> }
<ide> }
<ide>
<add>// Test fix for issue #17854
<add>func (s *DockerSuite) TestRunInitLayerPathOwnership(c *check.C) {
<add> // Not applicable on Windows as it does not support Linux uid/gid ownership
<add> testRequires(c, DaemonIsLinux)
<add> name := "testetcfileownership"
<add> _, err := buildImage(name,
<add> `FROM busybox
<add> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<add> RUN echo 'dockerio:x:1001:' >> /etc/group
<add> RUN chown dockerio:dockerio /etc`,
<add> true)
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add>
<add> // Test that dockerio ownership of /etc is retained at runtime
<add> out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc")
<add> out = strings.TrimSpace(out)
<add> if out != "dockerio:dockerio" {
<add> c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out)
<add> }
<add>}
<add>
<ide> func (s *DockerSuite) TestRunWithOomScoreAdj(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> | 2 |
Ruby | Ruby | destructure spec hash more efficiently | 3cda2158817c8d0f62dcc659388de12d834c067c | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def cached_location; end
<ide> class VCSDownloadStrategy < AbstractDownloadStrategy
<ide> def initialize name, resource
<ide> super
<del> specs = resource.specs
<del> @ref_type, @ref = specs.dup.shift unless specs.empty?
<add> @ref_type, @ref = destructure_spec_hash(resource.specs)
<add> end
<add>
<add> def destructure_spec_hash(spec)
<add> spec.each { |o| return o }
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | optimize memoized method if there are no arguments | be0d235a3b82e72de49592913753a1f291a98f86 | <ide><path>activesupport/lib/active_support/memoizable.rb
<ide> def memoize(*symbols)
<ide> raise "Already memoized #{symbol}" if method_defined?(:#{original_method})
<ide> alias #{original_method} #{symbol}
<ide>
<del> def #{symbol}(*args)
<del> #{memoized_ivar} ||= {}
<del> reload = args.pop if args.last == true || args.last == :reload
<add> if instance_method(:#{symbol}).arity == 0
<add> def #{symbol}(reload = false)
<add> if !reload && defined? #{memoized_ivar}
<add> #{memoized_ivar}
<add> else
<add> #{memoized_ivar} = #{original_method}.freeze
<add> end
<add> end
<add> else
<add> def #{symbol}(*args)
<add> #{memoized_ivar} ||= {}
<add> reload = args.pop if args.last == true || args.last == :reload
<ide>
<del> if !reload && #{memoized_ivar} && #{memoized_ivar}.has_key?(args)
<del> #{memoized_ivar}[args]
<del> else
<del> #{memoized_ivar}[args] = #{original_method}(*args).freeze
<add> if !reload && #{memoized_ivar} && #{memoized_ivar}.has_key?(args)
<add> #{memoized_ivar}[args]
<add> else
<add> #{memoized_ivar}[args] = #{original_method}(*args).freeze
<add> end
<ide> end
<ide> end
<ide> EOS | 1 |
Javascript | Javascript | fix outdated test comments | 661562fc52b211cb39459e413c4c5cd5debaf90f | <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Regression test
<ide> function App({text}) {
<ide> return (
<del> <Suspense fallback="Outer fallback">
<add> <Suspense fallback="Loading...">
<ide> <AsyncText ms={2000} text={text} />
<ide> </Suspense>
<ide> );
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide> expect(root).toMatchRenderedOutput(<span prop="Initial" />);
<ide>
<del> // Suspend B. Since showing a fallback would hide content that's already
<add> // Update. Since showing a fallback would hide content that's already
<ide> // visible, it should suspend for a bit without committing.
<ide> await ReactNoop.act(async () => {
<ide> root.render(<App text="First update" />);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(root).toMatchRenderedOutput(<span prop="Initial" />);
<ide> });
<ide>
<del> // Suspend A. This should also suspend for a JND.
<add> // Update again. This should also suspend for a bit.
<ide> await ReactNoop.act(async () => {
<ide> root.render(<App text="Second update" />);
<ide> | 1 |
Javascript | Javascript | fix stack leak on error | d6b78d0e3769e4af1b1a60e89f53faf20e4bb2b3 | <ide><path>lib/domain.js
<ide> exports.create = exports.createDomain = function(cb) {
<ide> // it's possible to enter one domain while already inside
<ide> // another one. the stack is each entered domain.
<ide> var stack = [];
<add>exports._stack = stack;
<ide> // the active domain is always the one that we're currently in.
<ide> exports.active = null;
<ide>
<ide> function uncaughtHandler(er) {
<ide> domain_thrown: true
<ide> });
<ide> exports.active.emit('error', er);
<add> exports.active.exit();
<ide> } else if (process.listeners('uncaughtException').length === 1) {
<ide> // if there are other handlers, then they'll take care of it.
<ide> // but if not, then we need to crash now.
<ide><path>test/simple/test-domain-stack.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>
<add>// Make sure that the domain stack doesn't get out of hand.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var domain = require('domain');
<add>var events = require('events');
<add>
<add>var a = domain.create();
<add>a.name = 'a';
<add>
<add>a.on('error', function() {
<add> if (domain._stack.length > 5) {
<add> console.error('leaking!', domain._stack);
<add> process.exit(1);
<add> }
<add>});
<add>
<add>var foo = a.bind(function() {
<add> throw new Error('error from foo');
<add>});
<add>
<add>for (var i = 0; i < 1000; i++) {
<add> process.nextTick(foo);
<add>} | 2 |
Python | Python | add test cases for linalg | 26a4597fb4db0b09cdaf5d9db817a68019174f75 | <ide><path>numpy/linalg/tests/test_linalg.py
<add>""" Test functions for linalg module
<add>"""
<add>
<add>from numpy.testing import *
<add>set_package_path()
<add>from numpy import array, single, double, csingle, cdouble, dot, identity, \
<add> multiply
<add>from numpy import linalg
<add>restore_path()
<add>
<add>old_assert_almost_equal = assert_almost_equal
<add>def assert_almost_equal(a, b, **kw):
<add> if a.dtype.type in (single, csingle):
<add> decimal = 6
<add> else:
<add> decimal = 12
<add> old_assert_almost_equal(a, b, decimal=decimal, **kw)
<add>
<add>class LinalgTestCase(NumpyTestCase):
<add> def _check(self, dtype):
<add> a = array([[1.,2.], [3.,4.]], dtype=dtype)
<add> b = array([2., 1.], dtype=dtype)
<add> self.do(a, b)
<add>
<add> def check_single(self):
<add> self._check(single)
<add> def check_double(self):
<add> self._check(double)
<add> def check_csingle(self):
<add> self._check(csingle)
<add> def check_cdouble(self):
<add> self._check(cdouble)
<add>
<add>class test_solve(LinalgTestCase):
<add> def do(self, a, b):
<add> x = linalg.solve(a, b)
<add> assert_almost_equal(b, dot(a, x))
<add>
<add>class test_inv(LinalgTestCase):
<add> def do(self, a, b):
<add> a_inv = linalg.inv(a)
<add> assert_almost_equal(dot(a, a_inv), identity(a.shape[0]))
<add>
<add>class test_eigvals(LinalgTestCase):
<add> def do(self, a, b):
<add> ev = linalg.eigvals(a)
<add> evalues, evectors = linalg.eig(a)
<add> assert_almost_equal(ev, evalues)
<add>
<add>class test_eig(LinalgTestCase):
<add> def do(self, a, b):
<add> evalues, evectors = linalg.eig(a)
<add> assert_almost_equal(dot(a, evectors), evectors*evalues)
<add>
<add>class test_svd(LinalgTestCase):
<add> def do(self, a, b):
<add> u, s, vt = linalg.svd(a, 0)
<add> assert_almost_equal(a, dot(u*s, vt))
<add>
<add>class test_pinv(LinalgTestCase):
<add> def do(self, a, b):
<add> a_ginv = linalg.pinv(a)
<add> assert_almost_equal(dot(a, a_ginv), identity(a.shape[0]))
<add>
<add>class test_det(LinalgTestCase):
<add> def do(self, a, b):
<add> d = linalg.det(a)
<add> ev = linalg.eigvals(a)
<add> assert_almost_equal(d, multiply.reduce(ev))
<add>
<add>class test_lstsq(LinalgTestCase):
<add> def do(self, a, b):
<add> u, s, vt = linalg.svd(a, 0)
<add> x, residuals, rank, sv = linalg.lstsq(a, b)
<add> assert_almost_equal(b, dot(a, x))
<add> assert_equal(rank, a.shape[0])
<add> assert_almost_equal(sv, s)
<add>
<add>if __name__ == '__main__':
<add> NumpyTest().run() | 1 |
PHP | PHP | add interface checks | 51ec8846e92ae8adbfd2751d612736464b067cb5 | <ide><path>src/Datasource/RulesChecker.php
<ide> */
<ide> namespace Cake\Datasource;
<ide>
<add>use Cake\Datasource\InvalidPropertyInterface;
<ide> use InvalidArgumentException;
<ide>
<ide> /**
<ide> protected function _addError($rule, $name, $options)
<ide> }
<ide> $entity->errors($options['errorField'], $message);
<ide>
<del> if (isset($entity->{$options['errorField']})) {
<add> if ($entity instanceof InvalidPropertyInterface && isset($entity->{$options['errorField']})) {
<ide> $invalidValue = $entity->{$options['errorField']};
<ide> $entity->invalid($options['errorField'], $invalidValue);
<ide> }
<ide><path>src/ORM/Marshaller.php
<ide> use Cake\Database\Expression\TupleComparison;
<ide> use Cake\Database\Type;
<ide> use Cake\Datasource\EntityInterface;
<add>use Cake\Datasource\InvalidPropertyInterface;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> public function one(array $data, array $options = [])
<ide> $properties = [];
<ide> foreach ($data as $key => $value) {
<ide> if (!empty($errors[$key])) {
<del> $entity->invalid($key, $value);
<add> if ($entity instanceof InvalidPropertyInterface) {
<add> $entity->invalid($key, $value);
<add> }
<ide> continue;
<ide> }
<ide> $columnType = $schema->columnType($key); | 2 |
Ruby | Ruby | verify dependencies map to formulae before locking | 369f9b3251e1206eab10c778e591e054f4a7942b | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def initialize ff
<ide> @poured_bottle = false
<ide> @pour_failed = false
<ide>
<add> verify_deps_exist
<ide> lock
<ide> check_install_sanity
<ide> end
<ide> def pour_bottle? install_bottle_options={:warn=>false}
<ide> install_bottle?(f, install_bottle_options)
<ide> end
<ide>
<add> def verify_deps_exist
<add> f.recursive_dependencies.map(&:to_formula)
<add> rescue FormulaUnavailableError => e
<add> e.dependent = f.name
<add> raise
<add> end
<add>
<ide> def check_install_sanity
<ide> raise FormulaInstallationAlreadyAttemptedError, f if @@attempted.include? f
<ide>
<ide> def check_install_sanity
<ide> raise CannotInstallFormulaError,
<ide> "You must `brew link #{unlinked_deps*' '}' before #{f} can be installed" unless unlinked_deps.empty?
<ide> end
<del>
<del> rescue FormulaUnavailableError => e
<del> # this is sometimes wrong if the dependency chain is more than one deep
<del> # but can't easily fix this without a rewrite FIXME-brew2
<del> e.dependent = f.name
<del> raise
<ide> end
<ide>
<ide> def build_bottle_preinstall | 1 |
Javascript | Javascript | remove ws, fix typo | 7dfedb732dad5ba1f1f21ff611a82ecf8327916c | <ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide> * @description
<ide> * Register callback function that will be called, when url changes.
<ide> *
<del> * It's only called when the url is changed by outside of angular:
<add> * It's only called when the url is changed from outside of angular:
<ide> * - user types different url into address bar
<ide> * - user clicks on history (forward/back) button
<ide> * - user clicks on a link
<ide> function Browser(window, document, $log, $sniffer) {
<ide> /**
<ide> * @name ng.$browser#baseHref
<ide> * @methodOf ng.$browser
<del> *
<add> *
<ide> * @description
<ide> * Returns current <base href>
<ide> * (always relative - without domain)
<ide> function Browser(window, document, $log, $sniffer) {
<ide> * It is not meant to be used directly, use the $cookie service instead.
<ide> *
<ide> * The return values vary depending on the arguments that the method was called with as follows:
<del> *
<add> *
<ide> * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
<ide> * it
<ide> * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
<ide> * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
<ide> * way)
<del> *
<add> *
<ide> * @returns {Object} Hash of all cookies (if called without any parameter)
<ide> */
<ide> self.cookies = function(name, value) { | 1 |
Ruby | Ruby | require active_support after autoload setup | b8e914709c06fceac51384f7484c002fcb715196 | <ide><path>actionpack/lib/action_dispatch.rb
<ide> # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide> #++
<ide>
<del>activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
<del>$:.unshift activesupport_path if File.directory?(activesupport_path)
<del>require 'active_support'
<del>
<ide> require 'rack'
<ide>
<ide> module Rack
<ide> module Session
<ide> end
<ide>
<ide> autoload :Mime, 'action_dispatch/http/mime_type'
<add>
<add>activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
<add>$:.unshift activesupport_path if File.directory?(activesupport_path)
<add>require 'active_support'
<ide><path>actionpack/lib/action_view.rb
<ide> # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide> #++
<ide>
<del>activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
<del>$:.unshift activesupport_path if File.directory?(activesupport_path)
<del>require 'active_support'
<del>require 'active_support/core_ext/class/attribute_accessors'
<del>
<ide> require File.join(File.dirname(__FILE__), "action_pack")
<ide>
<ide> module ActionView
<ide> class ERB
<ide> end
<ide>
<ide> I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
<add>
<add>activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
<add>$:.unshift activesupport_path if File.directory?(activesupport_path)
<add>require 'active_support'
<add>require 'active_support/core_ext/class/attribute_accessors' | 2 |
Ruby | Ruby | add on_macos/on_linux to pourbottlecheck | 509ab86ece78723efdca37fec286faf9c8ee896c | <ide><path>Library/Homebrew/software_spec.rb
<ide> require "compilers"
<ide> require "global"
<ide> require "os/mac/version"
<add>require "extend/on_os"
<ide>
<ide> class SoftwareSpec
<ide> extend T::Sig
<ide> def checksums
<ide> end
<ide>
<ide> class PourBottleCheck
<add> include OnOS
<add>
<ide> def initialize(formula)
<ide> @formula = formula
<ide> end | 1 |
PHP | PHP | bind request before routing again | 9b8490e5c568436748ed142b594879c3e5a90db0 | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> protected function dispatchToRouter()
<ide> {
<ide> return function($request)
<ide> {
<add> $this->app->instance('request', $request);
<add>
<ide> return $this->router->dispatch($request);
<ide> };
<ide> } | 1 |
Python | Python | add comb sort algorithm | 5fb6b31ea928162c5185d66381ae99c7454d33c0 | <ide><path>sorts/comb_sort.py
<add>"""
<add>Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
<add>Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.
<add>
<add>This is pure python implementation of counting sort algorithm
<add>For doctests run following command:
<add>python -m doctest -v comb_sort.py
<add>or
<add>python3 -m doctest -v comb_sort.py
<add>
<add>For manual testing run:
<add>python comb_sort.py
<add>"""
<add>
<add>def comb_sort(data):
<add> """Pure implementation of comb sort algorithm in Python
<add> :param collection: some mutable ordered collection with heterogeneous
<add> comparable items inside
<add> :return: the same collection ordered by ascending
<add> Examples:
<add> >>> comb_sort([0, 5, 3, 2, 2])
<add> [0, 2, 2, 3, 5]
<add> >>> comb_sort([])
<add> []
<add> >>> comb_sort([-2, -5, -45])
<add> [-45, -5, -2]
<add> """
<add> shrink_factor = 1.3
<add> gap = len(data)
<add> swapped = True
<add> i = 0
<add>
<add> while gap > 1 or swapped:
<add> # Update the gap value for a next comb
<add> gap = int(float(gap) / shrink_factor)
<add>
<add> swapped = False
<add> i = 0
<add>
<add> while gap + i < len(data):
<add> if data[i] > data[i+gap]:
<add> # Swap values
<add> data[i], data[i+gap] = data[i+gap], data[i]
<add> swapped = True
<add> i += 1
<add>
<add> return data
<add>
<add>
<add>if __name__ == '__main__':
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<add>
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<add> unsorted = [int(item) for item in user_input.split(',')]
<add> print(comb_sort(unsorted)) | 1 |
Python | Python | use 1/0 instead of booleans in config.h | 499f9b0bd93f5568b8ee86da18e7561839a54519 | <ide><path>numpy/build_utils/__init__.py
<ide> def check_header(self, header_name, **kw):
<ide> validate_arguments(self, kw)
<ide> try_compile(self, kw)
<ide> ret = kw["success"]
<add> if ret == 0:
<add> kw["define_value"] = 1
<add> else:
<add> kw["define_value"] = 0
<ide>
<ide> self.post_check(**kw)
<ide> if not kw.get('execute', False):
<ide> def check_type(self, type_name, **kw):
<ide> validate_arguments(self, kw)
<ide> try_compile(self, kw)
<ide> ret = kw["success"]
<add> if ret == 0:
<add> kw["define_value"] = 1
<add> else:
<add> kw["define_value"] = 0
<ide>
<ide> kw["define_name"] = "HAVE_%s" % sanitize_string(type_name)
<ide> kw["define_comment"] = "/* Set to 1 if %s is defined. */" % type_name | 1 |
Text | Text | add security issues to contributing.md | 54c3dd10dd2622b2cfe0e3b54226689828f3b5bd | <ide><path>CONTRIBUTING.md
<ide> Check the [cakephp-codesniffer](https://github.com/cakephp/cakephp-codesniffer)
<ide> repository to setup the CakePHP standard. The [README](https://github.com/cakephp/cakephp-codesniffer/blob/master/README.md) contains installation info
<ide> for the sniff and phpcs.
<ide>
<add>## Reporting a Security Issue
<add>
<add>If you've found a security related issue in CakePHP, please don't open an issue in github. Instead contact us at security@cakephp.org. For more information on how we handle security issues, [see the CakePHP Security Issue Process](http://book.cakephp.org/3.0/en/contributing/tickets.html#reporting-security-issues).
<add>
<ide> # Additional Resources
<ide>
<ide> * [CakePHP coding standards](http://book.cakephp.org/3.0/en/contributing/cakephp-coding-conventions.html) | 1 |
Javascript | Javascript | fix first start for new devs | cf61a55b92231546abdad47ffad06f9aca736c29 | <ide><path>index.js
<ide> /* eslint-disable no-process-exit */
<ide> require('babel/register');
<ide> require('dotenv').load();
<add>
<ide> var fs = require('fs'),
<add> Rx = require('rx'),
<ide> _ = require('lodash'),
<ide> path = require('path'),
<del> app = require('../server/server'),
<del> nonprofits = require('./nonprofits.json'),
<del> jobs = require('./jobs.json');
<add> app = require('../server/server');
<ide>
<ide> function getFilesFor(dir) {
<ide> return fs.readdirSync(path.join(__dirname, '/' + dir));
<ide> }
<ide>
<ide> var Challenge = app.models.Challenge;
<del>var Nonprofit = app.models.Nonprofit;
<del>var Job = app.models.Job;
<del>var counter = 0;
<ide> var challenges = getFilesFor('challenges');
<del>// plus two accounts for nonprofits and jobs seed.
<del>var numberToSave = challenges.length + 1;
<del>
<del>function completionMonitor() {
<del> // Increment counter
<del> counter++;
<del>
<del> // Exit if all challenges have been checked
<del> if (counter >= numberToSave) {
<del> process.exit(0);
<del> }
<del>
<del> // Log where in the seed order we're currently at
<del> console.log('Call: ' + counter + '/' + numberToSave);
<del>}
<add>var destroy = Rx.Observable.fromNodeCallback(Challenge.destroyAll, Challenge);
<add>var create = Rx.Observable.fromNodeCallback(Challenge.create, Challenge);
<ide>
<del>Challenge.destroyAll(function(err, info) {
<del> if (err) {
<del> throw err;
<del> } else {
<del> console.log('Deleted ', info);
<del> }
<del> challenges.forEach(function(file) {
<add>destroy()
<add> .flatMap(function() { return Rx.Observable.from(challenges); })
<add> .flatMap(function(file) {
<ide> var challengeSpec = require('./challenges/' + file);
<ide> var order = challengeSpec.order;
<ide> var block = challengeSpec.name;
<ide> var isBeta = !!challengeSpec.isBeta;
<add> console.log('parsed %s successfully', file);
<ide>
<ide> // challenge file has no challenges...
<ide> if (challengeSpec.challenges.length === 0) {
<del> console.log('file %s has no challenges', file);
<del> completionMonitor();
<del> return;
<add> return Rx.Observable.just([{ block: 'empty ' + block }]);
<ide> }
<ide>
<ide> var challenges = challengeSpec.challenges
<ide> Challenge.destroyAll(function(err, info) {
<ide> return challenge;
<ide> });
<ide>
<del> Challenge.create(
<del> challenges,
<del> function(err) {
<del> if (err) {
<del> throw err;
<del> } else {
<del> console.log('Successfully parsed %s', file);
<del> completionMonitor(err);
<del> }
<del> }
<del> );
<del> });
<del>});
<del>
<del>Nonprofit.destroyAll(function(err, info) {
<del> if (err) {
<del> console.error(err);
<del> } else {
<del> console.log('Deleted ', info);
<del> }
<del> Nonprofit.create(nonprofits, function(err, data) {
<del> if (err) {
<del> throw err;
<del> } else {
<del> console.log('Saved ', data);
<del> }
<del> completionMonitor(err);
<del> console.log('nonprofits');
<del> });
<del>});
<del>
<del>Job.destroyAll(function(err, info) {
<del> if (err) {
<del> throw err;
<del> } else {
<del> console.log('Deleted ', info);
<del> }
<del> Job.create(jobs, function(err, data) {
<del> if (err) {
<del> console.log('error: ', err);
<del> } else {
<del> console.log('Saved ', data);
<add> return create(challenges);
<add> })
<add> .subscribe(
<add> function(challenges) {
<add> console.log('%s successfully saved', challenges[0].block);
<add> },
<add> function(err) { throw err; },
<add> function() {
<add> console.log('challenge seed completed');
<add> process.exit(0);
<ide> }
<del> console.log('jobs');
<del> completionMonitor(err);
<del> });
<del>});
<add> );
<ide><path>nonprofits.js
<add>/* eslint-disable no-process-exit */
<add>require('babel/register');
<add>require('dotenv').load();
<add>
<add>var Rx = require('rx');
<add>var app = require('../server/server');
<add>
<add>var Nonprofits = app.models.Challenge;
<add>var nonprofits = require('./nonprofits.json');
<add>var destroy = Rx.Observable.fromNodeCallback(Nonprofits.destroyAll, Nonprofits);
<add>var create = Rx.Observable.fromNodeCallback(Nonprofits.create, Nonprofits);
<add>
<add>destroy()
<add> .flatMap(function() {
<add> if (!nonprofits) {
<add> return Rx.Observable.throw(new Error('No nonprofits found'));
<add> }
<add> return create(nonprofits);
<add> })
<add> .subscribe(
<add> function(nonprofits) {
<add> console.log('successfully saved %d nonprofits', nonprofits.length);
<add> },
<add> function(err) { throw err; },
<add> function() {
<add> console.log('nonprofit seed completed');
<add> process.exit(0);
<add> }
<add> ); | 2 |
Javascript | Javascript | make a null desc work for defineproperty | 76c313fc998b70328204d720a05892df81e4a423 | <ide><path>packages/ember-metal/lib/properties.js
<ide> Ember.defineProperty = function(obj, keyName, desc, val) {
<ide> } else {
<ide> if (descs[keyName]) { metaFor(obj).descs[keyName] = null; }
<ide>
<del> if (desc === undefined) {
<add> if (desc == null) {
<ide> if (existingDesc) {
<ide> objectDefineProperty(obj, keyName, {
<ide> enumerable: true, | 1 |
Javascript | Javascript | add test case for bug in webpack 4 | cb8f6ade65e1842471f7889e478d5cfaa3954516 | <ide><path>test/cases/side-effects/dynamic-reexports/dynamic-reexport-default/dynamic.js
<add>Object(exports).default = "dynamic";
<ide><path>test/cases/side-effects/dynamic-reexports/dynamic-reexport-default/index.js
<add>export * from "./dynamic";
<add>export default "static";
<ide><path>test/cases/side-effects/dynamic-reexports/index.js
<ide> import {
<ide> } from "./dedupe-target-with-side";
<ide> import { value, valueUsed } from "./dedupe-target";
<ide> import * as DefaultExport from "./default-export";
<del>import { value as valueDirect, value2 as value2Direct } from "./direct-export";
<add>import {
<add> value as valueDirect,
<add> value2 as value2Direct,
<add> default as Default1
<add>} from "./direct-export";
<ide> import {
<ide> value as valueChecked,
<ide> value2 as value2Checked
<ide> } from "./checked-export";
<add>import Default2 from "./dynamic-reexport-default";
<ide>
<ide> it("should dedupe static reexport target", () => {
<ide> expect(valueStatic).toBe(42);
<ide> it("should handle checked dynamic export when reexporting", () => {
<ide> expect(valueChecked).toBe(42);
<ide> expect(value2Checked).toBe(42);
<ide> });
<add>
<add>it("should handle default export correctly", () => {
<add> expect(Default1).toBe(undefined);
<add> expect(Default2).toBe("static");
<add>});
<ide><path>test/cases/side-effects/dynamic-reexports/warnings.js
<add>module.exports = [
<add> [
<add> /export 'default' \(imported as 'Default1'\) was not found in '\.\/direct-export'/
<add> ]
<add>]; | 4 |
Ruby | Ruby | extract habtm handling to a method | 5753a8cb2a63284aeb30d5b46e28301478cb779e | <ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def table_rows
<ide> row[fk_name] = ActiveRecord::FixtureSet.identify(value)
<ide> end
<ide> when :has_and_belongs_to_many
<del> if (targets = row.delete(association.name.to_s))
<del> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
<del> table_name = association.join_table
<del> rows[table_name].concat targets.map { |target|
<del> { association.foreign_key => row[primary_key_name],
<del> association.association_foreign_key => ActiveRecord::FixtureSet.identify(target) }
<del> }
<del> end
<add> handle_habtm(rows, row, association)
<ide> end
<ide> end
<ide> end
<ide> def primary_key_name
<ide> @primary_key_name ||= model_class && model_class.primary_key
<ide> end
<ide>
<add> def handle_habtm(rows, row, association)
<add> if (targets = row.delete(association.name.to_s))
<add> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
<add> table_name = association.join_table
<add> rows[table_name].concat targets.map { |target|
<add> { association.foreign_key => row[primary_key_name],
<add> association.association_foreign_key => ActiveRecord::FixtureSet.identify(target) }
<add> }
<add> end
<add> end
<add>
<ide> def has_primary_key_column?
<ide> @has_primary_key_column ||= primary_key_name &&
<ide> model_class.columns.any? { |c| c.name == primary_key_name } | 1 |
Python | Python | add doc link to docstring of export_tfhub | d4112a1b78dd9ae4d556d4d22d48ce1ed2188f8d | <ide><path>official/nlp/tools/export_tfhub.py
<ide> to https://tfhub.dev that implement the preprocessor and encoder APIs defined
<ide> at https://www.tensorflow.org/hub/common_saved_model_apis/text.
<ide>
<add>For a full usage guide, see
<add>https://github.com/tensorflow/models/blob/master/official/nlp/docs/tfhub.md
<add>
<ide> Minimal usage examples:
<ide>
<ide> 1) Exporting an Encoder from checkpoint and config. | 1 |
Ruby | Ruby | fix actionview and activemodel test cases typos | e21a18bed0b1246ca660c1ffe4d8be8c7fd1b213 | <ide><path>actionview/test/template/form_collections_helper_test.rb
<ide> def with_collection_check_boxes(*args, &block)
<ide> assert_select 'label[for=user_active_no]', 'No'
<ide> end
<ide>
<del> test 'colection check box should sanitize collection values for labels correctly' do
<add> test 'collection check box should sanitize collection values for labels correctly' do
<ide> with_collection_check_boxes :user, :name, ['$0.99', '$1.99'], :to_s, :to_s
<ide> assert_select 'label[for=user_name_099]', '$0.99'
<ide> assert_select 'label[for=user_name_199]', '$1.99'
<ide><path>activemodel/test/cases/serializers/json_serialization_test.rb
<ide> def @contact.as_json(options); { name: name, created_at: created_at }; end
<ide> assert_no_match %r{"preferences":}, json
<ide> end
<ide>
<del> test "custom as_json options should be extendible" do
<add> test "custom as_json options should be extensible" do
<ide> def @contact.as_json(options = {}); super(options.merge(only: [:name])); end
<ide> json = @contact.to_json
<ide> | 2 |
PHP | PHP | add method to check for mariadb | 03c04911351903a4f22b161ebf54a1e72f7ee948 | <ide><path>src/Database/Driver/Mysql.php
<ide> class Mysql extends Driver
<ide> */
<ide> protected const MAX_ALIAS_LENGTH = 256;
<ide>
<add> /**
<add> * Server type MySQL
<add> *
<add> * @var string
<add> */
<add> protected const SERVER_TYPE_MYSQL = 'mysql';
<add>
<add> /**
<add> * Server type MariaDB
<add> *
<add> * @var string
<add> */
<add> protected const SERVER_TYPE_MARIADB = 'mariadb';
<add>
<ide> /**
<ide> * Base configuration settings for MySQL driver
<ide> *
<ide> class Mysql extends Driver
<ide> *
<ide> * @var string
<ide> */
<del> protected $serverType = 'mysql';
<add> protected $serverType = self::SERVER_TYPE_MYSQL;
<ide>
<ide> /**
<ide> * Mappping of feature to db server version for feature availability checks.
<ide> public function supportsDynamicConstraints(): bool
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Returns true if the connected server is MariaDB.
<add> *
<add> * @return bool
<add> */
<add> public function isMariadb(): bool
<add> {
<add> $this->version();
<add>
<add> return $this->serverType === static::SERVER_TYPE_MARIADB;
<add> }
<add>
<ide> /**
<ide> * Returns connected server version.
<ide> *
<ide> public function version(): string
<ide> $this->_version = (string)$this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
<ide>
<ide> if (strpos($this->_version, 'MariaDB') !== false) {
<del> $this->serverType = 'mariadb';
<add> $this->serverType = static::SERVER_TYPE_MARIADB;
<ide> $parts = explode(':', $this->_version);
<ide> $this->_version = array_pop($parts);
<ide> }
<ide><path>tests/TestCase/Database/QueryTests/CommonTableExpressionQueryTests.php
<ide> public function testWithInInsertWithValuesQuery()
<ide> */
<ide> public function testWithInUpdateQuery()
<ide> {
<add> $this->skipIf(
<add> $this->connection->getDriver() instanceof Mysql && $this->connection->getDriver()->isMariadb(),
<add> 'MariaDB does not support CTEs in UPDATE query.'
<add> );
<add>
<ide> $this->loadFixtures('Articles');
<ide>
<ide> // test initial state
<ide> public function testWithInUpdateQuery()
<ide> */
<ide> public function testWithInDeleteQuery()
<ide> {
<add> $this->skipIf(
<add> $this->connection->getDriver() instanceof Mysql && $this->connection->getDriver()->isMariadb(),
<add> 'MariaDB does not support CTEs in DELETE query.'
<add> );
<add>
<ide> $this->loadFixtures('Articles');
<ide>
<ide> // test initial state
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testDescribeTable()
<ide> 'comment' => null,
<ide> ],
<ide> ];
<add>
<add> if (ConnectionManager::get('test')->getDriver()->isMariadb()) {
<add> $expected['created_with_precision']['default'] = 'current_timestamp(3)';
<add> $expected['created_with_precision']['comment'] = '';
<add> }
<add>
<ide> $this->assertEquals(['id'], $result->getPrimaryKey());
<ide> foreach ($expected as $field => $definition) {
<ide> $this->assertEquals(
<ide> public function testDescribeTableIndexes()
<ide> 'delete' => 'restrict',
<ide> ],
<ide> ];
<add>
<ide> $this->assertEquals($expected['primary'], $result->getConstraint('primary'));
<ide> $this->assertEquals($expected['length_idx'], $result->getConstraint('length_idx'));
<del> $this->assertEquals($expected['schema_articles_ibfk_1'], $result->getConstraint('schema_articles_ibfk_1'));
<add> if (ConnectionManager::get('test')->getDriver()->isMariadb()) {
<add> $this->assertEquals($expected['schema_articles_ibfk_1'], $result->getConstraint('author_idx'));
<add> } else {
<add> $this->assertEquals($expected['schema_articles_ibfk_1'], $result->getConstraint('schema_articles_ibfk_1'));
<add> }
<ide>
<ide> $this->assertCount(1, $result->indexes());
<ide> $expected = [
<ide> public function testDescribeJson()
<ide> $connection = ConnectionManager::get('test');
<ide> $this->_createTables($connection);
<ide> $this->skipIf(!$connection->getDriver()->supportsNativeJson(), 'Does not support native json');
<add> $this->skipIf($connection->getDriver()->isMariadb(), 'MariaDb internally uses TEXT for JSON columns');
<ide>
<ide> $schema = new SchemaCollection($connection);
<ide> $result = $schema->describe('schema_json'); | 3 |
Ruby | Ruby | add attribute_names method on errors | 89eb5540258d217b780dee384c47445a2c1e8a46 | <ide><path>activemodel/lib/active_model/errors.rb
<ide> def keys
<ide> keys.freeze
<ide> end
<ide>
<add> # Returns all error attribute names
<add> #
<add> # person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
<add> # person.errors.attribute_names # => [:name]
<add> def attribute_names
<add> @errors.map(&:attribute).uniq.freeze
<add> end
<add>
<ide> # Returns an xml formatted representation of the Errors hash.
<ide> #
<ide> # person.errors.add(:name, :blank, message: "can't be blank")
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def test_no_key
<ide> end
<ide> end
<ide>
<add> test "attribute_names returns the error attributes" do
<add> errors = ActiveModel::Errors.new(Person.new)
<add> errors.add(:foo, "omg")
<add> errors.add(:baz, "zomg")
<add>
<add> assert_equal [:foo, :baz], errors.attribute_names
<add> end
<add>
<add> test "attribute_names only returns unique attribute names" do
<add> errors = ActiveModel::Errors.new(Person.new)
<add> errors.add(:foo, "omg")
<add> errors.add(:foo, "zomg")
<add>
<add> assert_equal [:foo], errors.attribute_names
<add> end
<add>
<add> test "attribute_names returns an empty array after try to get a message only" do
<add> errors = ActiveModel::Errors.new(Person.new)
<add> errors.messages[:foo]
<add> errors.messages[:baz]
<add>
<add> assert_equal [], errors.attribute_names
<add> end
<add>
<ide> test "detecting whether there are errors with empty?, blank?, include?" do
<ide> person = Person.new
<ide> person.errors[:foo] | 2 |
Python | Python | prepare 2.1.4 release | 5d54eeb3967f3364955478c9520ed9ba05c4f9f2 | <ide><path>keras/__init__.py
<ide> from .models import Model
<ide> from .models import Sequential
<ide>
<del>__version__ = '2.1.3'
<add>__version__ = '2.1.4'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='2.1.3',
<add> version='2.1.4',
<ide> description='Deep Learning for humans',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/keras-team/keras',
<del> download_url='https://github.com/keras-team/keras/tarball/2.1.3',
<add> download_url='https://github.com/keras-team/keras/tarball/2.1.4',
<ide> license='MIT',
<ide> install_requires=['numpy>=1.9.1',
<ide> 'scipy>=0.14', | 2 |
Text | Text | fix some sentences | 70cfa581ab950e9dc661e75de3e89f1cda9b0797 | <ide><path>curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.portuguese.md
<ide> localeTitle: Passar Argumentos para Evitar Dependência Externa em uma Função
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> O último desafio foi um passo mais próximo dos princípios de programação funcional, mas ainda falta algo. Nós não alteramos o valor da variável global, mas o <code>incrementer</code> função não funcionaria sem a variável global <code>fixedValue</code> estar lá. Outro princípio da programação funcional é sempre declarar suas dependências explicitamente. Isso significa que, se uma função depende de uma variável ou objeto estar presente, passe essa variável ou objeto diretamente para a função como um argumento. Existem várias boas conseqüências desse princípio. A função é mais fácil de testar, você sabe exatamente qual entrada é necessária e não depende de mais nada em seu programa. Isso pode lhe dar mais confiança quando você altera, remove ou adiciona um novo código. Você saberia o que você pode ou não pode mudar e você pode ver onde estão as possíveis armadilhas. Finalmente, a função sempre produziria a mesma saída para o mesmo conjunto de entradas, independentemente da parte do código que a executa. </section>
<add><section id="description"> O último desafio foi um passo mais próximo dos princípios de programação funcional, mas ainda falta algo. Nós não alteramos o valor da variável global, mas a função <code>incrementer</code> não funcionaria sem a variável global <code>fixedValue</code> estar lá. Outro princípio da programação funcional é sempre declarar suas dependências explicitamente. Isso significa que, se uma função depende de uma variável ou objeto estar presente, passe essa variável ou o objeto diretamente para a função como um argumento. Existem várias boas conseqüências desse princípio. A função é mais fácil de testar, você sabe exatamente qual entrada é necessária e não depende de mais nada em seu programa. Isso pode lhe dar mais confiança quando você altera, remove ou adiciona um novo código. Você saberia o que você pode ou não pode mudar e você pode ver onde estão as possíveis armadilhas. Finalmente, a função sempre produziria a mesma saída para o mesmo conjunto de entradas, independentemente da parte do código que a executa. </section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> Vamos atualizar a função <code>incrementer</code> para declarar claramente suas dependências. Escreva a função <code>incrementer</code> modo que receba um argumento e, em seguida, aumente o valor em um. </section>
<add><section id="instructions"> Vamos atualizar a função <code>incrementer</code> para declarar claramente suas dependências. Escreva a função <code>incrementer</code> de modo que ela receba um argumento e, em seguida, aumente o valor em um. </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: Seu <code>incrementer</code> função não deve alterar o valor de <code>fixedValue</code> .
<add> - text: Sua <code>incrementer</code> função não deve alterar o valor de <code>fixedValue</code> .
<ide> testString: 'assert(fixedValue === 4, "Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.");'
<ide> - text: Sua função <code>incrementer</code> deve ter um parâmetro.
<ide> testString: 'assert(code.match(/function\s+?incrementer\s*?\(.+?\)/g), "Your <code>incrementer</code> function should take a parameter.");'
<del> - text: Sua função de <code>incrementer</code> deve retornar um valor que é maior que o valor <code>fixedValue</code> .
<add> - text: Sua função <code>incrementer</code> deve retornar um valor que é maior que o valor <code>fixedValue</code> .
<ide> testString: 'assert(newValue === 5, "Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.");'
<ide>
<ide> ``` | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.