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 |
|---|---|---|---|---|---|
Javascript | Javascript | remove server error listener so that it throws | 45ed000d4b29c4c621b95e6c75d6ac76a4cd9ddb | <ide><path>packager/react-packager/src/SocketInterface/SocketServer.js
<ide> class SocketServer {
<ide> this._server = net.createServer();
<ide> this._server.listen(sockPath);
<ide> this._ready = new Promise((resolve, reject) => {
<del> this._server.on('error', (e) => reject(e));
<del> this._server.on('listening', () => {
<add> this._server.once('error', (e) => reject(e));
<add> this._server.once('listening', () => {
<add> // Remove error listener so we make sure errors propagate.
<add> this._server.removeAllListeners('error');
<add> this._server.on(
<add> 'close',
<add> () => debug('server closed')
<add> );
<add>
<ide> debug(
<ide> 'Process %d listening on socket path %s ' +
<ide> 'for server with options %j',
<ide> class SocketServer {
<ide> });
<ide>
<ide> process.on('uncaughtException', (error) => {
<del> debug('uncaught error', error);
<add> debug('uncaught error', error.stack);
<ide> setImmediate(() => process.exit(1));
<ide> });
<ide> | 1 |
Python | Python | fix python2 tests | 6dacc79d395bd41e0ef76c2a043c2ef90cc79925 | <ide><path>pytorch_transformers/tests/tokenization_tests_commons.py
<ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<del>from __future__ import absolute_import
<del>from __future__ import division
<del>from __future__ import print_function
<add>from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<ide> import os
<ide> import sys
<ide> def create_and_check_save_and_load_tokenizer(tester, tokenizer_class, *inputs, *
<ide> def create_and_check_pickle_tokenizer(tester, tokenizer_class, *inputs, **kwargs):
<ide> tokenizer = tokenizer_class(*inputs, **kwargs)
<ide>
<del> text = "Munich and Berlin are nice cities"
<add> text = u"Munich and Berlin are nice cities"
<ide> filename = u"/tmp/tokenizer.bin"
<ide>
<ide> subwords = tokenizer.tokenize(text)
<ide><path>pytorch_transformers/tokenization_utils.py
<ide> def _from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs
<ide> max_len = cls.max_model_input_sizes[pretrained_model_name_or_path]
<ide> kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)
<ide>
<add> # Merge resolved_vocab_files arguments in kwargs.
<add> for args_name, file_path in resolved_vocab_files.items():
<add> kwargs[args_name] = file_path
<add>
<ide> # Instantiate tokenizer.
<del> tokenizer = cls(*inputs, **resolved_vocab_files, **kwargs)
<add> tokenizer = cls(*inputs, **kwargs)
<ide>
<ide> return tokenizer
<ide> | 2 |
Python | Python | relocate a stray parenthesis | c0e3b273c2e358f260e688e08e146e428314e0d4 | <ide><path>research/astronet/third_party/kepler_spline/kepler_spline.py
<ide> def choose_kepler_spline(all_time,
<ide> # Don't fit a spline on less than 4 points.
<ide> if len(time) < 4:
<ide> spline.append(flux)
<del> spline_mask.append(np.ones_like(flux), dtype=np.bool)
<add> spline_mask.append(np.ones_like(flux, dtype=np.bool))
<ide> continue
<ide>
<ide> # Fit B-spline to this light-curve segment. | 1 |
Text | Text | add a consideration note and a wip note | fe661915157ccdb9dc5db752edbb511dc9ddc193 | <ide><path>guides/source/action_view_overview.md
<ide> TODO...
<ide> Overview of all the helpers provided by Action View
<ide> ---------------------------------------------------
<ide>
<add>WIP: Not all the helpers are listed here. For a full list see the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html)
<add>
<add>TODO: I'm skeptical about whether it makes sense documenting all the helpers in an Action View Overview, or even some of them. *Agis-*
<add>
<ide> The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
<ide>
<ide> ### RecordTagHelper | 1 |
Ruby | Ruby | start output with the name/email | 5ecdf10e27f872d445be9947147071f13b280881 | <ide><path>Library/Homebrew/dev-cmd/contributions.rb
<ide> def contributions
<ide> coauthorships += git_log_coauthor_cmd(T.must(repo_path), args)
<ide> end
<ide>
<del> sentence = "Person #{args.named.first} directly authored #{commits} commits " \
<add> sentence = "#{args.named.first} directly authored #{commits} commits " \
<ide> "and co-authored #{coauthorships} commits " \
<ide> "across #{all_repos ? "all Homebrew repos" : repos.to_sentence}"
<ide> sentence += if args.from && args.to | 1 |
Javascript | Javascript | replace a tab with a space | 169e97e97226653691446334cddf374065ba3537 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> } else {
<add> } else {
<ide>
<ide> if ( shaderParam && shaderParam.value ) {
<ide> | 1 |
Ruby | Ruby | convert emoji test to spec | 6799081f8a156fbb07246cab936717fc00826857 | <ide><path>Library/Homebrew/test/emoji_spec.rb
<add>require "emoji"
<add>
<add>describe Emoji do
<add> describe "#install_badge" do
<add> subject { described_class.install_badge }
<add>
<add> it "returns 🍺 by default" do
<add> expect(subject).to eq "🍺"
<add> end
<add>
<add> it "returns the contents of HOMEBREW_INSTALL_BADGE if set" do
<add> ENV["HOMEBREW_INSTALL_BADGE"] = "foo"
<add> expect(subject).to eq "foo"
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/emoji_test.rb
<del>require "testing_env"
<del>require "emoji"
<del>
<del>class EmojiTest < Homebrew::TestCase
<del> def test_install_badge
<del> assert_equal "🍺", Emoji.install_badge
<del>
<del> ENV["HOMEBREW_INSTALL_BADGE"] = "foo"
<del> assert_equal "foo", Emoji.install_badge
<del> end
<del>end | 2 |
Go | Go | fix race between copyto and set | d0f3f77432f8fbbcd25b58015b925c66cd9e50f5 | <ide><path>libnetwork/bitseq/sequence.go
<ide> func (h *Handle) set(ordinal, start, end uint64, any bool, release bool) (uint64
<ide> )
<ide>
<ide> for {
<del> if h.store != nil {
<del> if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
<add> var store datastore.DataStore
<add> h.Lock()
<add> store = h.store
<add> h.Unlock()
<add> if store != nil {
<add> if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
<ide> return ret, err
<ide> }
<ide> } | 1 |
Text | Text | remove unneeded assert text | 84edc070761b0556c9eacca196f832be5791bf4b | <ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/cumulative-standard-deviation.english.md
<ide> forumTopicId: 302240
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Write a function that takes an array of numbers as parameter and returns the <a href="https://en.wikipedia.org/wiki/Standard Deviation">standard deviation</a> of the series.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>standardDeviation</code> should be a function.
<del> testString: assert(typeof standardDeviation == 'function', '<code>standardDeviation</code> should be a function.');
<add> testString: assert(typeof standardDeviation == 'function');
<ide> - text: <code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return a number.
<del> testString: assert(typeof standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) == 'number', '<code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return a number.');
<add> testString: assert(typeof standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) == 'number');
<ide> - text: <code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return <code>2</code>.
<del> testString: assert.equal(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]), 2, '<code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return <code>2</code>.');
<add> testString: assert.equal(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
<ide> - text: <code>standardDeviation([600, 470, 170, 430, 300])</code> should return <code>147.323</code>.
<del> testString: assert.equal(standardDeviation([600, 470, 170, 430, 300]), 147.323, '<code>standardDeviation([600, 470, 170, 430, 300])</code> should return <code>147.323</code>.');
<add> testString: assert.equal(standardDeviation([600, 470, 170, 430, 300]), 147.323);
<ide> - text: <code>standardDeviation([75, 83, 96, 100, 121, 125])</code> should return <code>18.239</code>.
<del> testString: assert.equal(standardDeviation([75, 83, 96, 100, 121, 125]), 18.239, '<code>standardDeviation([75, 83, 96, 100, 121, 125])</code> should return <code>18.239</code>.');
<add> testString: assert.equal(standardDeviation([75, 83, 96, 100, 121, 125]), 18.239);
<ide> - text: <code>standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82])</code> should return <code>16.87</code>.
<del> testString: assert.equal(standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82]), 16.87, '<code>standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82])</code> should return <code>16.87</code>.');
<add> testString: assert.equal(standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82]), 16.87);
<ide> - text: <code>standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314])</code> should return <code>22.631</code>.
<del> testString: assert.equal(standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314]), 22.631, '<code>standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314])</code> should return <code>22.631</code>.');
<add> testString: assert.equal(standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314]), 22.631);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function standardDeviation(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function standardDeviation(arr) {
<ide> arr.forEach(function(e) {
<ide> sum += e;
<ide> sum_sq += e * e;
<del> })
<add> });
<ide>
<del> var std_dev=Math.sqrt((sum_sq / n) - Math.pow(sum / n, 2))
<del> return Math.round(std_dev*1000)/1000;
<add> var std_dev = Math.sqrt(sum_sq / n - Math.pow(sum / n, 2));
<add> return Math.round(std_dev * 1000) / 1000;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/cusip.english.md
<ide> forumTopicId: 302241
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> A <b>CUSIP</b> is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes a string as a parameter and checks if the string is valid CUSIP.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>isCusip</code> should be a function.
<del> testString: assert(typeof isCusip == 'function', '<code>isCusip</code> should be a function.');
<add> testString: assert(typeof isCusip == 'function');
<ide> - text: <code>isCusip("037833100")</code> should return a boolean.
<del> testString: assert(typeof isCusip("037833100") == 'boolean', '<code>isCusip("037833100")</code> should return a boolean.');
<add> testString: assert(typeof isCusip("037833100") == 'boolean');
<ide> - text: <code>isCusip("037833100")</code> should return <code>true</code>.
<del> testString: assert.equal(isCusip("037833100"), true, '<code>isCusip("037833100")</code> should return <code>true</code>.');
<add> testString: assert.equal(isCusip("037833100"), true);
<ide> - text: <code>isCusip("17275R102")</code> should return <code>true</code>.
<del> testString: assert.equal(isCusip("17275R102"), true, '<code>isCusip("17275R102")</code> should return <code>true</code>.');
<add> testString: assert.equal(isCusip("17275R102"), true);
<ide> - text: <code>isCusip("38259P50a")</code> should return <code>false</code>.
<del> testString: assert.equal(isCusip("38259P50a"), false, '<code>isCusip("38259P50a")</code> should return <code>false</code>.');
<add> testString: assert.equal(isCusip("38259P50a"), false);
<ide> - text: <code>isCusip("38259P508")</code> should return <code>true</code>.
<del> testString: assert.equal(isCusip("38259P508"), true, '<code>isCusip("38259P508")</code> should return <code>true</code>.');
<add> testString: assert.equal(isCusip("38259P508"), true);
<ide> - text: <code>isCusip("38259P50#")</code> should return <code>false</code>.
<del> testString: assert.equal(isCusip("38259P50#"), false, '<code>isCusip("38259P50#")</code> should return <code>false</code>.');
<add> testString: assert.equal(isCusip("38259P50#"), false);
<ide> - text: <code>isCusip("68389X105")</code> should return <code>true</code>.
<del> testString: assert.equal(isCusip("68389X105"), true, '<code>isCusip("68389X105")</code> should return <code>true</code>.');
<add> testString: assert.equal(isCusip("68389X105"), true);
<ide> - text: <code>isCusip("68389X106")</code> should return <code>false</code>.
<del> testString: assert.equal(isCusip("68389X106"), false, '<code>isCusip("68389X106")</code> should return <code>false</code>.');
<add> testString: assert.equal(isCusip("68389X106"), false);
<ide> - text: <code>isCusip("5949181")</code> should return <code>false</code>.
<del> testString: assert.equal(isCusip("5949181"), false, '<code>isCusip("5949181")</code> should return <code>false</code>.');
<add> testString: assert.equal(isCusip("5949181"), false);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function isCusip(s) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function isCusip(s) {
<ide> return false;
<ide> }
<ide> if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing
<del> sum += Math.floor(v / 10) + v % 10;
<add> sum += Math.floor(v / 10) + (v % 10);
<ide> }
<ide> return s.charCodeAt(8) - 48 == (10 - (sum % 10)) % 10;
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/cut-a-rectangle.english.md
<ide> forumTopicId: 302242
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> A given rectangle is made from <i>m</i> × <i>n</i> squares. If <i>m</i> and <i>n</i> are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
<add>
<ide> <div style="width: 100%; text-align: center;">
<ide> <svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" width="520" height="170" aria-hidden="true" alt="Diagram showing the possible paths for 2 by 2 and 4 by 3 rectangles">
<ide> <style>
<ide> A given rectangle is made from <i>m</i> × <i>n</i> squares. If <i>m</i> and <i>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that calculates the number of different ways to cut an <i>m</i> × <i>n</i> rectangle.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>cutRectangle</code> should be a function.
<del> testString: assert(typeof cutRectangle == 'function', '<code>cutRectangle</code> should be a function.');
<add> testString: assert(typeof cutRectangle == 'function');
<ide> - text: <code>cutRectangle(2, 2)</code> should return a number.
<del> testString: assert(typeof cutRectangle(2, 2) == 'number', '<code>cutRectangle(2, 2)</code> should return a number.');
<add> testString: assert(typeof cutRectangle(2, 2) == 'number');
<ide> - text: <code>cutRectangle(2, 2)</code> should return <code>2</code>.
<del> testString: assert.equal(cutRectangle(2, 2), 2, '<code>cutRectangle(2, 2)</code> should return <code>2</code>.');
<add> testString: assert.equal(cutRectangle(2, 2), 2);
<ide> - text: <code>cutRectangle(4, 3)</code> should return <code>9</code>.
<del> testString: assert.equal(cutRectangle(4, 3), 9, '<code>cutRectangle(4, 3)</code> should return <code>9</code>.');
<add> testString: assert.equal(cutRectangle(4, 3), 9);
<ide> - text: <code>cutRectangle(4, 4)</code> should return <code>22</code>.
<del> testString: assert.equal(cutRectangle(4, 4), 22, '<code>cutRectangle(4, 4)</code> should return <code>22</code>.');
<add> testString: assert.equal(cutRectangle(4, 4), 22);
<ide> - text: <code>cutRectangle(8, 3)</code> should return <code>53</code>.
<del> testString: assert.equal(cutRectangle(8, 3), 53, '<code>cutRectangle(8, 3)</code> should return <code>53</code>.');
<add> testString: assert.equal(cutRectangle(8, 3), 53);
<ide> - text: <code>cutRectangle(7, 4)</code> should return <code>151</code>.
<del> testString: assert.equal(cutRectangle(7, 4), 151, '<code>cutRectangle(7, 4)</code> should return <code>151</code>.');
<add> testString: assert.equal(cutRectangle(7, 4), 151);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function cutRectangle(w, h) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function cutRectangle(w, h) {
<del> if (w % 2 == 1 && h % 2 == 1)
<del> return;
<add> if (w % 2 == 1 && h % 2 == 1) return;
<ide>
<ide> var dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]];
<ide>
<del> var grid = new Array(h); for (var i = 0; i < grid.length; i++) grid[i]=new Array(w);
<add> var grid = new Array(h);
<add> for (var i = 0; i < grid.length; i++) grid[i] = new Array(w);
<ide> var stack = [];
<ide>
<ide> var half = Math.floor((w * h) / 2);
<ide> var bits = Math.pow(2, half) - 1;
<del> var result=0;
<add> var result = 0;
<ide> for (; bits > 0; bits -= 2) {
<del>
<ide> for (var i = 0; i < half; i++) {
<ide> var r = Math.floor(i / w);
<ide> var c = i % w;
<ide> function cutRectangle(w, h) {
<ide> stack.push(0);
<ide> grid[0][0] = 2;
<ide> var count = 1;
<del> while (stack.length!=0) {
<del>
<add> while (stack.length != 0) {
<ide> var pos = stack.pop();
<ide> var r = Math.floor(pos / w);
<ide> var c = pos % w;
<ide> function cutRectangle(w, h) {
<ide> var nextC = c + dir[1];
<ide>
<ide> if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
<del>
<ide> if (grid[nextR][nextC] == 1) {
<ide> stack.push(nextR * w + nextC);
<ide> grid[nextR][nextC] = 2;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/dot-product.english.md
<ide> forumTopicId: 302251
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Create a function, to compute the <b><a href="https://en.wikipedia.org/wiki/Dot product">dot product</a></b>, also known as the <b>scalar product</b> of two vectors.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>dotProduct</code> should be a function.
<del> testString: assert(typeof dotProduct == 'function', '<code>dotProduct</code> should be a function.');
<add> testString: assert(typeof dotProduct == 'function');
<ide> - text: <code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return a number.
<del> testString: assert(typeof dotProduct([1, 3, -5], [4, -2, -1]) == 'number', '<code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return a number.');
<add> testString: assert(typeof dotProduct([1, 3, -5], [4, -2, -1]) == 'number');
<ide> - text: <code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return <code>3</code>.
<del> testString: assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3, '<code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return <code>3</code>.');
<add> testString: assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
<ide> - text: <code>dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])</code> should return <code>130</code>.
<del> testString: assert.equal(dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]), 130, '<code>dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])</code> should return <code>130</code>.');
<add> testString: assert.equal(dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]), 130);
<ide> - text: <code>dotProduct([5, 4, 3, 2], [7, 8, 9, 6])</code> should return <code>106</code>.
<del> testString: assert.equal(dotProduct([5, 4, 3, 2], [7, 8, 9, 6]), 106, '<code>dotProduct([5, 4, 3, 2], [7, 8, 9, 6])</code> should return <code>106</code>.');
<add> testString: assert.equal(dotProduct([5, 4, 3, 2], [7, 8, 9, 6]), 106);
<ide> - text: <code>dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])</code> should return <code>-36</code>.
<del> testString: assert.equal(dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6]), -36, '<code>dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])</code> should return <code>-36</code>.');
<add> testString: assert.equal(dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6]), -36);
<ide> - text: <code>dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])</code> should return <code>10392</code>.
<del> testString: assert.equal(dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110]), 10392, '<code>dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])</code> should return <code>10392</code>.');
<add> testString: assert.equal(dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110]), 10392);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function dotProduct(ary1, ary2) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function dotProduct(ary1, ary2) {
<del> var dotprod = 0;
<del> for (var i = 0; i < ary1.length; i++)
<del> dotprod += ary1[i] * ary2[i];
<del> return dotprod;
<add> var dotprod = 0;
<add> for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i];
<add> return dotprod;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/k-d-tree.english.md
<ide> forumTopicId: 302295
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> A k-d tree (short for <i>k</i>-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space.
<ide> k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches).
<ide> k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is <i>k</i>, the number of points in the data, <i>N</i>, should be <i>N</i> ≫ 2<sup><i>k</i></sup>.
<ide> Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Write a function to perform a nearest neighbour search using k-d tree. The function takes two parameters: an array of k-dimensional points, and a single k-dimensional point whose nearest neighbour should be returned by the function. A k-dimensional point will be given as an array of k elements.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>kdNN</code> should be a function.
<del> testString: assert(typeof kdNN == 'function', '<code>kdNN</code> should be a function.');
<add> testString: assert(typeof kdNN == 'function');
<ide> - text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return an array.
<del> testString: assert(Array.isArray(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])), '<code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return an array.');
<add> testString: assert(Array.isArray(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])));
<ide> - text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return <code>[ 8, 1 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2]), [8, 1], '<code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return <code>[ 8, 1 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2]), [8, 1]);
<ide> - text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])</code> should return <code>[ 8, 1 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1]), [8, 1], '<code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])</code> should return <code>[ 8, 1 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1]), [8, 1]);
<ide> - text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])</code> should return <code>[ 2, 3 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2]), [2, 3], '<code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])</code> should return <code>[ 2, 3 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2]), [2, 3]);
<ide> - text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])</code> should return <code>[ 1, 2, 5 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3]), [1, 2, 5], '<code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])</code> should return <code>[ 1, 2, 5 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3]), [1, 2, 5]);
<ide> - text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])</code> should return <code>[ 4, 6, 7 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6]), [4, 6, 7], '<code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])</code> should return <code>[ 4, 6, 7 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6]), [4, 6, 7]);
<ide> - text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])</code> should return <code>[ 7, 8, 9 ]</code>.
<del> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8]), [7, 8, 9], '<code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])</code> should return <code>[ 7, 8, 9 ]</code>.');
<add> testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8]), [7, 8, 9]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function kdNN(fpoints, fpoint) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide>
<ide> function kdTree(points, metric, dimensions) {
<del>
<ide> var self = this;
<ide>
<ide> function buildTree(points, depth, parent) {
<ide> function kdNN(fpoints, fpoint) {
<ide> return new Node(points[0], dim, parent);
<ide> }
<ide>
<del> points.sort(function (a, b) {
<add> points.sort(function(a, b) {
<ide> return a[dimensions[dim]] - b[dimensions[dim]];
<ide> });
<ide>
<ide> function kdNN(fpoints, fpoint) {
<ide>
<ide> this.root = buildTree(points, 0, null);
<ide>
<del> this.insert = function (point) {
<add> this.insert = function(point) {
<ide> function innerSearch(node, parent) {
<del>
<ide> if (node === null) {
<ide> return parent;
<ide> }
<ide> function kdNN(fpoints, fpoint) {
<ide> return;
<ide> }
<ide>
<del> newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);
<add> newNode = new Node(
<add> point,
<add> (insertPosition.dimension + 1) % dimensions.length,
<add> insertPosition
<add> );
<ide> dimension = dimensions[insertPosition.dimension];
<ide>
<ide> if (point[dimension] < insertPosition.obj[dimension]) {
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide> };
<ide>
<del> this.nearest = function (point, maxNodes, maxDistance) {
<del> var i,
<del> result,
<del> bestNodes;
<add> this.nearest = function(point, maxNodes, maxDistance) {
<add> var i, result, bestNodes;
<ide>
<del> bestNodes = new BinaryHeap(
<del> function (e) { return -e[1]; }
<del> );
<add> bestNodes = new BinaryHeap(function(e) {
<add> return -e[1];
<add> });
<ide>
<ide> function nearestSearch(node) {
<ide> var bestChild,
<ide> function kdNN(fpoints, fpoint) {
<ide> linearDistance = metric(linearPoint, node.obj);
<ide>
<ide> if (node.right === null && node.left === null) {
<del> if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
<add> if (
<add> bestNodes.size() < maxNodes ||
<add> ownDistance < bestNodes.peek()[1]
<add> ) {
<ide> saveNode(node, ownDistance);
<ide> }
<ide> return;
<ide> function kdNN(fpoints, fpoint) {
<ide> saveNode(node, ownDistance);
<ide> }
<ide>
<del> if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {
<add> if (
<add> bestNodes.size() < maxNodes ||
<add> Math.abs(linearDistance) < bestNodes.peek()[1]
<add> ) {
<ide> if (bestChild === node.left) {
<ide> otherChild = node.right;
<ide> } else {
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide> }
<ide>
<del> if (self.root)
<del> nearestSearch(self.root);
<add> if (self.root) nearestSearch(self.root);
<ide>
<ide> result = [];
<ide>
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide>
<ide> BinaryHeap.prototype = {
<del> push: function (element) {
<add> push: function(element) {
<ide> // Add the new element to the end of the array.
<ide> this.content.push(element);
<ide> // Allow it to bubble up.
<ide> this.bubbleUp(this.content.length - 1);
<ide> },
<ide>
<del> pop: function () {
<add> pop: function() {
<ide> // Store the first element so we can return it later.
<ide> var result = this.content[0];
<ide> // Get the element at the end of the array.
<ide> function kdNN(fpoints, fpoint) {
<ide> return result;
<ide> },
<ide>
<del> peek: function () {
<add> peek: function() {
<ide> return this.content[0];
<ide> },
<ide>
<del> size: function () {
<add> size: function() {
<ide> return this.content.length;
<ide> },
<ide>
<del> bubbleUp: function (n) {
<add> bubbleUp: function(n) {
<ide> // Fetch the element that has to be moved.
<ide> var element = this.content[n];
<ide> // When at 0, an element can not go up any further.
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide> },
<ide>
<del> sinkDown: function (n) {
<add> sinkDown: function(n) {
<ide> // Look up the target element and its score.
<ide> var length = this.content.length,
<ide> element = this.content[n],
<ide> elemScore = this.scoreFunction(element);
<ide>
<ide> while (true) {
<ide> // Compute the indices of the child elements.
<del> var child2N = (n + 1) * 2, child1N = child2N - 1;
<add> var child2N = (n + 1) * 2,
<add> child1N = child2N - 1;
<ide> // This is used to store the new position of the element,
<ide> // if any.
<ide> var swap = null;
<ide> function kdNN(fpoints, fpoint) {
<ide> var child1 = this.content[child1N],
<ide> child1Score = this.scoreFunction(child1);
<ide> // If the score is less than our element's, we need to swap.
<del> if (child1Score < elemScore)
<del> swap = child1N;
<add> if (child1Score < elemScore) swap = child1N;
<ide> }
<ide> // Do the same checks for the other child.
<ide> if (child2N < length) {
<ide> function kdNN(fpoints, fpoint) {
<ide> }
<ide> };
<ide>
<del> var dims = []
<add> var dims = [];
<ide>
<del> for (var i = 0; i < fpoint.length; i++) dims.push(i)
<add> for (var i = 0; i < fpoint.length; i++) dims.push(i);
<ide>
<del> var tree = new kdTree(fpoints, function (e1, e2) {
<del> var d = 0;
<del> var e3 = e1;
<del> if (!Array.isArray(e1)) {
<del> e3 = []
<del> for (var key in e1)
<del> e3.push(e1[key])
<add> var tree = new kdTree(
<add> fpoints,
<add> function(e1, e2) {
<add> var d = 0;
<add> var e3 = e1;
<add> if (!Array.isArray(e1)) {
<add> e3 = [];
<add> for (var key in e1) e3.push(e1[key]);
<ide>
<del> e1 = e3
<del> }
<del> e1.forEach(function (e, i) {
<del> var sqd = (e1[i] - e2[i]);
<del> d += sqd * sqd;
<del> })
<del> return d;
<del> }, dims)
<add> e1 = e3;
<add> }
<add> e1.forEach(function(e, i) {
<add> var sqd = e1[i] - e2[i];
<add> d += sqd * sqd;
<add> });
<add> return d;
<add> },
<add> dims
<add> );
<ide>
<ide> return tree.nearest(fpoint, 1, 1000)[0][0];
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/kaprekar-numbers.english.md
<ide> forumTopicId: 302296
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> A positive integer is a <a href="https://en.wikipedia.org/wiki/Kaprekar number">Kaprekar number</a> if:
<ide> <ul>
<ide> Kaprekar numbers:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes a number $n$, a base $bs$, and returns true if the number is a Kaprekar number for the given base. Otherwise, the function returns false.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>isKaprekar</code> should be a function.
<del> testString: assert(typeof isKaprekar == 'function', '<code>isKaprekar</code> should be a function.');
<add> testString: assert(typeof isKaprekar == 'function');
<ide> - text: <code>isKaprekar(1, 10)</code> should return a boolean.
<del> testString: assert(typeof isKaprekar(1, 10) == 'boolean', '<code>isKaprekar(1, 10)</code> should return a boolean.');
<add> testString: assert(typeof isKaprekar(1, 10) == 'boolean');
<ide> - text: <code>isKaprekar(1, 10)</code> should return <code>true</code>.
<del> testString: assert.equal(isKaprekar(1, 10), true, '<code>isKaprekar(1, 10)</code> should return <code>true</code>.');
<add> testString: assert.equal(isKaprekar(1, 10), true);
<ide> - text: <code>isKaprekar(9, 10)</code> should return <code>true</code>.
<del> testString: assert.equal(isKaprekar(9, 10), true, '<code>isKaprekar(9, 10)</code> should return <code>true</code>.');
<add> testString: assert.equal(isKaprekar(9, 10), true);
<ide> - text: <code>isKaprekar(2223, 10)</code> should return <code>true</code>.
<del> testString: assert.equal(isKaprekar(2223, 10), true, '<code>isKaprekar(2223, 10)</code> should return <code>true</code>.');
<add> testString: assert.equal(isKaprekar(2223, 10), true);
<ide> - text: <code>isKaprekar(22823, 10)</code> should return <code>false</code>.
<del> testString: assert.equal(isKaprekar(22823, 10), false, '<code>isKaprekar(22823, 10)</code> should return <code>false</code>.');
<add> testString: assert.equal(isKaprekar(22823, 10), false);
<ide> - text: <code>isKaprekar(9, 17)</code> should return <code>false</code>.
<del> testString: assert.equal(isKaprekar(9, 17), false, '<code>isKaprekar(9, 17)</code> should return <code>false</code>.');
<add> testString: assert.equal(isKaprekar(9, 17), false);
<ide> - text: <code>isKaprekar(225, 17)</code> should return <code>true</code>.
<del> testString: assert.equal(isKaprekar(225, 17), true, '<code>isKaprekar(225, 17)</code> should return <code>true</code>.');
<add> testString: assert.equal(isKaprekar(225, 17), true);
<ide> - text: <code>isKaprekar(999, 17)</code> should return <code>false</code>.
<del> testString: assert.equal(isKaprekar(999, 17), false, '<code>isKaprekar(999, 17)</code> should return <code>false</code>.');
<add> testString: assert.equal(isKaprekar(999, 17), false);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function isKaprekar(n, bs) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function isKaprekar(n, bs) {
<ide> if (n < 1) return false;
<ide> if (n == 1) return true;
<ide> for (var a = n * n, b = 0, s = 1; a; s *= bs) {
<del> b += a % bs * s;
<add> b += (a % bs) * s;
<ide> a = Math.floor(a / bs);
<ide> if (b && a + b == n) return true;
<del> } return false;
<del>}
<add> }
<add> return false;
<add>}
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/knapsack-problem-0-1.english.md
<ide> forumTopicId: 323649
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> The 0-1 knapsack problem is defined as follows:
<ide> You are given an array of objects representing items to be put in a knapsack. The objects have 3 attributes: name, weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100)</code> should return <code>405</code>.
<del> testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100), 405, "<code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100)</code> should return <code>405</code>.");
<add> testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100), 405);
<ide> - text: <code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200)</code> should return <code>510</code>.
<del> testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200), 510, "<code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200)</code> should return <code>510</code>.");
<add> testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200), 510);
<ide> - text: <code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100)</code> should return <code>145</code>.
<del> testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100), 145, "<code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100)</code> should return <code>145</code>.");
<add> testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100), 145);
<ide> - text: <code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200)</code> should return <code>185</code>.
<del> testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200), 185, "<code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200)</code> should return <code>185</code>.");
<add> testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200), 185);
<ide> - text: <code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100)</code> should return <code>237</code>.
<del> testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100), 237, "<code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100)</code> should return <code>237</code>.");
<add> testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100), 237);
<ide> - text: <code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200)</code> should return <code>317</code>.'
<del> testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200), 317, "<code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200)</code> should return <code>317</code>.");
<add> testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200), 317);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function knapsack(items, maxweight) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function knapsack(items, maxweight) {
<del> var _ = {
<del> max: function (e) {
<del> var mx = e[0];
<del> e.forEach(function (f) {
<del> if (mx < f)
<del> mx = f;
<del> })
<del> return mx;
<del> },
<del> map: function (array, func) {
<del> return array.map(func)
<del> },
<del> isUndefined: function (a) {
<del> if (a) {
<del> return false;
<del> }
<del> return true;
<del> },
<del> range: function (start, end, step) {
<del> var a = []
<del> var f = f = (i, end) => i < end
<del> if (start > end)
<del> f = (i, end) => i > end
<del>
<del> for (var i = start; f(i, end); i += step)
<del> a.push(i)
<del> return a
<del> }
<add> var _ = {
<add> max: function(e) {
<add> var mx = e[0];
<add> e.forEach(function(f) {
<add> if (mx < f) mx = f;
<add> });
<add> return mx;
<add> },
<add> map: function(array, func) {
<add> return array.map(func);
<add> },
<add> isUndefined: function(a) {
<add> if (a) {
<add> return false;
<add> }
<add> return true;
<add> },
<add> range: function(start, end, step) {
<add> var a = [];
<add> var f = (f = (i, end) => i < end);
<add> if (start > end) f = (i, end) => i > end;
<add>
<add> for (var i = start; f(i, end); i += step) a.push(i);
<add> return a;
<ide> }
<del>
<del> var valuefn = (e) => e.value
<del> var weightfn = (e) => e.weight
<del> var _epsilon = 0.01;
<del> var _p = _.max(_.map(items, valuefn));
<del> var _k = _epsilon * _p / items.length;
<del>
<del> var _memo = (function () {
<del> var _mem = {};
<del> var _key = function (i, w) {
<del> return i + '::' + w;
<del> };
<del> return {
<del> get: function (i, w) {
<del> return _mem[_key(i, w)];
<del> },
<del> put: function (i, w, r) {
<del> _mem[_key(i, w)] = r;
<del> return r;
<del> }
<del> };
<del> })();
<del>
<del> var _m = function (i, w) {
<del>
<del> i = Math.round(i);
<del> w = Math.round(w);
<del>
<del>
<del> if (i < 0 || w === 0) {
<del> // empty base case
<del> return { items: [], totalWeight: 0, totalValue: 0 };
<del> }
<del>
<del> var mm = _memo.get(i, w);
<del> if (!_.isUndefined(mm)) {
<del> return mm;
<del> }
<del>
<del> var item = items[i];
<del> if (weightfn(item) > w) {
<del> //item does not fit, try the next item
<del> return _memo.put(i, w, _m(i - 1, w));
<del> }
<del> // this item could fit.
<del> // are we better off excluding it?
<del> var excluded = _m(i - 1, w);
<del> // or including it?
<del> var included = _m(i - 1, w - weightfn(item));
<del> if (included.totalValue + Math.floor(valuefn(item) / _k) > excluded.totalValue) {
<del> // better off including it
<del> // make a copy of the list
<del> var i1 = included.items.slice();
<del> i1.push(item);
<del> return _memo.put(i, w,
<del> {
<del> items: i1,
<del> totalWeight: included.totalWeight + weightfn(item),
<del> totalValue: included.totalValue + Math.floor(valuefn(item) / _k)
<del> });
<del> }
<del> //better off excluding it
<del> return _memo.put(i, w, excluded);
<add> };
<add>
<add> var valuefn = e => e.value;
<add> var weightfn = e => e.weight;
<add> var _epsilon = 0.01;
<add> var _p = _.max(_.map(items, valuefn));
<add> var _k = (_epsilon * _p) / items.length;
<add>
<add> var _memo = (function() {
<add> var _mem = {};
<add> var _key = function(i, w) {
<add> return i + '::' + w;
<add> };
<add> return {
<add> get: function(i, w) {
<add> return _mem[_key(i, w)];
<add> },
<add> put: function(i, w, r) {
<add> _mem[_key(i, w)] = r;
<add> return r;
<add> }
<ide> };
<del> var scaled = _m(items.length - 1, maxweight);
<add> })();
<ide>
<del> var val = 0;
<del> scaled.items.forEach(function (e) {
<del> val += e.value
<del> })
<del> return val;
<add> var _m = function(i, w) {
<add> i = Math.round(i);
<add> w = Math.round(w);
<add>
<add> if (i < 0 || w === 0) {
<add> // empty base case
<add> return { items: [], totalWeight: 0, totalValue: 0 };
<add> }
<add>
<add> var mm = _memo.get(i, w);
<add> if (!_.isUndefined(mm)) {
<add> return mm;
<add> }
<add>
<add> var item = items[i];
<add> if (weightfn(item) > w) {
<add> //item does not fit, try the next item
<add> return _memo.put(i, w, _m(i - 1, w));
<add> }
<add> // this item could fit.
<add> // are we better off excluding it?
<add> var excluded = _m(i - 1, w);
<add> // or including it?
<add> var included = _m(i - 1, w - weightfn(item));
<add> if (
<add> included.totalValue + Math.floor(valuefn(item) / _k) >
<add> excluded.totalValue
<add> ) {
<add> // better off including it
<add> // make a copy of the list
<add> var i1 = included.items.slice();
<add> i1.push(item);
<add> return _memo.put(i, w, {
<add> items: i1,
<add> totalWeight: included.totalWeight + weightfn(item),
<add> totalValue: included.totalValue + Math.floor(valuefn(item) / _k)
<add> });
<add> }
<add> //better off excluding it
<add> return _memo.put(i, w, excluded);
<add> };
<add> var scaled = _m(items.length - 1, maxweight);
<add>
<add> var val = 0;
<add> scaled.items.forEach(function(e) {
<add> val += e.value;
<add> });
<add> return val;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/knapsack-problem-bounded.english.md
<ide> forumTopicId: 323652
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> The bounded knapsack problem is defined as follows:
<ide> You are given an array of objects representing items to be put in a knapsack. The objects have 4 attributes: name, pieces (the number of the particular item), weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized. Keep in mind that each item can appear between 0 and <code>pieces</code> times.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300)</code> should return <code>755</code>.
<del> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300), 755, "<code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300)</code> should return <code>755</code>.");
<add> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300), 755);
<ide> - text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400)</code> should return <code>875</code>.
<del> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400), 875, "<code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400)</code> should return <code>875</code>.");
<add> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400), 875);
<ide> - text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500)</code> should return <code>1015</code>.
<del> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500), 1015, "<code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500)</code> should return <code>1015</code>.");
<add> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500), 1015);
<ide> - text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600)</code> should return <code>1120</code>.
<del> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600), 1120, "<code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600)</code> should return <code>1120</code>.");
<add> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600), 1120);
<ide> - text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700)</code> should return <code>1225</code>.
<del> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700), 1225, "<code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700)</code> should return <code>1225</code>.");
<add> testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700), 1225);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function findBestPack(data, maxweight) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function findBestPack(data, maxweight) {
<del> var m = [
<del> [0]
<del> ]; // maximum pack value found so far
<del> var b = [
<del> [0]
<del> ]; // best combination found so far
<add> var m = [[0]]; // maximum pack value found so far
<add> var b = [[0]]; // best combination found so far
<ide> var opts = [0]; // item index for 0 of item 0
<ide> var P = [1]; // item encoding for 0 of item 0
<ide> var choose = 0;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/knapsack-problem-continuous.english.md
<ide> forumTopicId: 323654
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> A thief burgles a butcher's shop, where he can select from some items.
<ide> The thief knows the weights and prices of each items. Because he has a knapsack with a limit on the maximum weight that it can carry, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after cutting that is proportional to the original price by the ratio of masses. That means: half of an item has half the price of the original.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes an array of objects representing the items available in the shop. Each object has 3 attributes: name, weight, and value. The function also takes the maximum weight as a parameter. The function should return the maximum value possible, and the total weight of the selected items should not exceed the maximum weight.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10)</code> should return <code>257.875</code>.
<del> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10), 257.875, '<code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10)</code> should return <code>257.875</code>.');
<add> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10), 257.875);
<ide> - text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12)</code> should return <code>295.05405405405406</code>.
<del> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12), 295.05405405405406, '<code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12)</code> should return <code>295.05405405405406</code>.');
<add> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12), 295.05405405405406);
<ide> - text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15)</code> should return <code>349.3783783783784</code>.
<del> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15), 349.3783783783784, '<code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15)</code> should return <code>349.3783783783784</code>.');
<add> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15), 349.3783783783784);
<ide> - text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22)</code> should return <code>459.5263157894737</code>.
<del> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22), 459.5263157894737, '<code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22)</code> should return <code>459.5263157894737</code>.');
<add> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22), 459.5263157894737);
<ide> - text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24)</code> should return <code>478.4736842105263</code>.
<del> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24), 478.4736842105263, '<code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24)</code> should return <code>478.4736842105263</code>.');
<add> testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24), 478.4736842105263);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>function knapContinuous (items, maxweight) {
<add>function knapContinuous(items, maxweight) {
<ide> // Good luck!
<ide> }
<ide> ```
<ide> function knapContinuous (items, maxweight) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function knapContinuous(items, maxweight) {
<ide> function item_cmp(a, b) {
<del> const ua = a.unitVal, ub = b.unitVal;
<add> const ua = a.unitVal,
<add> ub = b.unitVal;
<ide> return ua < ub ? 1 : ua > ub ? -1 : 0;
<ide> }
<del> items = items.map(({ value, weight }) => ({ unitVal: value / weight, weight }));
<del> items.sort(item_cmp)
<add> items = items.map(({ value, weight }) => ({
<add> unitVal: value / weight,
<add> weight
<add> }));
<add> items.sort(item_cmp);
<ide>
<ide> let val = 0;
<ide> let wt = 0;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/knapsack-problem-unbounded.english.md
<ide> forumTopicId: 323655
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri-La. Opting to leave, he is allowed to take as much as he likes of the items available there, so long as it will fit in his knapsack, and he can carry it.
<ide> He knows that he can carry no more than a particular value of maximum weight in total; and that the capacity of his knapsack has a limited volume.
<ide> He can only take whole units of any item, but there is much more of any item tha
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes an array of objects, maximum weight, and maximum volume as parameters. Each object has 4 attributes: name, value, weight, and volume. The function should return the maximum value of items the traveller can take with him.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25)</code> should return <code>54500</code>.
<del> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25), 54500, '<code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25)</code> should return <code>54500</code>.');
<add> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25), 54500);
<ide> - text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25)</code> should return <code>88400</code>.
<del> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25), 88400, '<code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25)</code> should return <code>88400</code>.');
<add> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25), 88400);
<ide> - text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15)</code> should return <code>42500</code>.
<del> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15), 42500, '<code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15)</code> should return <code>42500</code>.');
<add> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15), 42500);
<ide> - text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)</code> should return <code>75300</code>.
<del> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35), 75300, '<code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)</code> should return <code>75300</code>.');
<add> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35), 75300);
<ide> - text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25)</code> should return <code>43200</code>.
<del> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25), 43200, '<code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25)</code> should return <code>43200</code>.');
<add> testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25), 43200);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function knapsackUnbounded(items, maxweight, maxvolume) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function knapsackUnbounded(items, maxweight, maxvolume) {
<del> var n = items.length;
<del> var best_value = 0;
<del> var count = new Array(n)
<del> var best = new Array(n)
<del> function recurseKnapsack(i, value, weight, volume) {
<del> var j, m1, m2, m;
<del> if (i == n) {
<del> if (value > best_value) {
<del> best_value = value;
<del> for (j = 0; j < n; j++) {
<del> best[j] = count[j];
<del> }
<del> }
<del> return;
<del> }
<del> m1 = Math.floor(weight / items[i].weight);
<del> m2 = Math.floor(volume / items[i].volume);
<del> m = m1 < m2 ? m1 : m2;
<del> for (count[i] = m; count[i] >= 0; count[i]--) {
<del> recurseKnapsack(
<del> i + 1,
<del> value + count[i] * items[i].value,
<del> weight - count[i] * items[i].weight,
<del> volume - count[i] * items[i].volume
<del> );
<add> var n = items.length;
<add> var best_value = 0;
<add> var count = new Array(n);
<add> var best = new Array(n);
<add> function recurseKnapsack(i, value, weight, volume) {
<add> var j, m1, m2, m;
<add> if (i == n) {
<add> if (value > best_value) {
<add> best_value = value;
<add> for (j = 0; j < n; j++) {
<add> best[j] = count[j];
<ide> }
<add> }
<add> return;
<add> }
<add> m1 = Math.floor(weight / items[i].weight);
<add> m2 = Math.floor(volume / items[i].volume);
<add> m = m1 < m2 ? m1 : m2;
<add> for (count[i] = m; count[i] >= 0; count[i]--) {
<add> recurseKnapsack(
<add> i + 1,
<add> value + count[i] * items[i].value,
<add> weight - count[i] * items[i].weight,
<add> volume - count[i] * items[i].volume
<add> );
<ide> }
<add> }
<ide>
<del> recurseKnapsack(0, 0, maxweight, maxvolume);
<del> return best_value;
<add> recurseKnapsack(0, 0, maxweight, maxvolume);
<add> return best_value;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/knights-tour.english.md
<ide> forumTopicId: 302297
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> <a href="https://en.wikipedia.org/wiki/Knight%27s_tour">Knight's Tour</a>Problem: You have an empty <code>w</code> * <code>h</code> chessboard, but for a single knight on some square. The knight must perform a sequence of legal moves that result in the knight visiting every square on the chessboard exactly once. Note that it is <i>not</i> a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes <code>w</code> and <code>h</code> as parameters and returns the number of initial positions from where it is possible to achieve the task stated above.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>knightTour</code> should be a function.
<del> testString: assert(typeof knightTour == 'function', '<code>knightTour</code> should be a function.');
<add> testString: assert(typeof knightTour == 'function');
<ide> - text: <code>knightTour(6, 6)</code> should return a number.
<del> testString: assert(typeof knightTour(6, 6) == 'number', '<code>knightTour(6, 6)</code> should return a number.');
<add> testString: assert(typeof knightTour(6, 6) == 'number');
<ide> - text: <code>knightTour(6, 6)</code> should return <code>35</code>.
<del> testString: assert.equal(knightTour(6, 6), 35, '<code>knightTour(6, 6)</code> should return <code>35</code>.');
<add> testString: assert.equal(knightTour(6, 6), 35);
<ide> - text: <code>knightTour(5, 6)</code> should return <code>20</code>.
<del> testString: assert.equal(knightTour(5, 6), 20, '<code>knightTour(5, 6)</code> should return <code>20</code>.');
<add> testString: assert.equal(knightTour(5, 6), 20);
<ide> - text: <code>knightTour(4, 6)</code> should return <code>10</code>.
<del> testString: assert.equal(knightTour(4, 6), 10, '<code>knightTour(4, 6)</code> should return <code>10</code>.');
<add> testString: assert.equal(knightTour(4, 6), 10);
<ide> - text: <code>knightTour(7, 3)</code> should return <code>4</code>.
<del> testString: assert.equal(knightTour(7, 3), 4, '<code>knightTour(7, 3)</code> should return <code>4</code>.');
<add> testString: assert.equal(knightTour(7, 3), 4);
<ide> - text: <code>knightTour(8, 6)</code> should return <code>47</code>.
<del> testString: assert.equal(knightTour(8, 6), 47, '<code>knightTour(8, 6)</code> should return <code>47</code>.');
<add> testString: assert.equal(knightTour(8, 6), 47);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function knightTour(w, h) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>function knightTour (w, h) {
<del> var b, cnt=0;
<add>function knightTour(w, h) {
<add> var b,
<add> cnt = 0;
<ide>
<del> var dx = [ -2, -2, -1, 1, 2, 2, 1, -1 ];
<del> var dy = [ -1, 1, 2, 2, 1, -1, -2, -2 ];
<add> var dx = [-2, -2, -1, 1, 2, 2, 1, -1];
<add> var dy = [-1, 1, 2, 2, 1, -1, -2, -2];
<ide>
<del> function init_board()
<del> {
<del> var i, j, k, x, y;
<del> // * b is board; a is board with 2 rows padded at each side
<add> function init_board() {
<add> var i, j, k, x, y;
<add> // * b is board; a is board with 2 rows padded at each side
<ide>
<del> for(i=0;i<h;i++){
<del> for(j=0;j<w;j++){
<del> b[i][j]=255
<add> for (i = 0; i < h; i++) {
<add> for (j = 0; j < w; j++) {
<add> b[i][j] = 255;
<ide> }
<ide> }
<ide>
<del> for (i = 0; i < h; i++) {
<del> for (j = 0; j < w; j++) {
<del> for (k = 0; k < 8; k++) {
<del> x = j + dx[k], y = i + dy[k];
<del> if (b[i][j] == 255) b[i][j] = 0;
<del> if(x >= 0 && x < w && y >= 0 && y < h) b[i][j]++;
<del> }
<del> }
<del> }
<add> for (i = 0; i < h; i++) {
<add> for (j = 0; j < w; j++) {
<add> for (k = 0; k < 8; k++) {
<add> (x = j + dx[k]), (y = i + dy[k]);
<add> if (b[i][j] == 255) b[i][j] = 0;
<add> if (x >= 0 && x < w && y >= 0 && y < h) b[i][j]++;
<add> }
<add> }
<add> }
<ide> }
<ide>
<del> function walk_board(x, y)
<del> {
<del> var i, nx, ny, least;
<del> var steps = 0;
<del> // printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x);
<del>
<del> while (1) {
<del> // * occupy cell
<del> b[y][x] = 255;
<del>
<del> // * reduce all neighbors' neighbor count
<del> for (i = 0; i < 8; i++)
<del> if(y+dy[i] >= 0 && x+dx[i] >= 0 && y+dy[i] < h && x+dx[i] < w)
<del> b[ y + dy[i] ][ x + dx[i] ]--;
<del>
<del> // find neighbor with lowest neighbor count
<del> least = 255;
<del> for (i = 0; i < 8; i++) {
<del> if(y+dy[i] >= 0 && x+dx[i] >= 0 && y+dy[i] < h && x+dx[i] < w)
<del> if (b[ y + dy[i] ][ x + dx[i] ] < least) {
<del> nx = x + dx[i];
<del> ny = y + dy[i];
<del> least = b[ny][nx];
<del> }
<del> }
<del>
<del> if (least > 7) {
<del> return steps == w * h - 1;
<del> }
<add> function walk_board(x, y) {
<add> var i, nx, ny, least;
<add> var steps = 0;
<add> // printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x);
<add>
<add> while (1) {
<add> // * occupy cell
<add> b[y][x] = 255;
<add>
<add> // * reduce all neighbors' neighbor count
<add> for (i = 0; i < 8; i++)
<add> if (y + dy[i] >= 0 && x + dx[i] >= 0 && y + dy[i] < h && x + dx[i] < w)
<add> b[y + dy[i]][x + dx[i]]--;
<add>
<add> // find neighbor with lowest neighbor count
<add> least = 255;
<add> for (i = 0; i < 8; i++) {
<add> if (y + dy[i] >= 0 && x + dx[i] >= 0 && y + dy[i] < h && x + dx[i] < w)
<add> if (b[y + dy[i]][x + dx[i]] < least) {
<add> nx = x + dx[i];
<add> ny = y + dy[i];
<add> least = b[ny][nx];
<add> }
<add> }
<add>
<add> if (least > 7) {
<add> return steps == w * h - 1;
<add> }
<ide>
<ide> steps++;
<del> x = nx, y = ny;
<del> }
<add> (x = nx), (y = ny);
<add> }
<ide> }
<ide>
<del> function solve (x, y) {
<del> b=new Array(h);
<del> for(var i=0;i<h;i++)
<del> b[i]=new Array(w)
<add> function solve(x, y) {
<add> b = new Array(h);
<add> for (var i = 0; i < h; i++) b[i] = new Array(w);
<ide>
<del> init_board();
<del> if (walk_board(x, y)) {
<add> init_board();
<add> if (walk_board(x, y)) {
<ide> cnt++;
<del> }
<add> }
<ide> }
<ide>
<del> for(var i=0;i<h;i++){
<del> for(var j=0;j<w;j++){
<add> for (var i = 0; i < h; i++) {
<add> for (var j = 0; j < w; j++) {
<ide> solve(j, i);
<ide> }
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/largest-int-from-concatenated-ints.english.md
<ide> forumTopicId: 302298
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>maxCombine</code> should be a function.
<del> testString: assert(typeof maxCombine == 'function', '<code>maxCombine</code> should be a function.');
<add> testString: assert(typeof maxCombine == 'function');
<ide> - text: <code>maxCombine([1, 3, 3, 4, 55])</code> should return a number.
<del> testString: assert(typeof maxCombine([1, 3, 3, 4, 55]) == 'number', '<code>maxCombine([1, 3, 3, 4, 55])</code> should return a number.');
<add> testString: assert(typeof maxCombine([1, 3, 3, 4, 55]) == 'number');
<ide> - text: <code>maxCombine([1, 3, 3, 4, 55])</code> should return <code>554331</code>.
<del> testString: assert.equal(maxCombine([1, 3, 3, 4, 55]), 554331, '<code>maxCombine([1, 3, 3, 4, 55])</code> should return <code>554331</code>.');
<add> testString: assert.equal(maxCombine([1, 3, 3, 4, 55]), 554331);
<ide> - text: <code>maxCombine([71, 45, 23, 4, 5])</code> should return <code>71545423</code>.
<del> testString: assert.equal(maxCombine([71, 45, 23, 4, 5]), 71545423, '<code>maxCombine([71, 45, 23, 4, 5])</code> should return <code>71545423</code>.');
<add> testString: assert.equal(maxCombine([71, 45, 23, 4, 5]), 71545423);
<ide> - text: <code>maxCombine([14, 43, 53, 114, 55])</code> should return <code>55534314114</code>.
<del> testString: assert.equal(maxCombine([14, 43, 53, 114, 55]), 55534314114, '<code>maxCombine([14, 43, 53, 114, 55])</code> should return <code>55534314114</code>.');
<add> testString: assert.equal(maxCombine([14, 43, 53, 114, 55]), 55534314114);
<ide> - text: <code>maxCombine([1, 34, 3, 98, 9, 76, 45, 4])</code> should return <code>998764543431</code>.
<del> testString: assert.equal(maxCombine([1, 34, 3, 98, 9, 76, 45, 4]), 998764543431, '<code>maxCombine([1, 34, 3, 98, 9, 76, 45, 4])</code> should return <code>998764543431</code>.');
<add> testString: assert.equal(maxCombine([1, 34, 3, 98, 9, 76, 45, 4]), 998764543431);
<ide> - text: <code>maxCombine([54, 546, 548, 60])</code> should return <code>6054854654</code>.
<del> testString: assert.equal(maxCombine([54, 546, 548, 60]), 6054854654, '<code>maxCombine([54, 546, 548, 60])</code> should return <code>6054854654</code>.');
<add> testString: assert.equal(maxCombine([54, 546, 548, 60]), 6054854654);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function maxCombine(xs) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>function maxCombine (xs) {
<del> return parseInt(
<del> xs.sort(
<del> function (x, y) {
<del> var a = x.toString(),
<del> b = y.toString(),
<del> ab = parseInt(a + b),
<del> ba = parseInt(b + a);
<del>
<del> return ab > ba ? -1 : (ab < ba ? 1 : 0);
<del> }
<del> )
<del> .join(''), 10
<del> );
<add>function maxCombine(xs) {
<add> return parseInt(
<add> xs
<add> .sort(function(x, y) {
<add> var a = x.toString(),
<add> b = y.toString(),
<add> ab = parseInt(a + b),
<add> ba = parseInt(b + a);
<add>
<add> return ab > ba ? -1 : ab < ba ? 1 : 0;
<add> })
<add> .join(''),
<add> 10
<add> );
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/last-friday-of-each-month.english.md
<ide> forumTopicId: 302299
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Write a function that returns the date of the last Friday of a given month for a given year.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>lastFriday</code> should be a function.
<del> testString: assert(typeof lastFriday == 'function', '<code>lastFriday</code> should be a function.');
<add> testString: assert(typeof lastFriday == 'function');
<ide> - text: <code>lastFriday(2018, 1)</code> should return a number.
<del> testString: assert(typeof lastFriday(2018, 1) == 'number', '<code>lastFriday(2018, 1)</code> should return a number.');
<add> testString: assert(typeof lastFriday(2018, 1) == 'number');
<ide> - text: <code>lastFriday(2018, 1)</code> should return <code>26</code>.
<del> testString: assert.equal(lastFriday(2018, 1), 26, '<code>lastFriday(2018, 1)</code> should return <code>26</code>.');
<add> testString: assert.equal(lastFriday(2018, 1), 26);
<ide> - text: <code>lastFriday(2017, 2)</code> should return <code>24</code>.
<del> testString: assert.equal(lastFriday(2017, 2), 24, '<code>lastFriday(2017, 2)</code> should return <code>24</code>.');
<add> testString: assert.equal(lastFriday(2017, 2), 24);
<ide> - text: <code>lastFriday(2012, 3)</code> should return <code>30</code>.
<del> testString: assert.equal(lastFriday(2012, 3), 30, '<code>lastFriday(2012, 3)</code> should return <code>30</code>.');
<add> testString: assert.equal(lastFriday(2012, 3), 30);
<ide> - text: <code>lastFriday(1900, 4)</code> should return <code>27</code>.
<del> testString: assert.equal(lastFriday(1900, 4), 27, '<code>lastFriday(1900, 4)</code> should return <code>27</code>.');
<add> testString: assert.equal(lastFriday(1900, 4), 27);
<ide> - text: <code>lastFriday(2000, 5)</code> should return <code>26</code>.
<del> testString: assert.equal(lastFriday(2000, 5), 26, '<code>lastFriday(2000, 5)</code> should return <code>26</code>.');
<add> testString: assert.equal(lastFriday(2000, 5), 26);
<ide> - text: <code>lastFriday(2006, 6)</code> should return <code>30</code>.
<del> testString: assert.equal(lastFriday(2006, 6), 30, '<code>lastFriday(2006, 6)</code> should return <code>30</code>.');
<add> testString: assert.equal(lastFriday(2006, 6), 30);
<ide> - text: <code>lastFriday(2010, 7)</code> should return <code>30</code>.
<del> testString: assert.equal(lastFriday(2010, 7), 30, '<code>lastFriday(2010, 7)</code> should return <code>30</code>.');
<add> testString: assert.equal(lastFriday(2010, 7), 30);
<ide> - text: <code>lastFriday(2005, 8)</code> should return <code>26</code>.
<del> testString: assert.equal(lastFriday(2005, 8), 26, '<code>lastFriday(2005, 8)</code> should return <code>26</code>.');
<add> testString: assert.equal(lastFriday(2005, 8), 26);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function lastFriday(year, month) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>function lastFriday (year, month) {
<add>function lastFriday(year, month) {
<ide> var i, last_day;
<ide> i = 0;
<ide> while (true) {
<ide> function lastFriday (year, month) {
<ide> }
<ide> i -= 1;
<ide> }
<del>};
<add>}
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/leap-year.english.md
<ide> forumTopicId: 302300
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Determine whether a given year is a leap year in the Gregorian calendar.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>isLeapYear</code> should be a function.
<del> testString: assert(typeof isLeapYear == 'function', '<code>isLeapYear</code> should be a function.');
<add> testString: assert(typeof isLeapYear == 'function');
<ide> - text: <code>isLeapYear()</code> should return a boolean.
<del> testString: assert(typeof isLeapYear(2018) == 'boolean', '<code>isLeapYear()</code> should return a boolean.');
<add> testString: assert(typeof isLeapYear(2018) == 'boolean');
<ide> - text: <code>isLeapYear(2018)</code> should return <code>false</code>.
<del> testString: assert.equal(isLeapYear(2018), false, '<code>isLeapYear(2018)</code> should return <code>false</code>.');
<add> testString: assert.equal(isLeapYear(2018), false);
<ide> - text: <code>isLeapYear(2016)</code> should return <code>true</code>.
<del> testString: assert.equal(isLeapYear(2016), true, '<code>isLeapYear(2016)</code> should return <code>true</code>.');
<add> testString: assert.equal(isLeapYear(2016), true);
<ide> - text: <code>isLeapYear(2000)</code> should return <code>true</code>.
<del> testString: assert.equal(isLeapYear(2000), true, '<code>isLeapYear(2000)</code> should return <code>true</code>.');
<add> testString: assert.equal(isLeapYear(2000), true);
<ide> - text: <code>isLeapYear(1900)</code> should return <code>false</code>.
<del> testString: assert.equal(isLeapYear(1900), false, '<code>isLeapYear(1900)</code> should return <code>false</code>.');
<add> testString: assert.equal(isLeapYear(1900), false);
<ide> - text: <code>isLeapYear(1996)</code> should return <code>true</code>.
<del> testString: assert.equal(isLeapYear(1996), true, '<code>isLeapYear(1996)</code> should return <code>true</code>.');
<add> testString: assert.equal(isLeapYear(1996), true);
<ide> - text: <code>isLeapYear(1800)</code> should return <code>false</code>.
<del> testString: assert.equal(isLeapYear(1800), false, '<code>isLeapYear(1800)</code> should return <code>false</code>.');
<add> testString: assert.equal(isLeapYear(1800), false);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function isLeapYear(year) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>function isLeapYear (year) {
<del> return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
<del>};
<add>function isLeapYear(year) {
<add> return year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;
<add>}
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/least-common-multiple.english.md
<ide> forumTopicId: 302301
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<del>The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either <i>m</i> or <i>n</i> is zero, then the least common multiple is zero.
<del>One way to calculate the least common multiple is to iterate all the multiples of <i>m</i>, until you find one that is also a multiple of <i>n</i>.
<del>If you already have <i>gcd</i> for <a href="https://rosettacode.org/wiki/greatest common divisor" target="_blank">greatest common divisor</a>, then this formula calculates <i>lcm</i>.
<add>The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either <i>m</i> or <i>n</i> is zero, then the least common multiple is zero.
<add>One way to calculate the least common multiple is to iterate all the multiples of <i>m</i>, until you find one that is also a multiple of <i>n</i>.
<add>If you already have <i>gcd</i> for <a href="https://rosettacode.org/wiki/greatest common divisor" target="_blank">greatest common divisor</a>, then this formula calculates <i>lcm</i>.
<ide> \( \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} \)
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Compute the least common multiple of an array of integers.
<del>Given <i>m</i> and <i>n</i>, the least common multiple is the smallest positive integer that has both <i>m</i> and <i>n</i> as factors.
<add>Given <i>m</i> and <i>n</i>, the least common multiple is the smallest positive integer that has both <i>m</i> and <i>n</i> as factors.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>LCM</code> should be a function.
<del> testString: assert(typeof LCM == 'function', '<code>LCM</code> should be a function.');
<add> testString: assert(typeof LCM == 'function');
<ide> - text: <code>LCM([2, 4, 8])</code> should return a number.
<del> testString: assert(typeof LCM([2, 4, 8]) == 'number', '<code>LCM([2, 4, 8])</code> should return a number.');
<add> testString: assert(typeof LCM([2, 4, 8]) == 'number');
<ide> - text: <code>LCM([2, 4, 8])</code> should return <code>8</code>.
<del> testString: assert.equal(LCM([2, 4, 8]), 8, '<code>LCM([2, 4, 8])</code> should return <code>8</code>.');
<add> testString: assert.equal(LCM([2, 4, 8]), 8);
<ide> - text: <code>LCM([4, 8, 12])</code> should return <code>24</code>.
<del> testString: assert.equal(LCM([4, 8, 12]), 24, '<code>LCM([4, 8, 12])</code> should return <code>24</code>.');
<add> testString: assert.equal(LCM([4, 8, 12]), 24);
<ide> - text: <code>LCM([3, 4, 5, 12, 40])</code> should return <code>120</code>.
<del> testString: assert.equal(LCM([3, 4, 5, 12, 40]), 120, '<code>LCM([3, 4, 5, 12, 40])</code> should return <code>120</code>.');
<add> testString: assert.equal(LCM([3, 4, 5, 12, 40]), 120);
<ide> - text: <code>LCM([11, 33, 90])</code> should return <code>990</code>.
<del> testString: assert.equal(LCM([11, 33, 90]), 990, '<code>LCM([11, 33, 90])</code> should return <code>990</code>.');
<add> testString: assert.equal(LCM([11, 33, 90]), 990);
<ide> - text: <code>LCM([-50, 25, -45, -18, 90, 447])</code> should return <code>67050</code>.
<del> testString: assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050, '<code>LCM([-50, 25, -45, -18, 90, 447])</code> should return <code>67050</code>.');
<add> testString: assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function LCM(A) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>function LCM (A) {
<del> var n = A.length, a = Math.abs(A[0]);
<del> for (var i = 1; i < n; i++)
<del> { var b = Math.abs(A[i]), c = a;
<del> while (a && b){ a > b ? a %= b : b %= a; }
<del> a = Math.abs(c*A[i])/(a+b);
<del> }
<del> return a;
<add>function LCM(A) {
<add> var n = A.length,
<add> a = Math.abs(A[0]);
<add> for (var i = 1; i < n; i++) {
<add> var b = Math.abs(A[i]),
<add> c = a;
<add> while (a && b) {
<add> a > b ? (a %= b) : (b %= a);
<add> }
<add> a = Math.abs(c * A[i]) / (a + b);
<add> }
<add> return a;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/left-factorials.english.md
<ide> forumTopicId: 302302
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> <b>Left factorials</b>, $ !n $, may refer to either <i>subfactorials</i> or to <i>factorial sums</i>. The same notation can be confusingly seen used for the two different definitions. Sometimes, <i>subfactorials</i> (also known as <i>derangements</i>) may use any of the notations:
<ide> <ul>
<ide> where $!0 = 0$
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function to calculate the left factorial of a given number.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>leftFactorial</code> should be a function.
<del> testString: assert(typeof leftFactorial == 'function', '<code>leftFactorial</code> should be a function.');
<add> testString: assert(typeof leftFactorial == 'function');
<ide> - text: <code>leftFactorial(0)</code> should return a number.
<del> testString: assert(typeof leftFactorial(0) == 'number', '<code>leftFactorial(0)</code> should return a number.');
<add> testString: assert(typeof leftFactorial(0) == 'number');
<ide> - text: <code>leftFactorial(0)</code> should return <code>0</code>.
<del> testString: assert.equal(leftFactorial(0), 0, '<code>leftFactorial(0)</code> should return <code>0</code>.');
<add> testString: assert.equal(leftFactorial(0), 0);
<ide> - text: <code>leftFactorial(1)</code> should return <code>1</code>.
<del> testString: assert.equal(leftFactorial(1), 1, '<code>leftFactorial(1)</code> should return <code>1</code>.');
<add> testString: assert.equal(leftFactorial(1), 1);
<ide> - text: <code>leftFactorial(2)</code> should return <code>2</code>.
<del> testString: assert.equal(leftFactorial(2), 2, '<code>leftFactorial(2)</code> should return <code>2</code>.');
<add> testString: assert.equal(leftFactorial(2), 2);
<ide> - text: <code>leftFactorial(3)</code> should return <code>4</code>.
<del> testString: assert.equal(leftFactorial(3), 4, '<code>leftFactorial(3)</code> should return <code>4</code>.');
<add> testString: assert.equal(leftFactorial(3), 4);
<ide> - text: <code>leftFactorial(10)</code> should return <code>409114</code>.
<del> testString: assert.equal(leftFactorial(10), 409114, '<code>leftFactorial(10)</code> should return <code>409114</code>.');
<add> testString: assert.equal(leftFactorial(10), 409114);
<ide> - text: <code>leftFactorial(17)</code> should return <code>22324392524314</code>.
<del> testString: assert.equal(leftFactorial(17), 22324392524314, '<code>leftFactorial(17)</code> should return <code>22324392524314</code>.');
<add> testString: assert.equal(leftFactorial(17), 22324392524314);
<ide> - text: <code>leftFactorial(19)</code> should return <code>6780385526348314</code>.
<del> testString: assert.equal(leftFactorial(19), 6780385526348314, '<code>leftFactorial(19)</code> should return <code>6780385526348314</code>.');
<add> testString: assert.equal(leftFactorial(19), 6780385526348314);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function leftFactorial(n) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function leftFactorial(n) {
<del> if (n == 0)
<del> return 0
<del> if (n == 1)
<del> return 1;
<del>
<del> // Note: for n>=20, the result may not be correct.
<del> // This is because JavaScript uses 53 bit integers and
<del> // for n>=20 result becomes too large.
<del>
<del> let res = 2, fact = 2;
<del> for (var i = 2; i < n; i++) {
<del> res += fact;
<del> fact *= (i + 1);
<del> }
<del>
<del> return res;
<add> if (n == 0) return 0;
<add> if (n == 1) return 1;
<add>
<add> // Note: for n>=20, the result may not be correct.
<add> // This is because JavaScript uses 53 bit integers and
<add> // for n>=20 result becomes too large.
<add>
<add> let res = 2,
<add> fact = 2;
<add> for (var i = 2; i < n; i++) {
<add> res += fact;
<add> fact *= i + 1;
<add> }
<add>
<add> return res;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sort-disjoint-sublist.english.md
<ide> forumTopicId: 302307
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted.
<ide> Make your function work with the following list of values and set of indices:
<ide> Where the correct result would be:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sortDisjoint</code> should be a function.
<del> testString: assert(typeof sortDisjoint == 'function', '<code>sortDisjoint</code> should be a function.');
<add> testString: assert(typeof sortDisjoint == 'function');
<ide> - text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return an array.
<del> testString: assert(Array.isArray(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])), '<code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return an array.');
<add> testString: assert(Array.isArray(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])));
<ide> - text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return <code>[7, 0, 5, 4, 3, 2, 1, 6]</code>.
<del> testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]), [7, 0, 5, 4, 3, 2, 1, 6], '<code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return <code>[7, 0, 5, 4, 3, 2, 1, 6]</code>.');
<add> testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]), [7, 0, 5, 4, 3, 2, 1, 6]);
<ide> - text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6])</code> should return <code>[7, 1, 2, 4, 3, 5, 6, 0]</code>.
<del> testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6]), [7, 1, 2, 4, 3, 5, 6, 0], '<code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6])</code> should return <code>[7, 1, 2, 4, 3, 5, 6, 0]</code>.');
<add> testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6]), [7, 1, 2, 4, 3, 5, 6, 0]);
<ide> - text: <code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7])</code> should return <code>[8, 1, 6, 5, 4, 3, 2, 7]</code>.
<del> testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7]), [8, 1, 6, 5, 4, 3, 2, 7], '<code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7])</code> should return <code>[8, 1, 6, 5, 4, 3, 2, 7]</code>.');
<add> testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7]), [8, 1, 6, 5, 4, 3, 2, 7]);
<ide> - text: <code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6])</code> should return <code>[8, 2, 6, 3, 4, 5, 7, 1]</code>.
<del> testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6]), [8, 2, 6, 3, 4, 5, 7, 1], '<code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6])</code> should return <code>[8, 2, 6, 3, 4, 5, 7, 1]</code>.');
<add> testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6]), [8, 2, 6, 3, 4, 5, 7, 1]);
<ide> - text: <code>sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4])</code> should return <code>[6, 1, 7, 1, 3, 5, 6]</code>.
<del> testString: assert.deepEqual(sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4]), [6, 1, 7, 1, 3, 5, 6],'<code>sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4])</code> should return <code>[6, 1, 7, 1, 3, 5, 6]</code>.');
<add> testString: assert.deepEqual(sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4]), [6, 1, 7, 1, 3, 5, 6]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function sortDisjoint(values, indices) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function sortDisjoint(values, indices) {
<ide> let sublist = [];
<ide>
<del> indices.sort(function (a, b) { return a - b; });
<del>
<add> indices.sort(function(a, b) {
<add> return a - b;
<add> });
<add>
<ide> for (let i = 0; i < indices.length; i++) {
<ide> sublist.push(values[indices[i]]);
<ide> }
<del>
<del> sublist.sort((a, b) => { return a - b; });
<del>
<add>
<add> sublist.sort((a, b) => {
<add> return a - b;
<add> });
<add>
<ide> for (let i = 0; i < indices.length; i++) {
<ide> values[indices[i]] = sublist[i];
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sort-stability.english.md
<ide> forumTopicId: 302308
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> When sorting records in a table by a particular column or field, a <a href="https://en.wikipedia.org/wiki/Stable_sort#Stability" target="_blank">stable sort</a> will always retain the relative order of records that have the same key.
<ide> For example, in this table of countries and cities, a stable sort on the <b>second</b> column, the cities, would keep the US Birmingham above the UK Birmingham. (Although an unstable sort <i>might</i>, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would <i>guarantee</i> it).
<ide> Similarly, stable sorting on just the first column would generate "UK London" as
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes a 2D array as a parameter. Each element has 2 elements similar to the above example. The function should sort the array as mentioned previously and return the sorted array.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>stableSort</code> should be a function.
<del> testString: assert(typeof stableSort == 'function', '<code>stableSort</code> should be a function.');
<add> testString: assert(typeof stableSort == 'function');
<ide> - text: <code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return an array.
<del> testString: assert(Array.isArray(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])), '<code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return an array.');
<add> testString: assert(Array.isArray(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])));
<ide> - text: <code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return <code>[["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</code>.
<del> testString: assert.deepEqual(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]), [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]], '<code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return <code>[["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</code>.');
<add> testString: assert.deepEqual(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]), [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]);
<ide> - text: <code>stableSort([[2, 2], [1, 2], [1, 4], [1, 5]])</code> should return <code>[[2, 2], [1, 2], [1, 4], [1, 5]]</code>.
<del> testString: assert.deepEqual(stableSort([[2, 2], [1, 2], [1, 4], [1, 5]]), [[2, 2], [1, 2], [1, 4], [1, 5]], '<code>stableSort([[2, 2], [1, 2], [1, 4], [1, 5]])</code> should return <code>[[2, 2], [1, 2], [1, 4], [1, 5]]</code>.');
<add> testString: assert.deepEqual(stableSort([[2, 2], [1, 2], [1, 4], [1, 5]]), [[2, 2], [1, 2], [1, 4], [1, 5]]);
<ide> - text: <code>stableSort([[11, 55], [12, 45], [11, 45], [32, 45]])</code> should return <code>[[12, 45], [11, 45], [32, 45], [11, 55]]</code>.
<del> testString: assert.deepEqual(stableSort([[11, 55], [12, 45], [11, 45], [32, 45]]), [[12, 45], [11, 45], [32, 45], [11, 55]], '<code>stableSort([[11, 55], [12, 45], [11, 45], [32, 45]])</code> should return <code>[[12, 45], [11, 45], [32, 45], [11, 55]]</code>.');
<add> testString: assert.deepEqual(stableSort([[11, 55], [12, 45], [11, 45], [32, 45]]), [[12, 45], [11, 45], [32, 45], [11, 55]]);
<ide> - text: <code>stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]])</code> should return <code>[[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]</code>.
<del> testString: assert.deepEqual(stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]]), [[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]], '<code>stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]])</code> should return <code>[[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]</code>.');
<add> testString: assert.deepEqual(stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]]), [[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]);
<ide> - text: <code>stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]])</code> should return <code>[[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]</code>.
<del> testString: assert.deepEqual(stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]]), [[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]], '<code>stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]])</code> should return <code>[[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]</code>.');
<add> testString: assert.deepEqual(stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]]), [[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function stableSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function stableSort(arr) {
<del> arr.sort(function (a, b) { return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0)) });
<del> return arr;
<add> arr.sort(function(a, b) {
<add> return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
<add> });
<add> return arr;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sort-using-a-custom-comparator.english.md
<ide> forumTopicId: 302309
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>lengthSorter</code> should be a function.
<del> testString: assert(typeof lengthSorter == 'function', '<code>lengthSorter</code> should be a function.');
<add> testString: assert(typeof lengthSorter == 'function');
<ide> - text: <code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return an array.
<del> testString: assert(Array.isArray(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])), '<code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return an array.');
<add> testString: assert(Array.isArray(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])));
<ide> - text: <code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return <code>["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]</code>.
<del> testString: assert.deepEqual(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]), ["strings", "sample", "sorted", "Here", "some", "are", "be", "to"], '<code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return <code>["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]</code>.');
<add> testString: assert.deepEqual(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]), ["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]);
<ide> - text: <code>lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"])</code> should return <code>["going", "good", "hope", "your", "day", "is", "?","I"]</code>.
<del> testString: assert.deepEqual(lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"]), ["going", "good", "hope", "your", "day", "is", "?","I"], '<code>lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"])</code> should return <code>["going", "good", "hope", "your", "day", "is", "?","I"]</code>.');
<add> testString: assert.deepEqual(lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"]), ["going", "good", "hope", "your", "day", "is", "?","I"]);
<ide> - text: <code>lengthSorter(["Mine", "is", "going", "great"])</code> should return <code>["going", "great", "Mine", "is"]</code>.
<del> testString: assert.deepEqual(lengthSorter(["Mine", "is", "going", "great"]), ["going", "great", "Mine", "is"], '<code>lengthSorter(["Mine", "is", "going", "great"])</code> should return <code>["going", "great", "Mine", "is"]</code>.');
<add> testString: assert.deepEqual(lengthSorter(["Mine", "is", "going", "great"]), ["going", "great", "Mine", "is"]);
<ide> - text: <code>lengthSorter(["Have", "fun", "sorting", "!!"])</code> should return <code>["sorting", "Have", "fun", "!!"]</code>.
<del> testString: assert.deepEqual(lengthSorter(["Have", "fun", "sorting", "!!"]), ["sorting", "Have", "fun", "!!"], '<code>lengthSorter(["Have", "fun", "sorting", "!!"])</code> should return <code>["sorting", "Have", "fun", "!!"]</code>.');
<add> testString: assert.deepEqual(lengthSorter(["Have", "fun", "sorting", "!!"]), ["sorting", "Have", "fun", "!!"]);
<ide> - text: <code>lengthSorter(["Everything", "is", "good", "!!"])</code> should return <code>["Everything", "good", "!!", "is"]</code>.
<del> testString: assert.deepEqual(lengthSorter(["Everything", "is", "good", "!!"]), ["Everything", "good", "!!", "is"], '<code>lengthSorter(["Everything", "is", "good", "!!"])</code> should return <code>["Everything", "good", "!!", "is"]</code>.');
<add> testString: assert.deepEqual(lengthSorter(["Everything", "is", "good", "!!"]), ["Everything", "good", "!!", "is"]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function lengthSorter(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function lengthSorter(arr) {
<del> arr.sort(function (a, b) {
<del> var result = b.length - a.length;
<del> if (result == 0)
<del> result = a.localeCompare(b);
<del> return result;
<del> })
<del> return arr;
<add> arr.sort(function(a, b) {
<add> var result = b.length - a.length;
<add> if (result == 0) result = a.localeCompare(b);
<add> return result;
<add> });
<add> return arr;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-bead-sort.english.md
<ide> forumTopicId: 302310
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Sort an array of positive integers using the <a href="https://en.wikipedia.org/wiki/Bead_sort" target="_blank">Bead Sort Algorithm</a>.
<ide> A <i>bead sort</i> is also known as a <i>gravity sort</i>.
<ide> This is the case when bead sort is implemented without a mechanism to assist in
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>beadSort</code> should be a function.
<del> testString: assert(typeof beadSort == 'function', '<code>beadSort</code> should be a function.');
<add> testString: assert(typeof beadSort == 'function');
<ide> - text: <code>beadSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(beadSort([25, 32, 12, 7, 20])), '<code>beadSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(beadSort([25, 32, 12, 7, 20])));
<ide> - text: <code>beadSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(beadSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>beadSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(beadSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>beadSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(beadSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>beadSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(beadSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>beadSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(beadSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>beadSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(beadSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>beadSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(beadSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>beadSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(beadSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>beadSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(beadSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>beadSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(beadSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function beadSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function beadSort(arr) {
<del> var max = 0;
<del> for (var i = 0; i < arr.length; i++)
<del> if (arr[i] > max)
<del> max = arr[i];;
<del> var grid = new Array(arr.length);
<del> for (var i = 0; i < grid.length; i++) {
<del> grid[i] = new Array(max);
<add> var max = 0;
<add> for (var i = 0; i < arr.length; i++) if (arr[i] > max) max = arr[i];
<add> var grid = new Array(arr.length);
<add> for (var i = 0; i < grid.length; i++) {
<add> grid[i] = new Array(max);
<add> }
<add> var levelcount = new Array(max);
<add> levelcount.fill(0);
<add> for (var i = 0; i < max; i++) {
<add> levelcount[i] = 0;
<add> for (var j = 0; j < arr.length; j++) grid[j][i] = '_';
<add> }
<add> for (var i = 0; i < arr.length; i++) {
<add> var num = arr[i];
<add> for (var j = 0; num > 0; j++) {
<add> grid[levelcount[j]++][j] = '*';
<add> num--;
<ide> }
<del> var levelcount = new Array(max);
<del> levelcount.fill(0)
<del> for (var i = 0; i < max; i++) {
<del> levelcount[i] = 0;
<del> for (var j = 0; j < arr.length; j++)
<del> grid[j][i] = '_';
<del> };
<del> for (var i = 0; i < arr.length; i++) {
<del> var num = arr[i];
<del> for (var j = 0; num > 0; j++) {
<del> grid[levelcount[j]++][j] = '*';
<del> num--;
<del> };
<del> };
<del> var sorted = new Array(arr.length)
<del> sorted.fill(0)
<del> for (var i = 0; i < arr.length; i++) {
<del> var putt = 0;
<del> for (var j = 0; j < max && (function (c) {
<del> return c.charCodeAt == null ? c : c.charCodeAt(0);
<del> })(grid[arr.length - 1 - i][j]) == '*'.charCodeAt(0); j++)
<del> putt++;
<del> sorted[i] = putt;
<del> };
<del> return sorted;
<add> }
<add> var sorted = new Array(arr.length);
<add> sorted.fill(0);
<add> for (var i = 0; i < arr.length; i++) {
<add> var putt = 0;
<add> for (
<add> var j = 0;
<add> j < max &&
<add> (function(c) {
<add> return c.charCodeAt == null ? c : c.charCodeAt(0);
<add> })(grid[arr.length - 1 - i][j]) == '*'.charCodeAt(0);
<add> j++
<add> )
<add> putt++;
<add> sorted[i] = putt;
<add> }
<add> return sorted;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-bogosort.english.md
<ide> forumTopicId: 302311
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> <a href="https://en.wikipedia.org/wiki/Bogosort" target="_blank">Bogosort</a> a list of numbers.
<ide> Bogosort simply shuffles a collection randomly until it is sorted.
<ide> Pseudocode:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>bogosort</code> should be a function.
<del> testString: assert(typeof bogosort == 'function', '<code>bogosort</code> should be a function.');
<add> testString: assert(typeof bogosort == 'function');
<ide> - text: <code>bogosort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(bogosort([25, 32, 12, 7, 20])), '<code>bogosort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(bogosort([25, 32, 12, 7, 20])));
<ide> - text: <code>bogosort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(bogosort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>bogosort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(bogosort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>bogosort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(bogosort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>bogosort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(bogosort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>bogosort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(bogosort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>bogosort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(bogosort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>bogosort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(bogosort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>bogosort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(bogosort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>bogosort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(bogosort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>bogosort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(bogosort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function bogosort(v) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function bogosort(v) {
<del> function shuffle(v) {
<del> for (var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
<del> return v;
<del> };
<del>
<del> function isSorted(v) {
<del> for (var i = 1; i < v.length; i++) {
<del> if (v[i - 1] > v[i]) {
<del> return false;
<del> }
<del> }
<del> return true;
<del> }
<del> var sorted = false;
<del> while (sorted == false) {
<del> v = shuffle(v);
<del> sorted = isSorted(v);
<del> }
<add> function shuffle(v) {
<add> for (
<add> var j, x, i = v.length;
<add> i;
<add> j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x
<add> );
<ide> return v;
<add> }
<add>
<add> function isSorted(v) {
<add> for (var i = 1; i < v.length; i++) {
<add> if (v[i - 1] > v[i]) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add> var sorted = false;
<add> while (sorted == false) {
<add> v = shuffle(v);
<add> sorted = isSorted(v);
<add> }
<add> return v;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-cocktail-sort.english.md
<ide> forumTopicId: 302312
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> The cocktail shaker sort is an improvement on the <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from <a href="https://en.wikipedia.org/wiki/Cocktail sort" target="_blank">wikipedia</a>):</p>
<ide> <pre>
<ide> The cocktail shaker sort is an improvement on the <a href="https://rosettacode.o
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that sorts a given array using cocktail sort.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>cocktailSort</code> should be a function.
<del> testString: assert(typeof cocktailSort == 'function', '<code>cocktailSort</code> should be a function.');
<add> testString: assert(typeof cocktailSort == 'function');
<ide> - text: <code>cocktailSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(cocktailSort([25, 32, 12, 7, 20])), '<code>cocktailSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(cocktailSort([25, 32, 12, 7, 20])));
<ide> - text: <code>cocktailSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(cocktailSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>cocktailSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(cocktailSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>cocktailSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(cocktailSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>cocktailSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(cocktailSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>cocktailSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(cocktailSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>cocktailSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(cocktailSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>cocktailSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(cocktailSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>cocktailSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(cocktailSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>cocktailSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(cocktailSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>cocktailSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(cocktailSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function cocktailSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function cocktailSort(arr) {
<ide> }
<ide> }
<ide>
<del> if (!isSorted)
<del> break;
<add> if (!isSorted) break;
<ide>
<ide> isSorted = false;
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-comb-sort.english.md
<ide> forumTopicId: 302313
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Implement a <i>comb sort</i>.
<ide> The <b>Comb Sort</b> is a variant of the <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>.
<ide> Pseudocode:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that sorts a given array using Comb sort.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>combSort</code> should be a function.
<del> testString: assert(typeof combSort == 'function', '<code>combSort</code> should be a function.');
<add> testString: assert(typeof combSort == 'function');
<ide> - text: <code>combSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(combSort([25, 32, 12, 7, 20])), '<code>combSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(combSort([25, 32, 12, 7, 20])));
<ide> - text: <code>combSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(combSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>combSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(combSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>combSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(combSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>combSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(combSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>combSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(combSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>combSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(combSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>combSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(combSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>combSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(combSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>combSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(combSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>combSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(combSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function combSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function combSort(arr) {
<ide> // If not first gap
<ide> if (iteration_count > 0)
<ide> // Calculate gap
<del> gap = (gap == 1) ? gap : Math.floor(gap / decrease_factor);
<add> gap = gap == 1 ? gap : Math.floor(gap / decrease_factor);
<ide>
<ide> // Set front and back elements and increment to a gap
<ide> var front = 0;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-gnome-sort.english.md
<ide> forumTopicId: 302314
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Gnome sort is a sorting algorithm which is similar to <a href="https://rosettacode.org/wiki/Insertion sort" target="_blank">Insertion sort</a>, except that moving an element to its proper place is accomplished by a series of swaps, as in <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>.
<ide> The pseudocode for the algorithm is:
<ide> The pseudocode for the algorithm is:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function to implement the above pseudo code. The function should return the sorted array.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>gnomeSort</code> should be a function.
<del> testString: assert(typeof gnomeSort == 'function', '<code>gnomeSort</code> should be a function.');
<add> testString: assert(typeof gnomeSort == 'function');
<ide> - text: <code>gnomeSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(gnomeSort([25, 32, 12, 7, 20])), '<code>gnomeSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(gnomeSort([25, 32, 12, 7, 20])));
<ide> - text: <code>gnomeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(gnomeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>gnomeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(gnomeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>gnomeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(gnomeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>gnomeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(gnomeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>gnomeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(gnomeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>gnomeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(gnomeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>gnomeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(gnomeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>gnomeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(gnomeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>gnomeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(gnomeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>gnomeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(gnomeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function gnomeSort(a) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-pancake-sort.english.md
<ide> forumTopicId: 302315
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to sort an array of integers (of any convenient size) into ascending order using <a href="https://en.wikipedia.org/wiki/Pancake sorting" target="_blank">Pancake sorting</a>. The function should return the sorted array.
<ide> In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
<ide> Only one end of the list can be flipped; this should be the low end, but the hig
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>pancakeSort</code> should be a function.
<del> testString: assert(typeof pancakeSort == 'function', '<code>pancakeSort</code> should be a function.');
<add> testString: assert(typeof pancakeSort == 'function');
<ide> - text: <code>pancakeSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(pancakeSort([25, 32, 12, 7, 20])), '<code>pancakeSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(pancakeSort([25, 32, 12, 7, 20])));
<ide> - text: <code>pancakeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(pancakeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>pancakeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(pancakeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>pancakeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(pancakeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>pancakeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(pancakeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>pancakeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(pancakeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>pancakeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(pancakeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>pancakeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(pancakeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>pancakeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(pancakeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>pancakeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(pancakeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>pancakeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(pancakeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function pancakeSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function pancakeSort(arr) {
<del> for (var i = arr.length - 1; i >= 1; i--) {
<del> // find the index of the largest element not yet sorted
<del> var max_idx = 0;
<del> var max = arr[0];
<del> for (var j = 1; j <= i; j++) {
<del> if (arr[j] > max) {
<del> max = arr[j];
<del> max_idx = j;
<del> }
<del> }
<del>
<del> if (max_idx == i)
<del> continue; // element already in place
<del>
<del> var new_slice;
<del>
<del> // flip arr max element to index 0
<del> if (max_idx > 0) {
<del> new_slice = arr.slice(0, max_idx + 1).reverse();
<del> for (var j = 0; j <= max_idx; j++)
<del> arr[j] = new_slice[j];
<del> }
<del>
<del> // then flip the max element to its place
<del> new_slice = arr.slice(0, i + 1).reverse();
<del> for (var j = 0; j <= i; j++)
<del> arr[j] = new_slice[j];
<add> for (var i = arr.length - 1; i >= 1; i--) {
<add> // find the index of the largest element not yet sorted
<add> var max_idx = 0;
<add> var max = arr[0];
<add> for (var j = 1; j <= i; j++) {
<add> if (arr[j] > max) {
<add> max = arr[j];
<add> max_idx = j;
<add> }
<ide> }
<del> return arr;
<add>
<add> if (max_idx == i) continue; // element already in place
<add>
<add> var new_slice;
<add>
<add> // flip arr max element to index 0
<add> if (max_idx > 0) {
<add> new_slice = arr.slice(0, max_idx + 1).reverse();
<add> for (var j = 0; j <= max_idx; j++) arr[j] = new_slice[j];
<add> }
<add>
<add> // then flip the max element to its place
<add> new_slice = arr.slice(0, i + 1).reverse();
<add> for (var j = 0; j <= i; j++) arr[j] = new_slice[j];
<add> }
<add> return arr;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-permutation-sort.english.md
<ide> forumTopicId: 302316
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to implement a permutation sort, which proceeds by generating the possible permutations of the input array until discovering the sorted one. The function should return the sorted array.
<ide> Pseudocode:
<ide> Pseudocode:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>permutationSort</code> should be a function.
<del> testString: assert(typeof permutationSort == 'function', '<code>permutationSort</code> should be a function.');
<add> testString: assert(typeof permutationSort == 'function');
<ide> - text: <code>permutationSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(permutationSort([25, 32, 12, 7, 20])), '<code>permutationSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(permutationSort([25, 32, 12, 7, 20])));
<ide> - text: <code>permutationSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(permutationSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>permutationSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(permutationSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>permutationSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(permutationSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>permutationSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(permutationSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>permutationSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(permutationSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>permutationSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(permutationSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>permutationSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(permutationSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>permutationSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(permutationSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>permutationSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(permutationSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>permutationSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(permutationSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function permutationSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function permutationSort(arr) {
<ide> permute(a, a.length, list);
<ide> for (var i = 0; i < list.length; i++) {
<ide> var x = list[i];
<del> if (isSorted(x))
<del> return x;
<add> if (isSorted(x)) return x;
<ide> }
<ide> return a;
<del> };
<add> }
<ide>
<ide> function permute(a, n, list) {
<ide> if (n === 1) {
<ide> function permutationSort(arr) {
<ide> swap(a, i, n - 1);
<ide> permute(a, n - 1, list);
<ide> swap(a, i, n - 1);
<del> };
<del> };
<add> }
<add> }
<ide>
<ide> function isSorted(a) {
<del> for (var i = 1; i < a.length; i++)
<del> if (a[i - 1] > a[i])
<del> return false;;
<add> for (var i = 1; i < a.length; i++) if (a[i - 1] > a[i]) return false;
<ide> return true;
<del> };
<add> }
<ide>
<ide> function swap(arr, i, j) {
<ide> var temp = arr[i];
<ide> arr[i] = arr[j];
<ide> arr[j] = temp;
<del> };
<add> }
<ide> return pSort(arr);
<ide> }
<ide> ```
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-shell-sort.english.md
<ide> forumTopicId: 302317
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to sort an array of elements using the <a href="https://en.wikipedia.org/wiki/Shell sort" target="_blank">Shell sort</a> algorithm, a diminishing increment sort. The function should return the sorted array.
<ide> The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
<ide> Empirical studies have shown a geometric increment sequence with a ratio of abou
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>shellSort</code> should be a function.
<del> testString: assert(typeof shellSort == 'function', '<code>shellSort</code> should be a function.');
<add> testString: assert(typeof shellSort == 'function');
<ide> - text: <code>shellSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(shellSort([25, 32, 12, 7, 20])), '<code>shellSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(shellSort([25, 32, 12, 7, 20])));
<ide> - text: <code>shellSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(shellSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>shellSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(shellSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>shellSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(shellSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>shellSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(shellSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>shellSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(shellSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>shellSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(shellSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>shellSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(shellSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>shellSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(shellSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>shellSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(shellSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>shellSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(shellSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function shellSort(a) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function shellSort(a) {
<del> for (var h = a.length; h > 0; h = parseInt(h / 2)) {
<del> for (var i = h; i < a.length; i++) {
<del> var k = a[i];
<del> for (var j = i; j >= h && k < a[j - h]; j -= h)
<del> a[j] = a[j - h];
<del> a[j] = k;
<del> }
<add> for (var h = a.length; h > 0; h = parseInt(h / 2)) {
<add> for (var i = h; i < a.length; i++) {
<add> var k = a[i];
<add> for (var j = i; j >= h && k < a[j - h]; j -= h) a[j] = a[j - h];
<add> a[j] = k;
<ide> }
<del> return a;
<add> }
<add> return a;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-stooge-sort.english.md
<ide> forumTopicId: 302318
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to perform <a href="https://en.wikipedia.org/wiki/Stooge sort" target="_blank">Stooge Sort</a> on an array of integers. The function should return a sorted array.
<ide> The Stooge Sort algorithm is as follows:
<ide> The Stooge Sort algorithm is as follows:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>stoogeSort</code> should be a function.
<del> testString: assert(typeof stoogeSort == 'function', '<code>stoogeSort</code> should be a function.');
<add> testString: assert(typeof stoogeSort == 'function');
<ide> - text: <code>stoogeSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(stoogeSort([25, 32, 12, 7, 20])), '<code>stoogeSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(stoogeSort([25, 32, 12, 7, 20])));
<ide> - text: <code>stoogeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(stoogeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>stoogeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(stoogeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>stoogeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(stoogeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>stoogeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(stoogeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>stoogeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(stoogeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>stoogeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(stoogeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>stoogeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(stoogeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>stoogeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(stoogeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>stoogeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(stoogeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>stoogeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(stoogeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function stoogeSort(arr) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sorting-algorithms-strand-sort.english.md
<ide> forumTopicId: 302319
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function to sort an array using the <a href="https://en.wikipedia.org/wiki/Strand sort" target="_blank">Strand sort</a>. The function should return the sorted array.
<ide> This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>strandSort</code> should be a function.
<del> testString: assert(typeof strandSort == 'function', '<code>strandSort</code> should be a function.');
<add> testString: assert(typeof strandSort == 'function');
<ide> - text: <code>strandSort([25, 32, 12, 7, 20])</code> should return an array.
<del> testString: assert(Array.isArray(strandSort([25, 32, 12, 7, 20])), '<code>strandSort([25, 32, 12, 7, 20])</code> should return an array.');
<add> testString: assert(Array.isArray(strandSort([25, 32, 12, 7, 20])));
<ide> - text: <code>strandSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
<del> testString: assert.deepEqual(strandSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32], '<code>strandSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.');
<add> testString: assert.deepEqual(strandSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
<ide> - text: <code>strandSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
<del> testString: assert.deepEqual(strandSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45], '<code>strandSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.');
<add> testString: assert.deepEqual(strandSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
<ide> - text: <code>strandSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
<del> testString: assert.deepEqual(strandSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43], '<code>strandSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.');
<add> testString: assert.deepEqual(strandSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
<ide> - text: <code>strandSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
<del> testString: assert.deepEqual(strandSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38], '<code>strandSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.');
<add> testString: assert.deepEqual(strandSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
<ide> - text: <code>strandSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
<del> testString: assert.deepEqual(strandSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48], '<code>strandSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.');
<add> testString: assert.deepEqual(strandSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function strandSort(list) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function strandSort(list) {
<del>
<ide> function merge(left, right) {
<ide> var result = [];
<ide> while (left.length != 0 && right.length != 0) {
<del> if (left[0] <= right[0])
<del> result.push(left.shift());
<del> else
<del> result.push(right.shift());
<add> if (left[0] <= right[0]) result.push(left.shift());
<add> else result.push(right.shift());
<ide> }
<ide> result.push.apply(result, left);
<ide> result.push.apply(result, right);
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/soundex.english.md
<ide> forumTopicId: 302320
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Soundex is an algorithm for creating indices for words based on their pronunciation.
<ide> The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from <a href="https://en.wikipedia.org/wiki/soundex" target="_blank">the WP article</a>).
<ide> There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the <a href="https://www.archives.gov/research/census/soundex.html" target="_blank">official Rules</a>. So check for instance if <b>Ashcraft</b> is coded to <b>A-261</b>.
<add>
<ide> <ul>
<ide> <li>If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.</li>
<ide> <li>If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.</li>
<ide> </ul>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes a string as a parameter and returns the encoded string.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>soundex</code> should be a function.
<del> testString: assert(typeof soundex == 'function', '<code>soundex</code> should be a function.');
<add> testString: assert(typeof soundex == 'function');
<ide> - text: <code>soundex("Soundex")</code> should return a string.
<del> testString: assert(typeof soundex("Soundex") == 'string', '<code>soundex("Soundex")</code> should return a string.');
<add> testString: assert(typeof soundex("Soundex") == 'string');
<ide> - text: <code>soundex("Soundex")</code> should return <code>"S532"</code>.
<del> testString: assert.equal(soundex("Soundex"), "S532", '<code>soundex("Soundex")</code> should return <code>"S532"</code>.');
<add> testString: assert.equal(soundex("Soundex"), "S532");
<ide> - text: <code>soundex("Example")</code> should return <code>"E251"</code>.
<del> testString: assert.equal(soundex("Example"), "E251", '<code>soundex("Example")</code> should return <code>"E251"</code>.');
<add> testString: assert.equal(soundex("Example"), "E251");
<ide> - text: <code>soundex("Sownteks")</code> should return <code>"S532"</code>.
<del> testString: assert.equal(soundex("Sownteks"), "S532", '<code>soundex("Sownteks")</code> should return <code>"S532"</code>.');
<add> testString: assert.equal(soundex("Sownteks"), "S532");
<ide> - text: <code>soundex("Ekzampul")</code> should return <code>"E251"</code>.
<del> testString: assert.equal(soundex("Ekzampul"), "E251", '<code>soundex("Ekzampul")</code> should return <code>"E251"</code>.');
<add> testString: assert.equal(soundex("Ekzampul"), "E251");
<ide> - text: <code>soundex("Euler")</code> should return <code>"E460"</code>.
<del> testString: assert.equal(soundex("Euler"), "E460", '<code>soundex("Euler")</code> should return <code>"E460"</code>.');
<add> testString: assert.equal(soundex("Euler"), "E460");
<ide> - text: <code>soundex("Gauss")</code> should return <code>"G200"</code>.
<del> testString: assert.equal(soundex("Gauss"), "G200", '<code>soundex("Gauss")</code> should return <code>"G200"</code>.');
<add> testString: assert.equal(soundex("Gauss"), "G200");
<ide> - text: <code>soundex("Hilbert")</code> should return <code>"H416"</code>.
<del> testString: assert.equal(soundex("Hilbert"), "H416", '<code>soundex("Hilbert")</code> should return <code>"H416"</code>.');
<add> testString: assert.equal(soundex("Hilbert"), "H416");
<ide> - text: <code>soundex("Knuth")</code> should return <code>"K530"</code>.
<del> testString: assert.equal(soundex("Knuth"), "K530", '<code>soundex("Knuth")</code> should return <code>"K530"</code>.');
<add> testString: assert.equal(soundex("Knuth"), "K530");
<ide> - text: <code>soundex("Lloyd")</code> should return <code>"L300"</code>.
<del> testString: assert.equal(soundex("Lloyd"), "L300", '<code>soundex("Lloyd")</code> should return <code>"L300"</code>.');
<add> testString: assert.equal(soundex("Lloyd"), "L300");
<ide> - text: <code>soundex("Lukasiewicz")</code> should return <code>"L222"</code>.
<del> testString: assert.equal(soundex("Lukasiewicz"), "L222", '<code>soundex("Lukasiewicz")</code> should return <code>"L222"</code>.');
<add> testString: assert.equal(soundex("Lukasiewicz"), "L222");
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function soundex(s) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function soundex(s) {
<del> var a = s.toLowerCase().split('')
<add> var a = s.toLowerCase().split('');
<ide> var f = a.shift(),
<ide> r = '',
<ide> codes = {
<del> a: '', e: '', i: '', o: '', u: '',
<del> b: 1, f: 1, p: 1, v: 1,
<del> c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2,
<del> d: 3, t: 3,
<del> l: 4,
<del> m: 5, n: 5,
<del> r: 6
<add> a: '',
<add> e: '',
<add> i: '',
<add> o: '',
<add> u: '',
<add> b: 1,
<add> f: 1,
<add> p: 1,
<add> v: 1,
<add> c: 2,
<add> g: 2,
<add> j: 2,
<add> k: 2,
<add> q: 2,
<add> s: 2,
<add> x: 2,
<add> z: 2,
<add> d: 3,
<add> t: 3,
<add> l: 4,
<add> m: 5,
<add> n: 5,
<add> r: 6
<ide> };
<del> r = f + a
<del> .map(function(v, i, a) {
<del> return codes[v]
<del> })
<del> .filter(function(v, i, a) {
<del> return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
<del> })
<del> .join('');
<add> r =
<add> f +
<add> a
<add> .map(function(v, i, a) {
<add> return codes[v];
<add> })
<add> .filter(function(v, i, a) {
<add> return i === 0 ? v !== codes[f] : v !== a[i - 1];
<add> })
<add> .join('');
<ide>
<ide> return (r + '000').slice(0, 4).toUpperCase();
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/spiral-matrix.english.md
<ide> forumTopicId: 302321
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Produce a spiral array.
<del>A <i>spiral array</i> is a square arrangement of the first N<sup>2</sup> natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
<del>For example, given <b>5</b>, produce this array:
<add>A <i>spiral array</i> is a square arrangement of the first N<sup>2</sup> natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
<add>For example, given <b>5</b>, produce this array:
<add>
<ide> <pre>
<ide> 0 1 2 3 4
<ide> 15 16 17 18 5
<ide> For example, given <b>5</b>, produce this array:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>spiralArray</code> should be a function.
<del> testString: assert(typeof spiralArray=='function','<code>spiralArray</code> should be a function.');
<add> testString: assert(typeof spiralArray=='function');
<ide> - text: <code>spiralArray(3)</code> should return an array.
<del> testString: assert(Array.isArray(spiralArray(3)), '<code>spiralArray(3)</code> should return an array.');
<add> testString: assert(Array.isArray(spiralArray(3)));
<ide> - text: <code>spiralArray(3)</code> should return <code>[[0, 1, 2],[7, 8, 3],[6, 5, 4]]</code>.
<del> testString: assert.deepEqual(spiralArray(3), [[0, 1, 2], [7, 8, 3], [6, 5, 4]], '<code>spiralArray(3)</code> should return <code>[[0, 1, 2],[7, 8, 3],[6, 5, 4]]</code>.');
<add> testString: assert.deepEqual(spiralArray(3), [[0, 1, 2], [7, 8, 3], [6, 5, 4]]);
<ide> - text: <code>spiralArray(4)</code> should return <code>[[0, 1, 2, 3],[11, 12, 13, 4],[10, 15, 14, 5],[9, 8, 7, 6]]</code>.
<del> testString: assert.deepEqual(spiralArray(4), [[0, 1, 2, 3], [11, 12, 13, 4], [10, 15, 14, 5], [9, 8, 7, 6]], '<code>spiralArray(4)</code> should return <code>[[0, 1, 2, 3],[11, 12, 13, 4],[10, 15, 14, 5],[9, 8, 7, 6]]</code>.');
<add> testString: assert.deepEqual(spiralArray(4), [[0, 1, 2, 3], [11, 12, 13, 4], [10, 15, 14, 5], [9, 8, 7, 6]]);
<ide> - text: <code>spiralArray(5)</code> should return <code>[[0, 1, 2, 3, 4],[15, 16, 17, 18, 5],[14, 23, 24, 19, 6],[13, 22, 21, 20, 7],[12, 11, 10, 9, 8]]</code>.
<del> testString: assert.deepEqual(spiralArray(5), [[0, 1, 2, 3, 4], [15, 16, 17, 18, 5], [14, 23, 24, 19, 6], [13, 22, 21, 20, 7], [12, 11, 10, 9, 8]], '<code>spiralArray(5)</code> should return <code>[[0, 1, 2, 3, 4],[15, 16, 17, 18, 5],[14, 23, 24, 19, 6],[13, 22, 21, 20, 7],[12, 11, 10, 9, 8]]</code>.');
<add> testString: assert.deepEqual(spiralArray(5), [[0, 1, 2, 3, 4], [15, 16, 17, 18, 5], [14, 23, 24, 19, 6], [13, 22, 21, 20, 7], [12, 11, 10, 9, 8]]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function spiralArray(n) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function spiralArray(n) {
<del> var arr = Array(n),
<del> x = 0, y = n,
<del> total = n * n--,
<del> dx = 1, dy = 0,
<del> i = 0, j = 0;
<del> while (y) arr[--y] = [];
<del> while (i < total) {
<del> arr[y][x] = i++;
<del> x += dx; y += dy;
<del> if (++j == n) {
<del> if (dy < 0) {x++; y++; n -= 2}
<del> j = dx; dx = -dy; dy = j; j = 0;
<del> }
<add> var arr = Array(n),
<add> x = 0,
<add> y = n,
<add> total = n * n--,
<add> dx = 1,
<add> dy = 0,
<add> i = 0,
<add> j = 0;
<add> while (y) arr[--y] = [];
<add> while (i < total) {
<add> arr[y][x] = i++;
<add> x += dx;
<add> y += dy;
<add> if (++j == n) {
<add> if (dy < 0) {
<add> x++;
<add> y++;
<add> n -= 2;
<add> }
<add> j = dx;
<add> dx = -dy;
<add> dy = j;
<add> j = 0;
<ide> }
<del> return arr;
<add> }
<add> return arr;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/split-a-character-string-based-on-change-of-character.english.md
<ide> forumTopicId: 302322
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<del>Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right).
<del>Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas.
<add>Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right).
<add>Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas.
<ide> For instance, the string:
<add>
<ide> <pre>
<ide> "gHHH5YY++///\"
<ide> </pre>
<add>
<ide> should be split as:
<add>
<ide> <pre>
<ide> ["g", "HHH", "5", "YY", "++", "///", "\" ];
<ide> </pre>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>split</code> should be a function.
<del> testString: assert(typeof split == 'function', '<code>split</code> should be a function.');
<add> testString: assert(typeof split == 'function');
<ide> - text: <code>split("hello")</code> should return an array.
<del> testString: assert(Array.isArray(split("hello")), '<code>split("hello")</code> should return an array.');
<add> testString: assert(Array.isArray(split("hello")));
<ide> - text: <code>split("hello")</code> should return <code>["h", "e", "ll", "o"]</code>.
<del> testString: assert.deepEqual(split("hello"), ["h", "e", "ll", "o"], '<code>split("hello")</code> should return <code>["h", "e", "ll", "o"]</code>.');
<add> testString: assert.deepEqual(split("hello"), ["h", "e", "ll", "o"]);
<ide> - text: <code>split("commission")</code> should return <code>["c", "o", "mm", "i", "ss", "i", "o", "n"]</code>.
<del> testString: assert.deepEqual(split("commission"), ["c", "o", "mm", "i", "ss", "i", "o", "n"], '<code>split("commission")</code> should return <code>["c", "o", "mm", "i", "ss", "i", "o", "n"]</code>.');
<add> testString: assert.deepEqual(split("commission"), ["c", "o", "mm", "i", "ss", "i", "o", "n"]);
<ide> - text: <code>split("ssss----====llloooo")</code> should return <code>["ssss", "----", "====", "lll", "oooo"]</code>.
<del> testString: assert.deepEqual(split("ssss----====llloooo"), ["ssss", "----", "====", "lll", "oooo"], '<code>split("ssss----====llloooo")</code> should return <code>["ssss", "----", "====", "lll", "oooo"]</code>.');
<add> testString: assert.deepEqual(split("ssss----====llloooo"), ["ssss", "----", "====", "lll", "oooo"]);
<ide> - text: <code>split("sssmmmaaammmaaat")</code> should return <code>["sss", "mmm", "aaa", "mmm", "aaa", "t"]</code>.
<del> testString: assert.deepEqual(split("sssmmmaaammmaaat"), ["sss", "mmm", "aaa", "mmm", "aaa", "t"], '<code>split("sssmmmaaammmaaat")</code> should return <code>["sss", "mmm", "aaa", "mmm", "aaa", "t"]</code>.');
<add> testString: assert.deepEqual(split("sssmmmaaammmaaat"), ["sss", "mmm", "aaa", "mmm", "aaa", "t"]);
<ide> - text: <code>split("gHHH5YY++///\")</code> should return <code>["g", "HHH", "5", "YY", "++", "///", "\\"]</code>.
<del> testString: assert.deepEqual(split("gHHH5YY++///\\"), ["g", "HHH", "5", "YY", "++", "///", "\\"], '<code>split("gHHH5YY++///\")</code> should return <code>["g", "HHH", "5", "YY", "++", "///", "\\"]</code>.');
<add> testString: assert.deepEqual(split("gHHH5YY++///\\"), ["g", "HHH", "5", "YY", "++", "///", "\\"]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function split(str) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function split(str) {
<ide> const concat = xs =>
<del> xs.length > 0 ? (() => {
<del> const unit = typeof xs[0] === 'string' ? '' : [];
<del> return unit.concat.apply(unit, xs);
<del> })() : [];
<add> xs.length > 0
<add> ? (() => {
<add> const unit = typeof xs[0] === 'string' ? '' : [];
<add> return unit.concat.apply(unit, xs);
<add> })()
<add> : [];
<ide>
<ide> const group = xs => groupBy((a, b) => a === b, xs);
<ide>
<ide> const groupBy = (f, xs) => {
<del> const dct = xs.slice(1)
<del> .reduce((a, x) => {
<del> const
<del> h = a.active.length > 0 ? a.active[0] : undefined,
<add> const dct = xs.slice(1).reduce(
<add> (a, x) => {
<add> const h = a.active.length > 0 ? a.active[0] : undefined,
<ide> blnGroup = h !== undefined && f(h, x);
<ide> return {
<ide> active: blnGroup ? a.active.concat([x]) : [x],
<ide> sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
<ide> };
<del> }, {
<add> },
<add> {
<ide> active: xs.length > 0 ? [xs[0]] : [],
<ide> sofar: []
<del> });
<add> }
<add> );
<ide> return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
<ide> };
<ide>
<ide> const map = (f, xs) => xs.map(f);
<ide>
<ide> const stringChars = s => s.split('');
<ide>
<del> return map(concat, group(stringChars(str)))
<add> return map(concat, group(stringChars(str)));
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/state-name-puzzle.english.md
<ide> forumTopicId: 302323
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition <a href="https://www.npr.org/templates/story/story.php?storyId=9264290" target="_blank">[1]</a> and originally attributed to David Edelheit.
<ide> The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two <i>different</i> U.S. States (so that all four state names differ from one another).
<ide> What states are these?
<del>The problem was reissued on <a href="https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle" target="_blank">the Unicon Discussion Web</a> which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to <a href="https://en.wikipedia.org/wiki/Goedel_numbering" target="_blank">Gödel numbering</a>, <a href="https://en.wikipedia.org/wiki/Equivalence_relation" target="_blank">equivalence relations</a>, and <a href="https://en.wikipedia.org/wiki/Equivalence_classes" target="_blank">equivalence classes</a>. The basic merits of these were discussed in the Unicon Discussion Web.
<add>The problem was reissued on <a href="https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle" target="_blank">the Unicon Discussion Web</a> which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to <a href="https://en.wikipedia.org/wiki/Goedel_numbering" target="_blank">Gödel numbering</a>, <a href="https://en.wikipedia.org/wiki/Equivalence_relation" target="_blank">equivalence relations</a>, and <a href="https://en.wikipedia.org/wiki/Equivalence_classes" target="_blank">equivalence classes</a>. The basic merits of these were discussed in the Unicon Discussion Web.
<ide> A second challenge in the form of a set of fictitious new states was also presented.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Write a function to solve the challenge for the given array of names of states. The function should return an array. Each element should be an object in this form: <code>{"from":[],"to":[]}</code>. The "from" array should contain the original names and the "to" array should contain the resultant names.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>solve</code> should be a function.
<del> testString: assert(typeof solve == 'function', '<code>solve</code> should be a function.');
<add> testString: assert(typeof solve == 'function');
<ide> - text: <code>solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])</code> should return an array.
<del> testString: assert(Array.isArray(solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])), '<code>solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])</code> should return an array.');
<add> testString: assert(Array.isArray(solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])));
<ide> - text: '<code>solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])</code> should return <code>[{ from: ["North Carolina ", "South Dakota"], to: ["North Dakota", "South Carolina"] }]</code>.'
<del> testString: assert.deepEqual(solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"]), [{ from:["North Carolina ", "South Dakota"], to:["North Dakota", "South Carolina"] }], '<code>solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])</code> should return <code>[{ from:["North Carolina ", "South Dakota"], to:["North Dakota", "South Carolina"] }]</code>.');
<add> testString: assert.deepEqual(solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"]), [{ from:["North Carolina ", "South Dakota"], to:["North Dakota", "South Carolina"] }]);
<ide> - text: '<code>solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"])</code> should return <code>[{ from: ["New Kory", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "New York"], to: ["Kory New", "Wen Kory"] }, { from: ["New Kory", "New York"], to: ["Kory New", "York New"] }, { from: ["New York", "Wen Kory"], to: ["New Kory", "York New"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "New Kory"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New York", "York New"], to: ["New Kory", "Wen Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "New Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "York New"] }, { from: ["Kory New", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New Kory", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New Kory"], to: ["Wen Kory", "York New"] }]</code>.'
<del> testString: assert.deepEqual(solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]), [{ from:["New Kory", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "New York"], to:["Kory New", "Wen Kory"] }, { from:["New Kory", "New York"], to:["Kory New", "York New"] }, { from:["New York", "Wen Kory"], to:["New Kory", "York New"] }, { from:["New York", "Wen Kory"], to:["Kory New", "New Kory"] }, { from:["New York", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New York", "York New"], to:["New Kory", "Wen Kory"] }, { from:["New York", "York New"], to:["Kory New", "New Kory"] }, { from:["New York", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "York New"] }, { from:["Kory New", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New Kory", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New Kory"], to:["Wen Kory", "York New"] }], '<code>solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"])</code> should return <code>[{ from:["New Kory", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "New York"], to:["Kory New", "Wen Kory"] }, { from:["New Kory", "New York"], to:["Kory New", "York New"] }, { from:["New York", "Wen Kory"], to:["New Kory", "York New"] }, { from:["New York", "Wen Kory"], to:["Kory New", "New Kory"] }, { from:["New York", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New York", "York New"], to:["New Kory", "Wen Kory"] }, { from:["New York", "York New"], to:["Kory New", "New Kory"] }, { from:["New York", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "York New"] }, { from:["Kory New", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New Kory", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New Kory"], to:["Wen Kory", "York New"] }]</code>.');
<add> testString: assert.deepEqual(solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]), [{ from:["New Kory", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "New York"], to:["Kory New", "Wen Kory"] }, { from:["New Kory", "New York"], to:["Kory New", "York New"] }, { from:["New York", "Wen Kory"], to:["New Kory", "York New"] }, { from:["New York", "Wen Kory"], to:["Kory New", "New Kory"] }, { from:["New York", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New York", "York New"], to:["New Kory", "Wen Kory"] }, { from:["New York", "York New"], to:["Kory New", "New Kory"] }, { from:["New York", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "Wen Kory"] }, { from:["Kory New", "New York"], to:["New Kory", "York New"] }, { from:["Kory New", "New York"], to:["Wen Kory", "York New"] }, { from:["New Kory", "Wen Kory"], to:["Kory New", "York New"] }, { from:["New Kory", "York New"], to:["Kory New", "Wen Kory"] }, { from:["Kory New", "New Kory"], to:["Wen Kory", "York New"] }]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function solve(input) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function solve(input) {
<ide> var orig = {};
<ide> input.forEach(function(e) {
<del> orig[e.replace(/\s/g, "").toLowerCase()] = e;
<del> })
<add> orig[e.replace(/\s/g, '').toLowerCase()] = e;
<add> });
<ide>
<del> input = Object.keys(orig)
<add> input = Object.keys(orig);
<ide> var map = {};
<ide> for (var i = 0; i < input.length - 1; i++) {
<ide> var pair0 = input[i];
<ide> for (var j = i + 1; j < input.length; j++) {
<del>
<ide> var pair = [pair0, input[j]];
<ide> var s = pair0 + pair[1];
<del> var key = s.split("").sort();
<add> var key = s.split('').sort();
<ide>
<ide> var val = map[key] ? map[key] : [];
<ide> val.push(pair);
<ide> function solve(input) {
<ide> }
<ide>
<ide> var result = [];
<del> Object.keys(map).forEach((key) => {
<del>
<add> Object.keys(map).forEach(key => {
<ide> for (var i = 0; i < map[key].length - 1; i++) {
<ide> var a = map[key][i];
<ide> for (var j = i + 1; j < map[key].length; j++) {
<ide> var b = map[key][j];
<ide>
<del> if ((new Set([a[0], b[0], a[1], b[1]])).size < 4)
<del> continue;
<del> var from = [orig[a[0]], orig[a[1]]].sort()
<del> var to = [orig[b[0]], orig[b[1]]].sort()
<add> if (new Set([a[0], b[0], a[1], b[1]]).size < 4) continue;
<add> var from = [orig[a[0]], orig[a[1]]].sort();
<add> var to = [orig[b[0]], orig[b[1]]].sort();
<ide> result.push({
<ide> from,
<ide> to
<del> })
<add> });
<ide> }
<ide> }
<ide> });
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/stern-brocot-sequence.english.md
<ide> forumTopicId: 302324
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the <a href="https://rosettacode.org/wiki/Fibonacci sequence" target="_blank">Fibonacci sequence</a>.
<ide> <ol>
<ide> For this task, the Stern-Brocot sequence is to be generated by an algorithm simi
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Create a function that returns the $ n^{th} $ member of the sequence using the method outlined above.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sternBrocot</code> should be a function.
<del> testString: assert(typeof sternBrocot == 'function', '<code>sternBrocot</code> should be a function.');
<add> testString: assert(typeof sternBrocot == 'function');
<ide> - text: <code>sternBrocot(2)</code> should return a number.
<del> testString: assert(typeof sternBrocot(2) == 'number', '<code>sternBrocot(2)</code> should return a number.');
<add> testString: assert(typeof sternBrocot(2) == 'number');
<ide> - text: <code>sternBrocot(2)</code> should return <code>3</code>.
<del> testString: assert.equal(sternBrocot(2), 3, '<code>sternBrocot(2)</code> should return <code>3</code>.');
<add> testString: assert.equal(sternBrocot(2), 3);
<ide> - text: <code>sternBrocot(3)</code> should return <code>5</code>.
<del> testString: assert.equal(sternBrocot(3), 5, '<code>sternBrocot(3)</code> should return <code>5</code>.');
<add> testString: assert.equal(sternBrocot(3), 5);
<ide> - text: <code>sternBrocot(5)</code> should return <code>11</code>.
<del> testString: assert.equal(sternBrocot(5), 11, '<code>sternBrocot(5)</code> should return <code>11</code>.');
<add> testString: assert.equal(sternBrocot(5), 11);
<ide> - text: <code>sternBrocot(7)</code> should return <code>19</code>.
<del> testString: assert.equal(sternBrocot(7), 19, '<code>sternBrocot(7)</code> should return <code>19</code>.');
<add> testString: assert.equal(sternBrocot(7), 19);
<ide> - text: <code>sternBrocot(10)</code> should return <code>39</code>.
<del> testString: assert.equal(sternBrocot(10), 39, '<code>sternBrocot(10)</code> should return <code>39</code>.');
<add> testString: assert.equal(sternBrocot(10), 39);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function sternBrocot(num) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function sternBrocot(num) {
<ide> function f(n) {
<del> return n < 2 ? n : (n & 1) ? f(Math.floor(n / 2)) + f(Math.floor(n / 2 + 1)) : f(Math.floor(n / 2));
<add> return n < 2
<add> ? n
<add> : n & 1
<add> ? f(Math.floor(n / 2)) + f(Math.floor(n / 2 + 1))
<add> : f(Math.floor(n / 2));
<ide> }
<ide>
<ide> function gcd(a, b) {
<del> return a ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b;
<add> return a ? (a < b ? gcd(b % a, a) : gcd(a % b, b)) : b;
<ide> }
<ide> var n;
<ide> for (n = 1; f(n) != num; n++);
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/straddling-checkerboard.english.md
<ide> forumTopicId: 302325
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Implement functions to encrypt and decrypt a message using the <a href="https://en.wikipedia.org/wiki/Straddling_checkerboard">straddling checkerboard</a> method. The functions will take a string and an array as parameters. The array has 3 strings representing the 3 rows of the checkerboard. The output will be a series of decimal digits.
<ide> Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>straddle</code> should be a function.
<del> testString: assert(typeof straddle == 'function', '<code>straddle</code> should be a function.');
<add> testString: assert(typeof straddle == 'function');
<ide> - text: <code>straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return a string.
<del> testString: assert(typeof straddle("One night-it was on the twentieth of March, 1888-I was returning.", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]) == 'string', '<code>straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return a string.');
<add> testString: assert(typeof straddle("One night-it was on the twentieth of March, 1888-I was returning.", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]) == 'string');
<ide> - text: <code>straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return <code>"34045747525284613427502840425027537379697175891898898898584619028294547488"</code>.
<del> testString: assert.equal(straddle("One night-it was on the twentieth of March, 1888-I was returning.", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]), "34045747525284613427502840425027537379697175891898898898584619028294547488", '<code>straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return <code>"34045747525284613427502840425027537379697175891898898898584619028294547488"</code>.');
<add> testString: assert.equal(straddle("One night-it was on the twentieth of March, 1888-I was returning.", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]), "34045747525284613427502840425027537379697175891898898898584619028294547488");
<ide> - text: <code>straddle("One night-it was on the twentieth of March, 1888-I was returning",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])</code> should return <code>"139539363509369743061399059745399365901344308320791798798798367430685972839363935"</code>.
<del> testString: assert.equal(straddle("One night-it was on the twentieth of March, 1888-I was returning", ["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"]), "139539363509369743061399059745399365901344308320791798798798367430685972839363935", '<code>straddle("One night-it was on the twentieth of March, 1888-I was returning",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])</code> should return <code>"139539363509369743061399059745399365901344308320791798798798367430685972839363935"</code>.');
<add> testString: assert.equal(straddle("One night-it was on the twentieth of March, 1888-I was returning", ["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"]), "139539363509369743061399059745399365901344308320791798798798367430685972839363935");
<ide> - text: <code>straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])</code> should return <code>"125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769"</code>.
<del> testString: assert.equal(straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.", ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."]), "125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769", '<code>straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])</code> should return <code>"125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769"</code>.');
<add> testString: assert.equal(straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.", ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."]), "125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769");
<ide> - text: <code>unstraddle</code> should be a function.
<del> testString: assert(typeof unstraddle == 'function', '<code>unstraddle</code> should be a function.');
<add> testString: assert(typeof unstraddle == 'function');
<ide> - text: <code>unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return a string.
<del> testString: assert(typeof unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]) == 'string', '<code>unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return a string.');
<add> testString: assert(typeof unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]) == 'string');
<ide> - text: <code>unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return <code>"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING."</code>.
<del> testString: assert.equal(unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]), "ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING.", '<code>unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])</code> should return <code>"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING."</code>.');
<add> testString: assert.equal(unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488", ["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"]), "ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING.");
<ide> - text: <code>unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])</code> should return <code>"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING"</code>.
<del> testString: assert.equal(unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935", ["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"]), "ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING", '<code>unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])</code> should return <code>"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING"</code>.');
<add> testString: assert.equal(unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935", ["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"]), "ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING");
<ide> - text: <code>unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])</code> should return <code>"THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR."</code>.
<del> testString: assert.equal(unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769", ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."]), "THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR.", '<code>unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])</code> should return <code>"THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR."</code>.');
<add> testString: assert.equal(unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769", ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."]), "THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR.");
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function unstraddle(message, alphabet) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function straddle(message, alphabet) {
<del> var prefixes = new Array("", alphabet[0].indexOf(" "), alphabet[0].lastIndexOf(" "))
<del>
<del> var out = ""
<del> message = message.toUpperCase()
<del> message = message.replace(/([0-9])/g, "/$1") // dumb way to escape numbers
<add> var prefixes = new Array(
<add> '',
<add> alphabet[0].indexOf(' '),
<add> alphabet[0].lastIndexOf(' ')
<add> );
<add>
<add> var out = '';
<add> message = message.toUpperCase();
<add> message = message.replace(/([0-9])/g, '/$1'); // dumb way to escape numbers
<ide> for (var i = 0; i < message.length; i++) {
<del> var chr = message[i]
<del> if (chr == " ") continue
<add> var chr = message[i];
<add> if (chr == ' ') continue;
<ide> for (var j = 0; j < 3; j++) {
<del> var k = alphabet[j].indexOf(chr)
<del> if (k < 0) continue
<del> out += prefixes[j].toString() + k
<add> var k = alphabet[j].indexOf(chr);
<add> if (k < 0) continue;
<add> out += prefixes[j].toString() + k;
<ide> }
<del> if (chr == "/") out += message[++i]
<add> if (chr == '/') out += message[++i];
<ide> }
<del> return out
<add> return out;
<ide> }
<ide> function unstraddle(message, alphabet) {
<del> var prefixes = new Array("", alphabet[0].indexOf(" "), alphabet[0].lastIndexOf(" "))
<del> var out = ""
<del> var n, o
<add> var prefixes = new Array(
<add> '',
<add> alphabet[0].indexOf(' '),
<add> alphabet[0].lastIndexOf(' ')
<add> );
<add> var out = '';
<add> var n, o;
<ide> for (var i = 0; i < message.length; i++) {
<del> n = message[i] * 1
<add> n = message[i] * 1;
<ide> switch (n) {
<ide> case prefixes[1]:
<ide> o = alphabet[1][message[++i]];
<del> break
<add> break;
<ide> case prefixes[2]:
<ide> o = alphabet[2][message[++i]];
<del> break
<add> break;
<ide> default:
<del> o = alphabet[0][n]
<add> o = alphabet[0][n];
<ide> }
<del> o == "/" ? out += message[++i] : out += o
<add> o == '/' ? (out += message[++i]) : (out += o);
<ide> }
<del> return out
<add> return out;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/stream-merge.english.md
<ide> forumTopicId: 302326
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Write a function that takes multiple sorted arrays of items, and returns one array of sorted items.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>mergeLists</code> should be a function.
<del> testString: assert(typeof mergeLists == 'function', '<code>mergeLists</code> should be a function.');
<add> testString: assert(typeof mergeLists == 'function');
<ide> - text: <code>mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])</code> should return an array.
<del> testString: assert(Array.isArray(mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])), '<code>mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])</code> should return an array.');
<add> testString: assert(Array.isArray(mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])));
<ide> - text: <code>mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])</code> should return <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code>.
<del> testString: assert.deepEqual(mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], '<code>mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])</code> should return <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code>.');
<add> testString: assert.deepEqual(mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
<ide> - text: <code>mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])</code> should return <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]</code>.
<del> testString: assert.deepEqual(mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], '<code>mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])</code> should return <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]</code>.');
<add> testString: assert.deepEqual(mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
<ide> - text: <code>mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]])</code> should return <code>[1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30]</code>.
<del> testString: assert.deepEqual(mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]]), [1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30], '<code>mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]])</code> should return <code>[1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30]</code>.');
<add> testString: assert.deepEqual(mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]]), [1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30]);
<ide> - text: <code>mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]])</code> should return <code>[2, 2, 3, 3, 5, 7, 14, 15, 17, 18]</code>.
<del> testString: assert.deepEqual(mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]]), [2, 2, 3, 3, 5, 7, 14, 15, 17, 18], '<code>mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]])</code> should return <code>[2, 2, 3, 3, 5, 7, 14, 15, 17, 18]</code>.');
<add> testString: assert.deepEqual(mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]]), [2, 2, 3, 3, 5, 7, 14, 15, 17, 18]);
<ide> - text: <code>mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]])</code> should return <code>[1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999]</code>.
<del> testString: assert.deepEqual(mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]]), [1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999], '<code>mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]])</code> should return <code>[1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999]</code>.');
<add> testString: assert.deepEqual(mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]]), [1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function mergeLists(lists) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function mergeLists(lists) {
<del> function merge (l1, l2) {
<del> var result = [], i=0, j=0;
<add> function merge(l1, l2) {
<add> var result = [],
<add> i = 0,
<add> j = 0;
<ide> while (l1.length && l2.length) {
<del> if(l1[i]<=l2[j]){
<add> if (l1[i] <= l2[j]) {
<ide> result.push(l1.shift());
<del> }else{
<add> } else {
<ide> result.push(l2.shift());
<ide> }
<ide> }
<ide> function mergeLists(lists) {
<ide> return result;
<ide> }
<ide>
<del> var result=lists[0];
<add> var result = lists[0];
<ide> for (var i = 1; i < lists.length; i++) {
<del> result=merge(result, lists[i]);
<add> result = merge(result, lists[i]);
<ide> }
<ide>
<ide> return result;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/strip-control-codes-and-extended-characters-from-a-string.english.md
<ide> forumTopicId: 302327
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> The task is to strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:
<ide> A string with control codes and extended characters stripped.
<ide> In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
<ide> On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>strip</code> should be a function.
<ide> testString: assert(typeof strip == 'function');
<ide> tests:
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function strip(s) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function strip(s) {
<del> return s.split('').filter(function(x) {
<del> var n = x.charCodeAt(0);
<add> return s
<add> .split('')
<add> .filter(function(x) {
<add> var n = x.charCodeAt(0);
<ide>
<del> return 31 < n && 127 > n;
<del> }).join('');
<add> return 31 < n && 127 > n;
<add> })
<add> .join('');
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/subleq.english.md
<ide> forumTopicId: 302328
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> <a href="https://rosettacode.org/wiki/eso:Subleq" target="_blank">Subleq</a> is an example of a <a href="https://en.wikipedia.org/wiki/One_instruction_set_computer" target="_blank">One-Instruction Set Computer (OISC)</a>.
<ide> It is named after its only instruction, which is <b>SU</b>btract and <b>B</b>ranch if <b>L</b>ess than or <b>EQ</b>ual
<ide> message: "Hello, world!\n\0"
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes an array of integers as a parameter. This represents the memory elements. The function
<ide> should interpret the sequence and return the output string. For this task, assume that there is no standard input.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>Subleq</code> should be a function.
<del> testString: assert(typeof Subleq == 'function', '<code>Subleq</code> should be a function.');
<add> testString: assert(typeof Subleq == 'function');
<ide> - text: <code>Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])</code> should return a string.
<del> testString: assert(typeof Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0]) == 'string', '<code>Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])</code> should return a string.');
<add> testString: assert(typeof Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0]) == 'string');
<ide> - text: <code>Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])</code> should return <code>"Hello, world!"</code>.
<del> testString: assert.equal(Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0]), "Hello, world!", '<code>Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])</code> should return <code>"Hello, world!"</code>.');
<add> testString: assert.equal(Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0]), "Hello, world!");
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function Subleq(mem) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function Subleq(mem) {
<del> var out = "";
<add> var out = '';
<ide> var instructionPointer = 0;
<ide> do {
<ide> var a = mem[instructionPointer];
<ide> var b = mem[instructionPointer + 1];
<del> if (a === -1) {} else if (b === -1) {
<add> if (a === -1) {
<add> } else if (b === -1) {
<ide> out += String.fromCharCode(mem[a]);
<ide> } else {
<ide> mem[b] -= mem[a];
<ide> function Subleq(mem) {
<ide> }
<ide> }
<ide> instructionPointer += 3;
<del> } while ((instructionPointer >= 0));
<add> } while (instructionPointer >= 0);
<ide>
<ide> return out;
<ide> }
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sudoku.english.md
<ide> forumTopicId: 302329
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Write a function to solve a partially filled-in normal 9x9 <a href="https://en.wikipedia.org/wiki/Sudoku" target="_blank">Sudoku</a> grid and return the result. The blank fields are represented by 0s.
<ide> <a href="https://en.wikipedia.org/wiki/Algorithmics_of_sudoku" target="_blank">Algorithmics of Sudoku</a> may help implement this.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>solveSudoku</code> should be a function.
<del> testString: assert(typeof solveSudoku == 'function', '<code>solveSudoku</code> should be a function.');
<add> testString: assert(typeof solveSudoku == 'function');
<ide> - text: <code>solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])</code> should return an array.
<del> testString: assert(Array.isArray(solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1], [-1, -1, 2, -1, -1, -1, 7, 5, -1], [-1, 3, 7, 1, -1, 4, -1, 6, -1], [4, -1, -1, 5, 9, -1, 1, -1, -1], [7, -1, -1, 3, -1, 8, -1, -1, 2], [-1, -1, 3, -1, 6, 2, -1, -1, 7], [-1, 5, -1, 7, -1, 9, 2, 1, -1], [-1, 6, 4, -1, -1, -1, 9, -1, -1], [-1, -1, -1, 2, -1, -1, 4, 3, 8]])), '<code>solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])</code> should return an array.');
<add> testString: assert(Array.isArray(solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1], [-1, -1, 2, -1, -1, -1, 7, 5, -1], [-1, 3, 7, 1, -1, 4, -1, 6, -1], [4, -1, -1, 5, 9, -1, 1, -1, -1], [7, -1, -1, 3, -1, 8, -1, -1, 2], [-1, -1, 3, -1, 6, 2, -1, -1, 7], [-1, 5, -1, 7, -1, 9, 2, 1, -1], [-1, 6, 4, -1, -1, -1, 9, -1, -1], [-1, -1, -1, 2, -1, -1, 4, 3, 8]])));
<ide> - text: <code>solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])</code> should return <code>[[8, 1, 9, 6, 7, 5, 3, 2, 4],[6, 4, 2, 9, 8, 3, 7, 5, 1],[5, 3, 7, 1, 2, 4, 8, 6, 9],[4, 2, 6, 5, 9, 7, 1, 8, 3],[7, 9, 5, 3, 1, 8, 6, 4, 2],[1, 8, 3, 4, 6, 2, 5, 9, 7],[3, 5, 8, 7, 4, 9, 2, 1, 6],[2, 6, 4, 8, 3, 1, 9, 7, 5],[9, 7, 1, 2, 5, 6, 4, 3, 8]]</code>.
<del> testString: assert.deepEqual(solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1], [-1, -1, 2, -1, -1, -1, 7, 5, -1], [-1, 3, 7, 1, -1, 4, -1, 6, -1], [4, -1, -1, 5, 9, -1, 1, -1, -1], [7, -1, -1, 3, -1, 8, -1, -1, 2], [-1, -1, 3, -1, 6, 2, -1, -1, 7], [-1, 5, -1, 7, -1, 9, 2, 1, -1], [-1, 6, 4, -1, -1, -1, 9, -1, -1], [-1, -1, -1, 2, -1, -1, 4, 3, 8]]), [[8, 1, 9, 6, 7, 5, 3, 2, 4], [6, 4, 2, 9, 8, 3, 7, 5, 1], [5, 3, 7, 1, 2, 4, 8, 6, 9], [4, 2, 6, 5, 9, 7, 1, 8, 3], [7, 9, 5, 3, 1, 8, 6, 4, 2], [1, 8, 3, 4, 6, 2, 5, 9, 7], [3, 5, 8, 7, 4, 9, 2, 1, 6], [2, 6, 4, 8, 3, 1, 9, 7, 5], [9, 7, 1, 2, 5, 6, 4, 3, 8]], '<code>solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])</code> should return <code>[[8, 1, 9, 6, 7, 5, 3, 2, 4],[6, 4, 2, 9, 8, 3, 7, 5, 1],[5, 3, 7, 1, 2, 4, 8, 6, 9],[4, 2, 6, 5, 9, 7, 1, 8, 3],[7, 9, 5, 3, 1, 8, 6, 4, 2],[1, 8, 3, 4, 6, 2, 5, 9, 7],[3, 5, 8, 7, 4, 9, 2, 1, 6],[2, 6, 4, 8, 3, 1, 9, 7, 5],[9, 7, 1, 2, 5, 6, 4, 3, 8]]</code>.');
<add> testString: assert.deepEqual(solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1], [-1, -1, 2, -1, -1, -1, 7, 5, -1], [-1, 3, 7, 1, -1, 4, -1, 6, -1], [4, -1, -1, 5, 9, -1, 1, -1, -1], [7, -1, -1, 3, -1, 8, -1, -1, 2], [-1, -1, 3, -1, 6, 2, -1, -1, 7], [-1, 5, -1, 7, -1, 9, 2, 1, -1], [-1, 6, 4, -1, -1, -1, 9, -1, -1], [-1, -1, -1, 2, -1, -1, 4, 3, 8]]), [[8, 1, 9, 6, 7, 5, 3, 2, 4], [6, 4, 2, 9, 8, 3, 7, 5, 1], [5, 3, 7, 1, 2, 4, 8, 6, 9], [4, 2, 6, 5, 9, 7, 1, 8, 3], [7, 9, 5, 3, 1, 8, 6, 4, 2], [1, 8, 3, 4, 6, 2, 5, 9, 7], [3, 5, 8, 7, 4, 9, 2, 1, 6], [2, 6, 4, 8, 3, 1, 9, 7, 5], [9, 7, 1, 2, 5, 6, 4, 3, 8]]);
<ide> - text: <code>solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1],[-1, -1, 2, -1, -1, -1, 8, -1, -1],[1, -1, -1, 7, -1, 3, 9, -1, 2],[-1, -1, 8, -1, 7, 2, -1, 4, 9],[-1, 2, -1, 9, 8, -1, -1, 7, -1],[7, 9, -1, -1, -1, -1, -1, 8, -1],[-1, -1, -1, -1, 3, -1, 5, -1, 6],[9, 6, -1, -1, 1, -1, 3, -1, -1],[-1, 5, -1, 6, 9, -1, -1, 1, -1]])</code> should return <code>[[5, 3, 9, 8, 2, 4, 7, 6, 1],[6, 7, 2, 1, 5, 9, 8, 3, 4],[1, 8, 4, 7, 6, 3, 9, 5, 2],[3, 1, 8, 5, 7, 2, 6, 4, 9],[4, 2, 5, 9, 8, 6, 1, 7, 3],[7, 9, 6, 3, 4, 1, 2, 8, 5],[8, 4, 1, 2, 3, 7, 5, 9, 6],[9, 6, 7, 4, 1, 5, 3, 2, 8],[2, 5, 3, 6, 9, 8, 4, 1, 7]]</code>.
<del> testString: assert.deepEqual(solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1], [-1, -1, 2, -1, -1, -1, 8, -1, -1], [1, -1, -1, 7, -1, 3, 9, -1, 2], [-1, -1, 8, -1, 7, 2, -1, 4, 9], [-1, 2, -1, 9, 8, -1, -1, 7, -1], [7, 9, -1, -1, -1, -1, -1, 8, -1], [-1, -1, -1, -1, 3, -1, 5, -1, 6], [9, 6, -1, -1, 1, -1, 3, -1, -1], [-1, 5, -1, 6, 9, -1, -1, 1, -1]]), [[5, 3, 9, 8, 2, 4, 7, 6, 1], [6, 7, 2, 1, 5, 9, 8, 3, 4], [1, 8, 4, 7, 6, 3, 9, 5, 2], [3, 1, 8, 5, 7, 2, 6, 4, 9], [4, 2, 5, 9, 8, 6, 1, 7, 3], [7, 9, 6, 3, 4, 1, 2, 8, 5], [8, 4, 1, 2, 3, 7, 5, 9, 6], [9, 6, 7, 4, 1, 5, 3, 2, 8], [2, 5, 3, 6, 9, 8, 4, 1, 7]], '<code>solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1],[-1, -1, 2, -1, -1, -1, 8, -1, -1],[1, -1, -1, 7, -1, 3, 9, -1, 2],[-1, -1, 8, -1, 7, 2, -1, 4, 9],[-1, 2, -1, 9, 8, -1, -1, 7, -1],[7, 9, -1, -1, -1, -1, -1, 8, -1],[-1, -1, -1, -1, 3, -1, 5, -1, 6],[9, 6, -1, -1, 1, -1, 3, -1, -1],[-1, 5, -1, 6, 9, -1, -1, 1, -1]])</code> should return <code>[[5, 3, 9, 8, 2, 4, 7, 6, 1],[6, 7, 2, 1, 5, 9, 8, 3, 4],[1, 8, 4, 7, 6, 3, 9, 5, 2],[3, 1, 8, 5, 7, 2, 6, 4, 9],[4, 2, 5, 9, 8, 6, 1, 7, 3],[7, 9, 6, 3, 4, 1, 2, 8, 5],[8, 4, 1, 2, 3, 7, 5, 9, 6],[9, 6, 7, 4, 1, 5, 3, 2, 8],[2, 5, 3, 6, 9, 8, 4, 1, 7]]</code>.');
<add> testString: assert.deepEqual(solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1], [-1, -1, 2, -1, -1, -1, 8, -1, -1], [1, -1, -1, 7, -1, 3, 9, -1, 2], [-1, -1, 8, -1, 7, 2, -1, 4, 9], [-1, 2, -1, 9, 8, -1, -1, 7, -1], [7, 9, -1, -1, -1, -1, -1, 8, -1], [-1, -1, -1, -1, 3, -1, 5, -1, 6], [9, 6, -1, -1, 1, -1, 3, -1, -1], [-1, 5, -1, 6, 9, -1, -1, 1, -1]]), [[5, 3, 9, 8, 2, 4, 7, 6, 1], [6, 7, 2, 1, 5, 9, 8, 3, 4], [1, 8, 4, 7, 6, 3, 9, 5, 2], [3, 1, 8, 5, 7, 2, 6, 4, 9], [4, 2, 5, 9, 8, 6, 1, 7, 3], [7, 9, 6, 3, 4, 1, 2, 8, 5], [8, 4, 1, 2, 3, 7, 5, 9, 6], [9, 6, 7, 4, 1, 5, 3, 2, 8], [2, 5, 3, 6, 9, 8, 4, 1, 7]]);
<ide> - text: <code>solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1],[9, -1, -1, 3, -1, 5, -1, -1, 1],[-1, -1, 1, 8, -1, 6, 4, -1, -1],[-1, -1, 8, 1, -1, 2, 9, -1, -1],[7, -1, -1, -1, -1, -1, -1, -1, 8],[-1, -1, 6, 7, -1, 8, 2, -1, -1],[-1, -1, 2, 6, -1, 9, 5, -1, -1],[8, -1, -1, 2, -1, 3, -1, -1, 9],[-1, -1, 5, -1, 1, -1, 3, -1, -1]])</code> should return <code>[[4, 8, 3, 9, 2, 1, 6, 5, 7],[9, 6, 7, 3, 4, 5, 8, 2, 1],[2, 5, 1, 8, 7, 6, 4, 9, 3],[5, 4, 8, 1, 3, 2, 9, 7, 6],[7, 2, 9, 5, 6, 4, 1, 3, 8],[1, 3, 6, 7, 9, 8, 2, 4, 5],[3, 7, 2, 6, 8, 9, 5, 1, 4],[8, 1, 4, 2, 5, 3, 7, 6, 9],[6, 9, 5, 4, 1, 7, 3, 8, 2]]</code>.
<del> testString: assert.deepEqual(solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1], [9, -1, -1, 3, -1, 5, -1, -1, 1], [-1, -1, 1, 8, -1, 6, 4, -1, -1], [-1, -1, 8, 1, -1, 2, 9, -1, -1], [7, -1, -1, -1, -1, -1, -1, -1, 8], [-1, -1, 6, 7, -1, 8, 2, -1, -1], [-1, -1, 2, 6, -1, 9, 5, -1, -1], [8, -1, -1, 2, -1, 3, -1, -1, 9], [-1, -1, 5, -1, 1, -1, 3, -1, -1]]), [[4, 8, 3, 9, 2, 1, 6, 5, 7], [9, 6, 7, 3, 4, 5, 8, 2, 1], [2, 5, 1, 8, 7, 6, 4, 9, 3], [5, 4, 8, 1, 3, 2, 9, 7, 6], [7, 2, 9, 5, 6, 4, 1, 3, 8], [1, 3, 6, 7, 9, 8, 2, 4, 5], [3, 7, 2, 6, 8, 9, 5, 1, 4], [8, 1, 4, 2, 5, 3, 7, 6, 9], [6, 9, 5, 4, 1, 7, 3, 8, 2]], '<code>solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1],[9, -1, -1, 3, -1, 5, -1, -1, 1],[-1, -1, 1, 8, -1, 6, 4, -1, -1],[-1, -1, 8, 1, -1, 2, 9, -1, -1],[7, -1, -1, -1, -1, -1, -1, -1, 8],[-1, -1, 6, 7, -1, 8, 2, -1, -1],[-1, -1, 2, 6, -1, 9, 5, -1, -1],[8, -1, -1, 2, -1, 3, -1, -1, 9],[-1, -1, 5, -1, 1, -1, 3, -1, -1]])</code> should return <code>[[4, 8, 3, 9, 2, 1, 6, 5, 7],[9, 6, 7, 3, 4, 5, 8, 2, 1],[2, 5, 1, 8, 7, 6, 4, 9, 3],[5, 4, 8, 1, 3, 2, 9, 7, 6],[7, 2, 9, 5, 6, 4, 1, 3, 8],[1, 3, 6, 7, 9, 8, 2, 4, 5],[3, 7, 2, 6, 8, 9, 5, 1, 4],[8, 1, 4, 2, 5, 3, 7, 6, 9],[6, 9, 5, 4, 1, 7, 3, 8, 2]]</code>.');
<add> testString: assert.deepEqual(solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1], [9, -1, -1, 3, -1, 5, -1, -1, 1], [-1, -1, 1, 8, -1, 6, 4, -1, -1], [-1, -1, 8, 1, -1, 2, 9, -1, -1], [7, -1, -1, -1, -1, -1, -1, -1, 8], [-1, -1, 6, 7, -1, 8, 2, -1, -1], [-1, -1, 2, 6, -1, 9, 5, -1, -1], [8, -1, -1, 2, -1, 3, -1, -1, 9], [-1, -1, 5, -1, 1, -1, 3, -1, -1]]), [[4, 8, 3, 9, 2, 1, 6, 5, 7], [9, 6, 7, 3, 4, 5, 8, 2, 1], [2, 5, 1, 8, 7, 6, 4, 9, 3], [5, 4, 8, 1, 3, 2, 9, 7, 6], [7, 2, 9, 5, 6, 4, 1, 3, 8], [1, 3, 6, 7, 9, 8, 2, 4, 5], [3, 7, 2, 6, 8, 9, 5, 1, 4], [8, 1, 4, 2, 5, 3, 7, 6, 9], [6, 9, 5, 4, 1, 7, 3, 8, 2]]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function solveSudoku(puzzle) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function solveSudoku(puzzle) {
<ide> n.R = e.R;
<ide> n.L = e;
<ide> e.R.L = n;
<del> return e.R = n;
<add> return (e.R = n);
<ide> };
<ide>
<ide> const addBelow = (e, n) => {
<ide> n.D = e.D;
<ide> n.U = e;
<ide> e.D.U = n;
<del> return e.D = n;
<add> return (e.D = n);
<ide> };
<ide>
<ide> const search = function(h, s) {
<ide> function solveSudoku(puzzle) {
<ide> const cellCount = g.length;
<ide> const tokenCount = Math.sqrt(cellCount);
<ide> const N = Math.sqrt(tokenCount);
<del> const g2D = g.map(e => isNaN(e * 1) ?
<del> new Array(tokenCount).fill(1).map((_, i) => i + 1) : [e * 1]);
<add> const g2D = g.map(e =>
<add> isNaN(e * 1)
<add> ? new Array(tokenCount).fill(1).map((_, i) => i + 1)
<add> : [e * 1]
<add> );
<ide> return [cellCount, N, tokenCount, g2D];
<ide> };
<ide>
<ide> function solveSudoku(puzzle) {
<ide> };
<ide>
<ide> const reduceGrid = puzString => {
<del>
<ide> const [
<ide> numCells, // The total number of cells in a grid (81 for a 9x9 grid)
<ide> N, // the 'n' value of the grid. (3 for a 9x9 grid)
<ide> function solveSudoku(puzzle) {
<ide>
<ide> // The 4 columns that we will populate.
<ide> const A = headRow[i];
<del> const B = headRow[numCells + candIdx + (ri * U)];
<del> const C = headRow[(numCells * 2) + candIdx + (ci * U)];
<del> const D = headRow[(numCells * 3) + candIdx + (bi * U)];
<add> const B = headRow[numCells + candIdx + ri * U];
<add> const C = headRow[numCells * 2 + candIdx + ci * U];
<add> const D = headRow[numCells * 3 + candIdx + bi * U];
<ide>
<ide> // The Row-Column Constraint
<ide> let rcc = addBelow(A.U, new DoX(id, A));
<ide> function solveSudoku(puzzle) {
<ide> search(H, []);
<ide> };
<ide>
<del> var stringPuzzle = "";
<add> var stringPuzzle = '';
<ide>
<ide> for (var i = 0; i < puzzle.length; i++) {
<ide> puzzle[i].forEach(function(e) {
<del> if (e == -1)
<del> stringPuzzle += ".";
<del> else
<del> stringPuzzle += e;
<del> })
<add> if (e == -1) stringPuzzle += '.';
<add> else stringPuzzle += e;
<add> });
<ide> }
<ide>
<del> reduceGrid(stringPuzzle)
<add> reduceGrid(stringPuzzle);
<ide>
<ide> var result = [];
<ide>
<ide> for (var i = 0; i < 9; i++) {
<del> result.push(solution.slice(i * 9, (i + 1) * 9).map(e => parseInt(e)))
<add> result.push(solution.slice(i * 9, (i + 1) * 9).map(e => parseInt(e)));
<ide> }
<ide>
<ide> return result;
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sum-digits-of-an-integer.english.md
<ide> forumTopicId: 302331
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Write a function that takes a string as a parameter. This string represents a number that can be in any base (less than 37) and return the sum of its digits.
<ide> <ul>
<ide> Write a function that takes a string as a parameter. This string represents a nu
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sumDigits</code> should be a function.
<del> testString: assert(typeof sumDigits == 'function', '<code>sumDigits</code> should be a function.');
<add> testString: assert(typeof sumDigits == 'function');
<ide> - text: <code>sumDigits("1")</code> should return a number.
<del> testString: assert(typeof sumDigits("1") == 'number', '<code>sumDigits("1")</code> should return a number.');
<add> testString: assert(typeof sumDigits("1") == 'number');
<ide> - text: <code>sumDigits("1")</code> should return <code>1</code>.
<del> testString: assert.equal(sumDigits("1"), 1, '<code>sumDigits("1")</code> should return <code>1</code>.');
<add> testString: assert.equal(sumDigits("1"), 1);
<ide> - text: <code>sumDigits("12345")</code> should return <code>15</code>.
<del> testString: assert.equal(sumDigits("12345"), 15, '<code>sumDigits("12345")</code> should return <code>15</code>.');
<add> testString: assert.equal(sumDigits("12345"), 15);
<ide> - text: <code>sumDigits("254")</code> should return <code>11</code>.
<del> testString: assert.equal(sumDigits("254"), 11, '<code>sumDigits("254")</code> should return <code>11</code>.');
<add> testString: assert.equal(sumDigits("254"), 11);
<ide> - text: <code>sumDigits("fe")</code> should return <code>29</code>.
<del> testString: assert.equal(sumDigits("fe"), 29, '<code>sumDigits("fe")</code> should return <code>29</code>.');
<add> testString: assert.equal(sumDigits("fe"), 29);
<ide> - text: <code>sumDigits("f0e")</code> should return <code>29</code>.
<del> testString: assert.equal(sumDigits("f0e"), 29, '<code>sumDigits("f0e")</code> should return <code>29</code>.');
<add> testString: assert.equal(sumDigits("f0e"), 29);
<ide> - text: <code>sumDigits("999ABCXYZ")</code> should return <code>162</code>.
<del> testString: assert.equal(sumDigits("999ABCXYZ"), 162, '<code>sumDigits("999ABCXYZ")</code> should return <code>162</code>.');
<add> testString: assert.equal(sumDigits("999ABCXYZ"), 162);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function sumDigits(n) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function sumDigits(n) {
<del> n += ''
<del> for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36)
<del> return s
<add> n += '';
<add> for (var s = 0, i = 0, e = n.length; i < e; i += 1)
<add> s += parseInt(n.charAt(i), 36);
<add> return s;
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sum-multiples-of-3-and-5.english.md
<ide> forumTopicId: 302332
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below <i>n</i>.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sumMults</code> should be a function.
<del> testString: assert(typeof sumMults == 'function', '<code>sumMults</code> should be a function.');
<add> testString: assert(typeof sumMults == 'function');
<ide> - text: <code>sumMults(10)</code> should return a number.
<del> testString: assert(typeof sumMults(10) == 'number', '<code>sumMults(10)</code> should return a number.');
<add> testString: assert(typeof sumMults(10) == 'number');
<ide> - text: <code>sumMults(10)</code> should return <code>23</code>.
<del> testString: assert.equal(sumMults(10), 23, '<code>sumMults(10)</code> should return <code>23</code>.');
<add> testString: assert.equal(sumMults(10), 23);
<ide> - text: <code>sumMults(100)</code> should return <code>2318</code>.
<del> testString: assert.equal(sumMults(100), 2318, '<code>sumMults(100)</code> should return <code>2318</code>.');
<add> testString: assert.equal(sumMults(100), 2318);
<ide> - text: <code>sumMults(1000)</code> should return <code>233168</code>.
<del> testString: assert.equal(sumMults(1000), 233168, '<code>sumMults(1000)</code> should return <code>233168</code>.');
<add> testString: assert.equal(sumMults(1000), 233168);
<ide> - text: <code>sumMults(10000)</code> should return <code>23331668</code>.
<del> testString: assert.equal(sumMults(10000), 23331668, '<code>sumMults(10000)</code> should return <code>23331668</code>.');
<add> testString: assert.equal(sumMults(10000), 23331668);
<ide> - text: <code>sumMults(100000)</code> should return <code>2333316668</code>.
<del> testString: assert.equal(sumMults(100000), 2333316668, '<code>sumMults(100000)</code> should return <code>2333316668</code>.');
<add> testString: assert.equal(sumMults(100000), 2333316668);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function sumMults(n) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sum-of-a-series.english.md
<ide> forumTopicId: 302333
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<del>Compute the <b>n</b><sup>th</sup> term of a <a href="https://en.wikipedia.org/wiki/Series (mathematics)" target="_blank">series</a>, i.e. the sum of the <b>n</b> first terms of the corresponding <a href="https://en.wikipedia.org/wiki/sequence" target="_blank">sequence</a>.
<del>Informally this value, or its limit when <b>n</b> tends to infinity, is also called the <i>sum of the series</i>, thus the title of this task.
<add>Compute the <b>n</b><sup>th</sup> term of a <a href="https://en.wikipedia.org/wiki/Series (mathematics)" target="_blank">series</a>, i.e. the sum of the <b>n</b> first terms of the corresponding <a href="https://en.wikipedia.org/wiki/sequence" target="_blank">sequence</a>.
<add>Informally this value, or its limit when <b>n</b> tends to infinity, is also called the <i>sum of the series</i>, thus the title of this task.
<ide> For this task, use:
<ide> <span style="margin-left: 2em;">$S_n = \sum_{k=1}^n \frac{1}{k^2}$</span>
<del>and compute $S_{1000}$
<del> This approximates the <a href="https://en.wikipedia.org/wiki/Riemann zeta function" target="_blank">zeta function</a> for S=2, whose exact value
<add>and compute $S_{1000}$
<add>This approximates the <a href="https://en.wikipedia.org/wiki/Riemann zeta function" target="_blank">zeta function</a> for S=2, whose exact value
<ide> <span style="margin-left: 2em;">$\zeta(2) = {\pi^2\over 6}$</span>
<del> is the solution of the <a href="https://en.wikipedia.org/wiki/Basel problem" target="_blank">Basel problem</a>.
<add>is the solution of the <a href="https://en.wikipedia.org/wiki/Basel problem" target="_blank">Basel problem</a>.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Write a function that take $a$ and $b$ as parameters and returns the sum of $a^{th}$ to $b^{th}$ members of the sequence.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sum</code> should be a function.
<del> testString: assert(typeof sum == 'function', '<code>sum</code> should be a function.');
<add> testString: assert(typeof sum == 'function');
<ide> - text: <code>sum(1, 100)</code> should return a number.
<del> testString: assert(typeof sum(1, 100) == 'number', '<code>sum(1, 100)</code> should return a number.');
<add> testString: assert(typeof sum(1, 100) == 'number');
<ide> - text: <code>sum(1, 100)</code> should return <code>1.6349839001848923</code>.
<del> testString: assert.equal(sum(1, 100), 1.6349839001848923, '<code>sum(1, 100)</code> should return <code>1.6349839001848923</code>.');
<add> testString: assert.equal(sum(1, 100), 1.6349839001848923);
<ide> - text: <code>sum(33, 46)</code> should return <code>0.009262256361481223</code>.
<del> testString: assert.equal(sum(33, 46), 0.009262256361481223, '<code>sum(33, 46)</code> should return <code>0.009262256361481223</code>.');
<add> testString: assert.equal(sum(33, 46), 0.009262256361481223);
<ide> - text: <code>sum(21, 213)</code> should return <code>0.044086990748706555</code>.
<del> testString: assert.equal(sum(21, 213), 0.044086990748706555, '<code>sum(21, 213)</code> should return <code>0.044086990748706555</code>.');
<add> testString: assert.equal(sum(21, 213), 0.044086990748706555);
<ide> - text: <code>sum(11, 111)</code> should return <code>0.08619778593108679</code>.
<del> testString: assert.equal(sum(11, 111), 0.08619778593108679, '<code>sum(11, 111)</code> should return <code>0.08619778593108679</code>.');
<add> testString: assert.equal(sum(11, 111), 0.08619778593108679);
<ide> - text: <code>sum(1, 10)</code> should return <code>1.5497677311665408</code>.
<del> testString: assert.equal(sum(1, 10), 1.5497677311665408, '<code>sum(1, 10)</code> should return <code>1.5497677311665408</code>.');
<add> testString: assert.equal(sum(1, 10), 1.5497677311665408);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function sum(a, b) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function sum(a, b) {
<ide> function fn(x) {
<del> return 1 / (x * x)
<add> return 1 / (x * x);
<ide> }
<ide> var s = 0;
<ide> for (; a <= b; a++) s += fn(a);
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sum-of-squares.english.md
<ide> forumTopicId: 302334
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Write a function to find the sum of squares of an array of integers.
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sumsq</code> should be a function.
<del> testString: assert(typeof sumsq == 'function', '<code>sumsq</code> should be a function.');
<add> testString: assert(typeof sumsq == 'function');
<ide> - text: <code>sumsq([1, 2, 3, 4, 5])</code> should return a number.
<del> testString: assert(typeof sumsq([1, 2, 3, 4, 5]) == 'number', '<code>sumsq([1, 2, 3, 4, 5])</code> should return a number.');
<add> testString: assert(typeof sumsq([1, 2, 3, 4, 5]) == 'number');
<ide> - text: <code>sumsq([1, 2, 3, 4, 5])</code> should return <code>55</code>.
<del> testString: assert.equal(sumsq([1, 2, 3, 4, 5]), 55, '<code>sumsq([1, 2, 3, 4, 5])</code> should return <code>55</code>.');
<add> testString: assert.equal(sumsq([1, 2, 3, 4, 5]), 55);
<ide> - text: <code>sumsq([25, 32, 12, 7, 20])</code> should return <code>2242</code>.
<del> testString: assert.equal(sumsq([25, 32, 12, 7, 20]), 2242, '<code>sumsq([25, 32, 12, 7, 20])</code> should return <code>2242</code>.');
<add> testString: assert.equal(sumsq([25, 32, 12, 7, 20]), 2242);
<ide> - text: <code>sumsq([38, 45, 35, 8, 13])</code> should return <code>4927</code>.
<del> testString: assert.equal(sumsq([38, 45, 35, 8, 13]), 4927, '<code>sumsq([38, 45, 35, 8, 13])</code> should return <code>4927</code>.');
<add> testString: assert.equal(sumsq([38, 45, 35, 8, 13]), 4927);
<ide> - text: <code>sumsq([43, 36, 20, 34, 24])</code> should return <code>5277</code>.
<del> testString: assert.equal(sumsq([43, 36, 20, 34, 24]), 5277, '<code>sumsq([43, 36, 20, 34, 24])</code> should return <code>5277</code>.');
<add> testString: assert.equal(sumsq([43, 36, 20, 34, 24]), 5277);
<ide> - text: <code>sumsq([12, 33, 26, 18, 1, 16, 3])</code> should return <code>2499</code>.
<del> testString: assert.equal(sumsq([12, 33, 26, 18, 1, 16, 3]), 2499, '<code>sumsq([12, 33, 26, 18, 1, 16, 3])</code> should return <code>2499</code>.');
<add> testString: assert.equal(sumsq([12, 33, 26, 18, 1, 16, 3]), 2499);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function sumsq(array) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sum-to-100.english.md
<ide> forumTopicId: 302335
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Find solutions to the <i>sum to one hundred</i> puzzle.
<ide> Add (insert) the mathematical operators <b>+</b> or <b>─</b> (plus or minus) before any of the digits in the decimal numeric string <b>123456789</b> such that the resulting mathematical expression adds up to a particular sum (in this iconic case, <b>100</b>).
<ide> Example:
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> Write a function that takes a number as parameter. The function should return an array containing all solutions for the given number. The solutions should be strings representing the expressions. For example: "1+23-456+78-9". Sort the array before returning it.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>sumTo100</code> should be a function.
<del> testString: assert(typeof sumTo100 == 'function', '<code>sumTo100</code> should be a function.');
<add> testString: assert(typeof sumTo100 == 'function');
<ide> - text: <code>sumTo100(199)</code> should return an array.
<del> testString: assert(Array.isArray(sumTo100(199)), '<code>sumTo100(199)</code> should return an array.');
<add> testString: assert(Array.isArray(sumTo100(199)));
<ide> - text: <code>sumTo100(199)</code> should return <code>["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]</code>.
<del> testString: assert.deepEqual(sumTo100(199), ["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"], '<code>sumTo100(199)</code> should return <code>["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]</code>.');
<add> testString: assert.deepEqual(sumTo100(199), ["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]);
<ide> - text: <code>sumTo100(209)</code> should return <code>["1+234+56+7-89"]</code>.
<del> testString: assert.deepEqual(sumTo100(209), ["1+234+56+7-89"], '<code>sumTo100(209)</code> should return <code>["1+234+56+7-89"]</code>.');
<add> testString: assert.deepEqual(sumTo100(209), ["1+234+56+7-89"]);
<ide> - text: <code>sumTo100(243)</code> should return <code>["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]</code>.
<del> testString: assert.deepEqual(sumTo100(243), ["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"], '<code>sumTo100(243)</code> should return <code>["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]</code>.');
<add> testString: assert.deepEqual(sumTo100(243), ["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]);
<ide> - text: <code>sumTo100(199)</code> should return <code>["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]</code>.
<del> testString: assert.deepEqual(sumTo100(199), ["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"], '<code>sumTo100(199)</code> should return <code>["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]</code>.');
<add> testString: assert.deepEqual(sumTo100(199), ["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]);
<ide> - text: <code>sumTo100(197)</code> should return <code>["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]</code>.
<del> testString: assert.deepEqual(sumTo100(197), ["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"], '<code>sumTo100(197)</code> should return <code>["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]</code>.');
<add> testString: assert.deepEqual(sumTo100(197), ["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide> <div id='js-seed'>
<ide>
<ide> function sumTo100(n) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function sumTo100(n) {
<ide> var permutationsWithRepetition = function(n, as) {
<del> return as.length > 0 ?
<del> foldl1(curry(cartesianProduct)(as), replicate(n, as)) : [];
<add> return as.length > 0
<add> ? foldl1(curry(cartesianProduct)(as), replicate(n, as))
<add> : [];
<ide> };
<ide>
<ide> var cartesianProduct = function(xs, ys) {
<del> return [].concat.apply([], xs.map(function(x) {
<del> return [].concat.apply([], ys.map(function(y) {
<del> return [
<del> [x].concat(y)
<del> ];
<del> }));
<del> }));
<add> return [].concat.apply(
<add> [],
<add> xs.map(function(x) {
<add> return [].concat.apply(
<add> [],
<add> ys.map(function(y) {
<add> return [[x].concat(y)];
<add> })
<add> );
<add> })
<add> );
<ide> };
<ide>
<ide> var curry = function(f) {
<ide> function sumTo100(n) {
<ide> };
<ide>
<ide> var foldl1 = function(f, xs) {
<del> return xs.length > 0 ? xs.slice(1)
<del> .reduce(f, xs[0]) : [];
<add> return xs.length > 0 ? xs.slice(1).reduce(f, xs[0]) : [];
<ide> };
<ide>
<ide> var replicate = function(n, a) {
<ide> function sumTo100(n) {
<ide> };
<ide>
<ide> var asSum = function(xs) {
<del> var dct = xs.reduceRight(function(a, sign, i) {
<del> var d = i + 1; // zero-based index to [1-9] positions
<del> if (sign !== 0) {
<del> // Sum increased, digits cleared
<del> return {
<del> digits: [],
<del> n: a.n + sign * parseInt([d].concat(a.digits)
<del> .join(''), 10)
<del> };
<del> } else return { // Digits extended, sum unchanged
<del> digits: [d].concat(a.digits),
<del> n: a.n
<del> };
<del> }, {
<del> digits: [],
<del> n: 0
<del> });
<del> return dct.n + (
<del> dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0
<add> var dct = xs.reduceRight(
<add> function(a, sign, i) {
<add> var d = i + 1; // zero-based index to [1-9] positions
<add> if (sign !== 0) {
<add> // Sum increased, digits cleared
<add> return {
<add> digits: [],
<add> n: a.n + sign * parseInt([d].concat(a.digits).join(''), 10)
<add> };
<add> } else
<add> return {
<add> // Digits extended, sum unchanged
<add> digits: [d].concat(a.digits),
<add> n: a.n
<add> };
<add> },
<add> {
<add> digits: [],
<add> n: 0
<add> }
<add> );
<add> return (
<add> dct.n + (dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0)
<ide> );
<ide> };
<ide>
<ide> var asString = function(xs) {
<ide> var ns = xs.reduce(function(a, sign, i) {
<del> var d = (i + 1)
<del> .toString();
<add> var d = (i + 1).toString();
<ide> return sign === 0 ? a + d : a + (sign > 0 ? '+' : '-') + d;
<ide> }, '');
<ide>
<ide> function sumTo100(n) {
<ide> var universe = permutationsWithRepetition(9, [0, 1, -1])
<ide> .filter(function(x) {
<ide> return x[0] !== 1 && asSum(x) === n;
<del> }).map(asString);
<del> return universe.sort()
<add> })
<add> .map(asString);
<add> return universe.sort();
<ide> }
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/sutherland-hodgman-polygon-clipping.english.md
<ide> forumTopicId: 302336
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<del>The <a href="https://en.wikipedia.org/wiki/Sutherland-Hodgman clipping algorithm" target="_blank">Sutherland-Hodgman clipping algorithm</a> finds the polygon that is the intersection between an arbitrary polygon (the "subject polygon") and a convex polygon (the "clip polygon").
<add>The <a href="https://en.wikipedia.org/wiki/Sutherland-Hodgman clipping algorithm" target="_blank">Sutherland-Hodgman clipping algorithm</a> finds the polygon that is the intersection between an arbitrary polygon (the "subject polygon") and a convex polygon (the "clip polygon").
<ide> It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.
<ide> Take the closed polygon defined by the points:
<add>
<ide> <pre>[(50, 150), (200, 50), (350, 150), (350, 300), (250, 300), (200, 250), (150, 350), (100, 250), (100, 200)]</pre>
<add>
<ide> and clip it by the rectangle defined by the points:
<add>
<ide> <pre>[(100, 100), (300, 100), (300, 300), (100, 300)]</pre>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Write a function that takes 2 arrays as parameters. The first array contains the points of the subject polygon and the second array contains the points of the clipping polygon. The function should return an array containing the points of the clipped polygon. Each number should be rounded to 3 decimal places.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>clip</code> should be a function.
<del> testString: assert(typeof clip == 'function', '<code>clip</code> should be a function.');
<add> testString: assert(typeof clip == 'function');
<ide> - text: <code>clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])</code> should return an array.
<del> testString: assert(Array.isArray(clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])), '<code>clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])</code> should return an array.');
<add> testString: assert(Array.isArray(clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])));
<ide> - text: <code>clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])</code> should return <code>[[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]]</code>.
<del> testString: assert.deepEqual(clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]]), [[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]], '<code>clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])</code> should return <code>[[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]]</code>.');
<add> testString: assert.deepEqual(clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]]), [[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]]);
<ide> - text: <code>clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]])</code> should return <code>[[150, 200], [350, 400], [348.611, 394.444], [30, 50]]</code>.
<del> testString: assert.deepEqual(clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]]), [[150, 200], [350, 400], [348.611, 394.444], [30, 50]], '<code>clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]])</code> should return <code>[[150, 200], [350, 400], [348.611, 394.444], [30, 50]]</code>.');
<add> testString: assert.deepEqual(clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]]), [[150, 200], [350, 400], [348.611, 394.444], [30, 50]]);
<ide> - text: <code>clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]])</code> should return <code>[[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]]</code>.
<del> testString: assert.deepEqual(clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]]), [[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]], '<code>clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]])</code> should return <code>[[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]]</code>.');
<add> testString: assert.deepEqual(clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]]), [[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function clip(subjectPolygon, clipPolygon) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function clip(subjectPolygon, clipPolygon) {
<ide> var cp1, cp2, s, e, i, j;
<ide> var inside = function(p) {
<del> return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]);
<add> return (
<add> (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0])
<add> );
<ide> };
<ide> var intersection = function() {
<ide> var dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]],
<ide><path>curriculum/challenges/english/08-coding-interview-prep/rosetta-code/symmetric-difference.english.md
<ide> forumTopicId: 16086
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide>
<ide> Given two <a href="https://rosettacode.org/wiki/set" target="_blank">set</a>s <i>A</i> and <i>B</i>, compute $(A \setminus B) \cup (B \setminus A).$
<ide> That is, enumerate the items that are in <i>A</i> or <i>B</i> but not both. This set is called the <a href="https://en.wikipedia.org/wiki/Symmetric difference" target="_blank">symmetric difference</a> of <i>A</i> and <i>B</i>.
<ide> In other words: $(A \cup B) \setminus (A \cap B)$ (the set of items that are in at least one of <i>A</i> or <i>B</i> minus the set of items that are in both <i>A</i> and <i>B</i>).
<add>
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> Write a function that takes two arrays as parameters and returns the symmetric difference. Sort the resultant array before returning it.
<add>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<del>``` yml
<add>```yml
<ide> tests:
<ide> - text: <code>symmetricDifference</code> should be a function.
<del> testString: assert(typeof symmetricDifference == 'function', '<code>symmetricDifference</code> should be a function.');
<add> testString: assert(typeof symmetricDifference == 'function');
<ide> - text: <code>symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])</code> should return an array.
<del> testString: assert(Array.isArray(symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])), '<code>symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])</code> should return an array.');
<add> testString: assert(Array.isArray(symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])));
<ide> - text: <code>symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])</code> should return <code>["Jim", "Serena"]</code>.
<del> testString: assert.deepEqual(symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"]), ["Jim", "Serena"], '<code>symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])</code> should return <code>["Jim", "Serena"]</code>.');
<add> testString: assert.deepEqual(symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"]), ["Jim", "Serena"]);
<ide> - text: <code>symmetricDifference([1, 2, 3], [3, 4])</code> should return <code>[1, 2, 4]</code>.
<del> testString: assert.deepEqual(symmetricDifference([1, 2, 3], [3, 4]), [1, 2, 4], '<code>symmetricDifference([1, 2, 3], [3, 4])</code> should return <code>[1, 2, 4]</code>.');
<add> testString: assert.deepEqual(symmetricDifference([1, 2, 3], [3, 4]), [1, 2, 4]);
<ide> - text: <code>symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7])</code> should return <code>[1, 2, 5, 7, 8]</code>.
<del> testString: assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7]), [1, 2, 5, 7, 8], '<code>symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7])</code> should return <code>[1, 2, 5, 7, 8]</code>.');
<add> testString: assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7]), [1, 2, 5, 7, 8]);
<ide> - text: <code>symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9])</code> should return <code>[2, 4, 9]</code>.
<del> testString: assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9]), [2, 4, 9], '<code>symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9])</code> should return <code>[2, 4, 9]</code>.');
<add> testString: assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9]), [2, 4, 9]);
<ide> - text: <code>symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9])</code> should return <code>[1, 3, 4, 8]</code>.
<del> testString: assert.deepEqual(symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9]), [1, 3, 4, 8], '<code>symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9])</code> should return <code>[1, 3, 4, 8]</code>.');
<add> testString: assert.deepEqual(symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9]), [1, 3, 4, 8]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> function symmetricDifference(A, B) {
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<ide> function symmetricDifference(A, B) {
<ide> function relative_complement(A, B) {
<ide> return A.filter(function(elem) {
<del> return B.indexOf(elem) == -1
<add> return B.indexOf(elem) == -1;
<ide> });
<ide> }
<ide>
<ide> function unique(ary) {
<ide> var u = ary.concat().sort();
<del> for (var i = 1; i < u.length;) {
<del> if (u[i - 1] === u[i])
<del> u.splice(i, 1);
<del> else
<del> i++;
<add> for (var i = 1; i < u.length; ) {
<add> if (u[i - 1] === u[i]) u.splice(i, 1);
<add> else i++;
<ide> }
<ide> return u;
<ide> }
<ide>
<del> return unique(relative_complement(A, B).concat(relative_complement(B, A))).sort();
<add> return unique(
<add> relative_complement(A, B).concat(relative_complement(B, A))
<add> ).sort();
<ide> }
<ide> ```
<ide> | 46 |
Text | Text | add jsdelivr as cdn install option | c81a55fed1d9da9f97cc26391083876e5471e84f | <ide><path>docs/getting-started/installation.md
<ide> Chart.js can be installed via npm or bower. It is recommended to get Chart.js th
<ide>
<ide> ## npm
<ide> [](https://npmjs.com/package/chart.js)
<add>[](https://npmjs.com/package/chart.js)
<ide>
<ide> ```bash
<ide> npm install chart.js --save
<ide> bower install chart.js --save
<ide> ```
<ide>
<ide> ## CDN
<del>[](https://cdnjs.com/libraries/Chart.js)
<add>### CDNJS
<add>[](https://cdnjs.com/libraries/Chart.js)
<ide>
<del>or just use these [Chart.js CDN](https://cdnjs.com/libraries/Chart.js) links.
<add>Chart.js built files are available on [CDNJS](https://cdnjs.com/):
<add>
<add>https://cdnjs.com/libraries/Chart.js
<add>
<add>### jsDelivr
<add>[](https://cdn.jsdelivr.net/npm/chart.js@latest/dist/) [](https://www.jsdelivr.com/package/npm/chart.js)
<add>
<add>Chart.js built files are also available through [jsDelivr](http://www.jsdelivr.com/):
<add>
<add>https://www.jsdelivr.com/package/npm/chart.js?path=dist
<ide>
<ide> ## Github
<ide> [](https://github.com/chartjs/Chart.js/releases/latest) | 1 |
Ruby | Ruby | fix active storage behavior on record dup | d02d259b6128423a0ddf4118a7143c3e7b3cd22f | <ide><path>activestorage/lib/active_storage/attached/model.rb
<ide> def has_one_attached(name, dependent: :purge_later, service: nil)
<ide> generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> # frozen_string_literal: true
<ide> def #{name}
<del> @active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self)
<add> @active_storage_attached ||= {}
<add> @active_storage_attached[:#{name}] ||= ActiveStorage::Attached::One.new("#{name}", self)
<ide> end
<ide>
<ide> def #{name}=(attachable)
<ide> def has_many_attached(name, dependent: :purge_later, service: nil)
<ide> generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> # frozen_string_literal: true
<ide> def #{name}
<del> @active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self)
<add> @active_storage_attached ||= {}
<add> @active_storage_attached[:#{name}] ||= ActiveStorage::Attached::Many.new("#{name}", self)
<ide> end
<ide>
<ide> def #{name}=(attachables)
<ide> def changed_for_autosave? #:nodoc:
<ide> super || attachment_changes.any?
<ide> end
<ide>
<add> def initialize_dup(*) #:nodoc:
<add> super
<add> @active_storage_attached = nil
<add> @attachment_changes = nil
<add> end
<add>
<ide> def reload(*) #:nodoc:
<ide> super.tap { @attachment_changes = nil }
<ide> end
<ide><path>activestorage/test/models/attached/many_test.rb
<ide> class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> test "duped record does not share attachments" do
<add> @user.highlights.attach [ create_blob(filename: "funky.jpg") ]
<add>
<add> assert_not_equal @user.highlights.first, @user.dup.highlights.first
<add> end
<add>
<add> test "duped record does not share attachment changes" do
<add> @user.highlights.attach [ create_blob(filename: "funky.jpg") ]
<add> assert_not_predicate @user, :changed_for_autosave?
<add>
<add> @user.dup.highlights.attach [ create_blob(filename: "town.mp4") ]
<add> assert_not_predicate @user, :changed_for_autosave?
<add> end
<add>
<ide> test "clearing change on reload" do
<ide> @user.highlights = [ create_blob(filename: "funky.jpg"), create_blob(filename: "town.jpg") ]
<ide> assert @user.highlights.attached?
<ide><path>activestorage/test/models/attached/one_test.rb
<ide> def upload.open
<ide> end
<ide> end
<ide>
<add> test "duped record does not share attachments" do
<add> @user.avatar.attach create_blob(filename: "funky.jpg")
<add>
<add> assert_not_equal @user.avatar.attachment, @user.dup.avatar.attachment
<add> end
<add>
<add> test "duped record does not share attachment changes" do
<add> @user.avatar.attach create_blob(filename: "funky.jpg")
<add> assert_not_predicate @user, :changed_for_autosave?
<add>
<add> @user.dup.avatar.attach create_blob(filename: "town.jpg")
<add> assert_not_predicate @user, :changed_for_autosave?
<add> end
<add>
<ide> test "clearing change on reload" do
<ide> @user.avatar = create_blob(filename: "funky.jpg")
<ide> assert @user.avatar.attached? | 3 |
PHP | PHP | add validation guess for postgress inet field | 744558de90c4a408fba6c5602783ff465d6eb3e3 | <ide><path>lib/Cake/Console/Command/Task/ModelTask.php
<ide> public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
<ide> $guess = $methods['date'];
<ide> } elseif ($metaData['type'] == 'time') {
<ide> $guess = $methods['time'];
<add> } elseif ($metaData['type'] == 'inet') {
<add> $guess = $methods['ip'];
<ide> }
<ide> }
<ide> | 1 |
Python | Python | remove some temporary debugging stuff | cb4b4f6be6eeac3d2383614998a5e1436cb4226e | <ide><path>djangorestframework/resource.py
<ide> def dispatch(self, request, *args, **kwargs):
<ide>
<ide> except ErrorResponse, exc:
<ide> response = exc.response
<del>
<del> except:
<del> import traceback
<del> traceback.print_exc()
<ide>
<ide> # Always add these headers.
<ide> #
<ide> # TODO - this isn't actually the correct way to set the vary header,
<ide> # also it's currently sub-obtimal for HTTP caching - need to sort that out.
<del> try:
<del> response.headers['Allow'] = ', '.join(self.allowed_methods)
<del> response.headers['Vary'] = 'Authenticate, Accept'
<add> response.headers['Allow'] = ', '.join(self.allowed_methods)
<add> response.headers['Vary'] = 'Authenticate, Accept'
<ide>
<del> return self.emit(response)
<del> except:
<del> import traceback
<del> traceback.print_exc()
<add> return self.emit(response)
<ide> | 1 |
Javascript | Javascript | use eslint with prettier to format code | fc8c71ad16a8c0c23bfd6ffb284226bf795ca4b2 | <ide><path>api-server/server/middlewares/add-return-to.js
<ide> export default function addReturnToUrl() {
<ide> req.method !== 'GET' ||
<ide> pathsOfNoReturnRegex.test(path) ||
<ide> !whiteListRegex.test(path) ||
<del> (/hot/i).test(req.path)
<add> /hot/i.test(req.path)
<ide> ) {
<ide> return next();
<ide> }
<ide><path>api-server/server/middlewares/csurf.js
<ide> export default function() {
<ide> });
<ide> return function csrf(req, res, next) {
<ide> const path = req.path.split('/')[1];
<del> if ((/(^api$|^unauthenticated$|^internal$|^p$)/).test(path)) {
<add> if (/(^api$|^unauthenticated$|^internal$|^p$)/.test(path)) {
<ide> return next();
<ide> }
<ide> return protection(req, res, next);
<ide><path>api-server/server/utils/map.js
<ide> const getFirstChallenge = _.once(_getFirstChallenge);
<ide> * interface ChallengeMap {
<ide> * result: {
<ide> * superBlocks: [ ...superBlockDashedName: String ]
<del>* },
<add> * },
<ide> * entities: {
<ide> * superBlock: {
<ide> * [ ...superBlockDashedName ]: SuperBlock
<ide> export function _cachedMap({ Block, Challenge }) {
<ide> });
<ide> const blockMap = Observable.combineLatest(
<ide> blocks.map(blocks =>
<del> blocks.map(block => block.toJSON()).reduce((hash, block) => {
<del> hash[block.dashedName] = block;
<del> return hash;
<del> }, {})
<add> blocks
<add> .map(block => block.toJSON())
<add> .reduce((hash, block) => {
<add> hash[block.dashedName] = block;
<add> return hash;
<add> }, {})
<ide> ),
<ide> challenges
<ide> ).map(([blocksMap, challenges]) => {
<ide><path>client/gatsby-browser.js
<ide> export const wrapPageElement = ({ element, props }) => {
<ide> </DefaultLayout>
<ide> );
<ide> }
<del> if ((/^\/guide(\/.*)*/).test(pathname)) {
<add> if (/^\/guide(\/.*)*/.test(pathname)) {
<ide> return (
<ide> <DefaultLayout>
<ide> <GuideLayout>{element}</GuideLayout>
<ide> </DefaultLayout>
<ide> );
<ide> }
<del> if ((/^\/learn(\/.*)*/).test(pathname)) {
<add> if (/^\/learn(\/.*)*/.test(pathname)) {
<ide> return <DefaultLayout showFooter={false}>{element}</DefaultLayout>;
<ide> }
<ide> return <DefaultLayout>{element}</DefaultLayout>;
<ide><path>client/gatsby-node.js
<ide> exports.onCreateWebpackConfig = ({ stage, rules, plugins, actions }) => {
<ide> /* eslint-disable max-len */
<ide> exclude: modulePath => {
<ide> return (
<del> (/node_modules/).test(modulePath) &&
<del> !(/(ansi-styles|chalk|strict-uri-encode|react-freecodecamp-search)/).test(
<add> /node_modules/.test(modulePath) &&
<add> !/(ansi-styles|chalk|strict-uri-encode|react-freecodecamp-search)/.test(
<ide> modulePath
<ide> )
<ide> );
<ide><path>client/gatsby-ssr.js
<ide> export const wrapPageElement = ({ element, props }) => {
<ide> </DefaultLayout>
<ide> );
<ide> }
<del> if ((/^\/guide(\/.*)*/).test(pathname)) {
<add> if (/^\/guide(\/.*)*/.test(pathname)) {
<ide> return (
<ide> <DefaultLayout>
<ide> <GuideLayout>{element}</GuideLayout>
<ide> </DefaultLayout>
<ide> );
<ide> }
<del> if ((/^\/learn(\/.*)*/).test(pathname)) {
<add> if (/^\/learn(\/.*)*/.test(pathname)) {
<ide> return <DefaultLayout showFooter={false}>{element}</DefaultLayout>;
<ide> }
<ide> return <DefaultLayout>{element}</DefaultLayout>;
<ide><path>client/plugins/fcc-source-challenges/gatsby-node.js
<ide> exports.sourceNodes = function sourceChallengesSourceNodes(
<ide> persistent: true
<ide> });
<ide>
<del> watcher.on('ready', sourceAndCreateNodes).on(
<del> 'change',
<del> filePath =>
<del> (/\.md$/).test(filePath)
<del> ? onSourceChange(filePath)
<del> .then(challenge => {
<del> reporter.info(
<del> `File changed at ${filePath}, replacing challengeNode id ${
<del> challenge.id
<del> }`
<del> );
<del> return createChallengeNode(challenge, reporter);
<del> })
<del> .then(createNode)
<del> .catch(e =>
<del> reporter.error(`fcc-replace-challenge
<add> watcher.on('ready', sourceAndCreateNodes).on('change', filePath =>
<add> /\.md$/.test(filePath)
<add> ? onSourceChange(filePath)
<add> .then(challenge => {
<add> reporter.info(
<add> `File changed at ${filePath}, replacing challengeNode id ${
<add> challenge.id
<add> }`
<add> );
<add> return createChallengeNode(challenge, reporter);
<add> })
<add> .then(createNode)
<add> .catch(e =>
<add> reporter.error(`fcc-replace-challenge
<ide>
<ide> ${e.message}
<ide>
<ide> `)
<del> )
<del> : null
<add> )
<add> : null
<ide> );
<ide>
<ide> function sourceAndCreateNodes() {
<ide><path>client/plugins/gatsby-remark-fcc-forum-emoji/index.js
<ide> function markdownToHTML(node) {
<ide> }
<ide>
<ide> module.exports = function forumEmojiPlugin({ markdownAST }) {
<del> visit(
<del> markdownAST,
<del> 'image',
<del> imageNode =>
<del> emojiRE.test(imageNode.title) ? markdownToHTML(imageNode) : imageNode
<add> visit(markdownAST, 'image', imageNode =>
<add> emojiRE.test(imageNode.title) ? markdownToHTML(imageNode) : imageNode
<ide> );
<ide> };
<ide><path>client/src/client-only-routes/ShowSettings.js
<ide> function ShowSettings(props) {
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> href={`/${username}`}
<del> >
<add> >
<ide> Show me my public portfolio
<ide> </Button>
<ide> <Button
<ide> function ShowSettings(props) {
<ide> className='btn-invert'
<ide> href={'/signout'}
<ide> onClick={createHandleSignoutClick(hardGoTo)}
<del> >
<add> >
<ide> Sign me out of freeCodeCamp
<ide> </Button>
<ide> </FullWidthRow>
<ide><path>client/src/client-only-routes/ShowUnsubscribed.js
<ide> function ShowUnsubscribed({ unsubscribeId }) {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> href={`${apiLocation}/internal/resubscribe/${unsubscribeId}`}
<del> >
<add> >
<ide> You can click here to resubscribe
<ide> </Button>
<ide> </FullWidthRow>
<ide><path>client/src/components/Donation/components/DonateCompletion.js
<ide> function DonateCompletion({ processing, reset, success, error = null }) {
<ide> const heading = processing
<ide> ? 'We are processing your donation.'
<ide> : success
<del> ? 'Your donation was successful.'
<del> : 'Something went wrong with your donation';
<add> ? 'Your donation was successful.'
<add> : 'Something went wrong with your donation';
<ide> return (
<ide> <Alert bsStyle={style} className='donation-completion'>
<ide> <h4>{heading}</h4>
<ide><path>client/src/components/Donation/components/DonateForm.js
<ide> class DonateForm extends Component {
<ide> disabled={!isFormValid}
<ide> id='confirm-donation-btn'
<ide> type='submit'
<del> >
<add> >
<ide> Confirm your donation of $5 / month
<ide> </Button>
<ide> <Spacer />
<ide><path>client/src/components/Donation/components/DonateModal.js
<ide> import DonateText from './DonateText';
<ide>
<ide> import '../Donation.css';
<ide>
<del>const mapStateToProps = createSelector(isDonationModalOpenSelector, show => ({
<del> show
<del>}));
<add>const mapStateToProps = createSelector(
<add> isDonationModalOpenSelector,
<add> show => ({
<add> show
<add> })
<add>);
<ide>
<ide> const mapDispatchToProps = dispatch =>
<ide> bindActionCreators(
<ide><path>client/src/components/Flash/index.js
<ide> function Flash({ messages, onClose }) {
<ide> className='flash-message'
<ide> key={id}
<ide> onDismiss={createDismissHandler(onClose, id)}
<del> >
<add> >
<ide> <div dangerouslySetInnerHTML={{ __html: message }} />
<ide> </Alert>
<ide> ));
<ide><path>client/src/components/Footer/index.js
<ide> const ColHeader = ({ children, ...other }) => (
<ide> ColHeader.propTypes = propTypes;
<ide>
<ide> const Link = ({ children, to, external, ...other }) => {
<del> if (!external && (/^\/(?!\/)/).test(to)) {
<add> if (!external && /^\/(?!\/)/.test(to)) {
<ide> return (
<ide> <GatsbyLink to={to} {...other}>
<ide> {children}
<ide><path>client/src/components/Header/components/Login.js
<ide> import { gtagReportConversion } from '../../../analytics/gtag';
<ide>
<ide> import './login.css';
<ide>
<del>const mapStateToProps = createSelector(isSignedInSelector, isSignedIn => ({
<del> isSignedIn
<del>}));
<add>const mapStateToProps = createSelector(
<add> isSignedInSelector,
<add> isSignedIn => ({
<add> isSignedIn
<add> })
<add>);
<ide> const mapDispatchToProps = dispatch => ({
<ide> navigate: location => dispatch(hardGoTo(location))
<ide> });
<ide> function Login(props) {
<ide> className={
<ide> (restProps.block ? 'btn-cta-big' : '') + ' signup-btn btn-cta'
<ide> }
<del> >
<add> >
<ide> {children || 'Sign In'}
<ide> </Button>
<ide> </a>
<ide><path>client/src/components/Header/components/SignedIn.js
<ide> import { createSelector } from 'reselect';
<ide>
<ide> import { userSelector } from '../../../redux';
<ide>
<del>const mapStateToProps = createSelector(userSelector, ({ picture }) => ({
<del> picture
<del>}));
<add>const mapStateToProps = createSelector(
<add> userSelector,
<add> ({ picture }) => ({
<add> picture
<add> })
<add>);
<ide>
<ide> function SignedIn({ picture }) {
<ide> return (
<ide><path>client/src/components/Header/index.js
<ide> class Header extends Component {
<ide> className='menu-button'
<ide> onClick={this.toggleClass}
<ide> ref={this.menuButtonRef}
<del> >
<add> >
<ide> Menu
<ide> </span>
<ide> <Media onChange={this.handleMediaChange} query='(max-width: 734px)' />
<ide><path>client/src/components/Map/components/Block.js
<ide> export class Block extends Component {
<ide> <li
<ide> className={'map-challenge-title' + completedClass}
<ide> key={'map-challenge' + challenge.fields.slug}
<del> >
<add> >
<ide> <span className='badge map-badge'>
<ide> {i !== 0 && this.renderCheckMark(challenge.isCompleted)}
<ide> </span>
<ide> <Link
<ide> onClick={this.handleChallengeClick(challenge.fields.slug)}
<ide> to={challenge.fields.slug}
<del> >
<add> >
<ide> {challenge.title || challenge.frontmatter.title}
<ide> </Link>
<ide> </li>
<ide><path>client/src/components/Map/components/SuperBlock.js
<ide> import { ChallengeNode } from '../../../redux/propTypes';
<ide> const mapStateToProps = (state, ownProps) => {
<ide> const expandedSelector = makeExpandedSuperBlockSelector(ownProps.superBlock);
<ide>
<del> return createSelector(expandedSelector, isExpanded => ({ isExpanded }))(
<del> state
<del> );
<add> return createSelector(
<add> expandedSelector,
<add> isExpanded => ({ isExpanded })
<add> )(state);
<ide> };
<ide>
<ide> function mapDispatchToProps(dispatch) {
<ide><path>client/src/components/Supporters.js
<ide> function Supporters({ isDonating, activeDonations }) {
<ide> bsStyle='primary'
<ide> href='https://donate.freecodecamp.org'
<ide> target='_blank'
<del> >
<add> >
<ide> Click here to become a Supporter
<ide> </Button>
<ide> </FullWidthRow>
<ide><path>client/src/components/formHelpers/Form.js
<ide> export function DynamicForm({
<ide> id={`dynamic-${id}`}
<ide> onSubmit={handleSubmit(submit)}
<ide> style={{ width: '100%' }}
<del> >
<add> >
<ide> <FormFields errors={errors} fields={fields} options={options} />
<ide> <BlockSaveWrapper>
<ide> {hideButton ? null : (
<ide> export function DynamicForm({
<ide> (allPristine && !enableSubmit) ||
<ide> !!Object.keys(errors).filter(key => errors[key]).length
<ide> }
<del> >
<add> >
<ide> {buttonText ? buttonText : null}
<ide> </BlockSaveButton>
<ide> )}
<ide><path>client/src/components/formHelpers/index.js
<ide> export function getValidationState(field) {
<ide> return null;
<ide> }
<ide>
<del> if ((/https?:\/\/glitch\.com\/edit\/#!\/.*/g).test(field.value)) {
<add> if (/https?:\/\/glitch\.com\/edit\/#!\/.*/g.test(field.value)) {
<ide> return 'glitch-warning';
<ide> }
<ide>
<ide><path>client/src/components/helpers/ToggleButton.js
<ide> export default function ToggleButton({
<ide> disabled={value}
<ide> type='radio'
<ide> value={1}
<del> >
<add> >
<ide> {onLabel}
<ide> </TB>
<ide> <TB
<ide> export default function ToggleButton({
<ide> disabled={!value}
<ide> type='radio'
<ide> value={2}
<del> >
<add> >
<ide> {offLabel}
<ide> </TB>
<ide> </BSBG>
<ide><path>client/src/components/helpers/form/BlockSaveButton.js
<ide> function BlockSaveButton({ children, ...restProps }) {
<ide> bsStyle='primary'
<ide> type='submit'
<ide> {...restProps}
<del> >
<add> >
<ide> {children || 'Save'}
<ide> </Button>
<ide> );
<ide><path>client/src/components/layouts/Default.js
<ide> class DefaultLayout extends Component {
<ide> },
<ide> { name: 'keywords', content: metaKeywords.join(', ') }
<ide> ]}
<del> >
<add> >
<ide> <style>{fontawesome.dom.css()}</style>
<ide> </Helmet>
<ide> <Header disableSettings={disableSettings} />
<ide><path>client/src/components/layouts/Guide.js
<ide> class GuideLayout extends React.Component {
<ide> md={4}
<ide> smHidden={!displaySideNav}
<ide> xsHidden={!displaySideNav}
<del> >
<add> >
<ide> <SideNav
<ide> expandedState={expandedState}
<ide> onNavigate={this.handleNavigation}
<ide> class GuideLayout extends React.Component {
<ide> md={8}
<ide> smHidden={displaySideNav}
<ide> xsHidden={displaySideNav}
<del> >
<add> >
<ide> <main
<ide> className='content'
<ide> id='main'
<ide> ref={this.getContentRef}
<ide> tabIndex='-1'
<del> >
<add> >
<ide> {this.props.children}
<ide> </main>
<ide> </Col>
<ide><path>client/src/components/layouts/components/guide/NavPanel.js
<ide> function NoArticles() {
<ide> }
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> write one?
<ide> </a>
<ide> </span>
<ide> class NavPanel extends Component {
<ide> bsClass='panelStyle panel'
<ide> id={`${dashedName}-panel`}
<ide> role='listitem'
<del> >
<add> >
<ide> <Panel.Heading>{this.renderHeader()}</Panel.Heading>
<ide> {isExpanded ? <Panel.Body>{this.renderBody()}</Panel.Body> : null}
<ide> </Panel>
<ide><path>client/src/components/layouts/components/guide/SideNav.js
<ide> class SideNav extends Component {
<ide> path={parent.path}
<ide> title={title}
<ide> toggleDisplaySideNav={this.props.toggleDisplaySideNav}
<del> >
<add> >
<ide> {children}
<ide> </NavPanel>
<ide> );
<ide><path>client/src/components/profile/Profile.js
<ide> function renderSettingsButton() {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> className='btn-invert'
<del> >
<add> >
<ide> Update my settings
<ide> </Button>
<ide> </Link>
<ide><path>client/src/components/profile/components/Certifications.js
<ide> function renderCertShow(username, cert) {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> className='btn-invert'
<del> >
<add> >
<ide> View {cert.title}
<ide> </Button>
<ide> </Link>
<ide><path>client/src/components/profile/components/TimeLine.js
<ide> class Timeline extends Component {
<ide> aria-labelledby='contained-modal-title'
<ide> onHide={this.closeSolution}
<ide> show={solutionOpen}
<del> >
<add> >
<ide> <Modal.Header closeButton={true}>
<ide> <Modal.Title id='contained-modal-title'>
<ide> {`${username}'s Solution to ${blockNameify(idToNameMap[id])}`}
<ide><path>client/src/components/settings/Certification.js
<ide> class CertificationSettings extends Component {
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={onClickHandler}
<del> >
<add> >
<ide> Show Code
<ide> </Button>
<ide> );
<ide> class CertificationSettings extends Component {
<ide> className='btn-invert'
<ide> id={`dropdown-for-${projectId}`}
<ide> title='Show Solutions'
<del> >
<add> >
<ide> <MenuItem
<ide> bsStyle='primary'
<ide> href={solution}
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Front End
<ide> </MenuItem>
<ide> <MenuItem
<ide> bsStyle='primary'
<ide> href={githubLink}
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Back End
<ide> </MenuItem>
<ide> </DropdownButton>
<ide> class CertificationSettings extends Component {
<ide> href={solution}
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Show Solution
<ide> </Button>
<ide> );
<ide> class CertificationSettings extends Component {
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={onClickHandler}
<del> >
<add> >
<ide> Show Code
<ide> </Button>
<ide> );
<ide> class CertificationSettings extends Component {
<ide> bsStyle='primary'
<ide> href={certLocation}
<ide> onClick={createClickHandler(superBlock)}
<del> >
<add> >
<ide> {isCert ? 'Show Certification' : 'Claim Certification'}
<ide> </Button>
<ide> </td>
<ide> class CertificationSettings extends Component {
<ide> bsSize='large'
<ide> onHide={this.handleSolutionModalHide}
<ide> show={isOpen}
<del> >
<add> >
<ide> <Modal.Header className='this-one?' closeButton={true}>
<ide> <Modal.Title id='solution-viewer-modal-title'>
<ide> Solution for {projectTitle}
<ide><path>client/src/components/settings/Email.js
<ide> class EmailSettings extends Component {
<ide> <FormGroup
<ide> controlId='new-email'
<ide> validationState={newEmailValidation}
<del> >
<add> >
<ide> <ControlLabel>New Email</ControlLabel>
<ide> <FormControl
<ide> onChange={this.createHandleEmailFormChange('newEmail')}
<ide> class EmailSettings extends Component {
<ide> <FormGroup
<ide> controlId='confirm-email'
<ide> validationState={confirmEmailValidation}
<del> >
<add> >
<ide> <ControlLabel>Confirm New Email</ControlLabel>
<ide> <FormControl
<ide> onChange={this.createHandleEmailFormChange('confirmNewEmail')}
<ide><path>client/src/components/settings/Internet.js
<ide> class InternetSettings extends Component {
<ide> <FormGroup
<ide> controlId='internet-github'
<ide> validationState={this.getValidationStateFor(githubProfile)}
<del> >
<add> >
<ide> <ControlLabel>
<ide> <strong>GitHub</strong>
<ide> </ControlLabel>
<ide> class InternetSettings extends Component {
<ide> <FormGroup
<ide> controlId='internet-linkedin'
<ide> validationState={this.getValidationStateFor(linkedin)}
<del> >
<add> >
<ide> <ControlLabel>
<ide> <strong>LinkedIn</strong>
<ide> </ControlLabel>
<ide> class InternetSettings extends Component {
<ide> <FormGroup
<ide> controlId='internet-picture'
<ide> validationState={this.getValidationStateFor(twitter)}
<del> >
<add> >
<ide> <ControlLabel>
<ide> <strong>Twitter</strong>
<ide> </ControlLabel>
<ide> class InternetSettings extends Component {
<ide> <FormGroup
<ide> controlId='internet-website'
<ide> validationState={this.getValidationStateFor(website)}
<del> >
<add> >
<ide> <ControlLabel>
<ide> <strong>Personal Website</strong>
<ide> </ControlLabel>
<ide><path>client/src/components/settings/Portfolio.js
<ide> class PortfolioSettings extends Component {
<ide> if (isImage && !maybeUrl) {
<ide> return { state: null, message: '' };
<ide> }
<del> if (isImage && !(/\.(png|jpg|jpeg|gif)$/).test(maybeUrl)) {
<add> if (isImage && !/\.(png|jpg|jpeg|gif)$/.test(maybeUrl)) {
<ide> return {
<ide> state: 'error',
<ide> message: 'URL must link directly to an image file'
<ide> class PortfolioSettings extends Component {
<ide> validationState={
<ide> pristine || (!pristine && !title) ? null : titleState
<ide> }
<del> >
<add> >
<ide> <ControlLabel>Title</ControlLabel>
<ide> <FormControl
<ide> onChange={this.createOnChangeHandler(id, 'title')}
<ide> class PortfolioSettings extends Component {
<ide> validationState={
<ide> pristine || (!pristine && !url) ? null : urlState
<ide> }
<del> >
<add> >
<ide> <ControlLabel>URL</ControlLabel>
<ide> <FormControl
<ide> onChange={this.createOnChangeHandler(id, 'url')}
<ide> class PortfolioSettings extends Component {
<ide> <FormGroup
<ide> controlId={`${id}-image`}
<ide> validationState={pristine ? null : imageState}
<del> >
<add> >
<ide> <ControlLabel>Image</ControlLabel>
<ide> <FormControl
<ide> onChange={this.createOnChangeHandler(id, 'image')}
<ide> class PortfolioSettings extends Component {
<ide> <FormGroup
<ide> controlId={`${id}-description`}
<ide> validationState={pristine ? null : descriptionState}
<del> >
<add> >
<ide> <ControlLabel>Description</ControlLabel>
<ide> <FormControl
<ide> componentClass='textarea'
<ide> class PortfolioSettings extends Component {
<ide> /* eslint-enable camelcase */
<ide> })
<ide> }
<del> >
<add> >
<ide> Save this portfolio item
<ide> </BlockSaveButton>
<ide> <ButtonSpacer />
<ide> class PortfolioSettings extends Component {
<ide> className='btn-delete-portfolio'
<ide> onClick={() => this.handleRemoveItem(id)}
<ide> type='button'
<del> >
<add> >
<ide> Remove this portfolio item
<ide> </Button>
<ide> </form>
<ide> class PortfolioSettings extends Component {
<ide> bsStyle='primary'
<ide> onClick={this.handleAdd}
<ide> type='button'
<del> >
<add> >
<ide> Add a new portfolio Item
<ide> </Button>
<ide> </FullWidthRow>
<ide><path>client/src/components/settings/Privacy.js
<ide> import Spacer from '../helpers/Spacer';
<ide> import ToggleSetting from './ToggleSetting';
<ide> import SectionHeader from './SectionHeader';
<ide>
<del>const mapStateToProps = createSelector(userSelector, user => ({
<del> ...user.profileUI,
<del> user
<del>}));
<add>const mapStateToProps = createSelector(
<add> userSelector,
<add> user => ({
<add> ...user.profileUI,
<add> user
<add> })
<add>);
<ide>
<ide> const mapDispatchToProps = dispatch =>
<ide> bindActionCreators({ submitProfileUI }, dispatch);
<ide> class PrivacySettings extends Component {
<ide> toggleFlag={this.toggleFlag('showLocation')}
<ide> />
<ide> <ToggleSetting
<del> action='My "about me"'
<add> action='My "about me"'
<ide> flag={!showAbout}
<ide> flagName='showAbout'
<ide> offLabel='Public'
<ide> class PrivacySettings extends Component {
<ide> href={`data:text/json;charset=utf-8,${encodeURIComponent(
<ide> JSON.stringify(user)
<ide> )}`}
<del> >
<add> >
<ide> Download your data
<ide> </Button>
<ide> </FullWidthRow>
<ide><path>client/src/components/settings/SolutionViewer.js
<ide> function SolutionViewer({
<ide> bsStyle='primary'
<ide> className='solution-viewer'
<ide> key={solution.slice(0, 10)}
<del> >
<add> >
<ide> <Panel.Heading>JS</Panel.Heading>
<ide> <Panel.Body>
<ide> <pre>
<ide><path>client/src/components/settings/Username.js
<ide> class UsernameSettings extends Component {
<ide> characterValidation: { valid }
<ide> } = this.state;
<ide>
<del> return this.setState(
<del> { submitClicked: true },
<del> () => (valid ? submitNewUsername(formValue) : null)
<add> return this.setState({ submitClicked: true }, () =>
<add> valid ? submitNewUsername(formValue) : null
<ide> );
<ide> }
<ide>
<ide><path>client/src/contexts/GuideNavigationContext.js
<ide> class NavigationContextProvider extends Component {
<ide> toggleDisplaySideNav: noop,
<ide> toggleExpandedState: this.toggleExpandedState
<ide> }}
<del> >
<add> >
<ide> {children}
<ide> </Provider>
<ide> );
<ide><path>client/src/pages/accept-privacy-terms.js
<ide> class AcceptPrivacyTerms extends Component {
<ide> id='terms-of-service'
<ide> inline={true}
<ide> onChange={this.createHandleChange('termsOfService')}
<del> >
<add> >
<ide> I accept the{' '}
<ide> <a
<ide> href='https://www.freecodecamp/terms'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> terms of service
<ide> </a>{' '}
<ide> (required)
<ide> class AcceptPrivacyTerms extends Component {
<ide> id='privacy-policy'
<ide> inline={true}
<ide> onChange={this.createHandleChange('privacyPolicy')}
<del> >
<add> >
<ide> I accept the{' '}
<ide> <a
<ide> href='https://www.freecodecamp/privacy'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> privacy policy
<ide> </a>{' '}
<ide> (required)
<ide> class AcceptPrivacyTerms extends Component {
<ide> id='quincy-email'
<ide> inline={true}
<ide> onChange={this.createHandleChange('quincyEmail')}
<del> >
<add> >
<ide> I want weekly emails from Quincy, freeCodeCamp.org's
<ide> founder.
<ide> </Checkbox>
<ide> class AcceptPrivacyTerms extends Component {
<ide> className='big-cta-btn'
<ide> disabled={!privacyPolicy || !termsOfService}
<ide> type='submit'
<del> >
<add> >
<ide> Continue to freeCodeCamp
<ide> </Button>
<ide> </form>
<ide><path>client/src/pages/donate-other.js
<ide> class DonateOtherPage extends Component {
<ide> })
<ide> }
<ide> target='_blank'
<del> >
<add> >
<ide> <input defaultValue='_s-xclick' name='cmd' type='hidden' />{' '}
<ide> <input
<ide> defaultValue={item.defaultValueHash}
<ide><path>client/src/pages/guide.js
<ide> function Index() {
<ide> href='https://freecodecamp.org'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> freeCodeCamp.org
<ide> </a>
<ide> {'. It has a curriculum that starts from zero and helps you learn' +
<ide> function Index() {
<ide> href='https://github.com/freeCodeCamp/freeCodeCamp'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> open source
<ide> </a>
<ide> {'. Your help in making it better is greatly appreciated!'}
<ide><path>client/src/pages/index.js
<ide> const IndexPage = () => (
<ide> href='https://donate.freecodecamp.org/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> make a tax-deductible donation here
<ide> </a>
<ide> </p>
<ide><path>client/src/pages/learn.js
<ide> const IndexPage = ({
<ide> href='https://donate.freecodecamp.org'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> donate
<ide> </a>{' '}
<ide> to our nonprofit.
<ide><path>client/src/pages/software-resources-for-nonprofits.js
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://givecamp.org/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Give Camp
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.volunteermatch.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Volunteer Match.com
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.catchafire.org'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Catchafire
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://anyonecanhaveawebsite.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Anyone Can Have A Website
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://www.youtube.com/watch?v=4AXDKWuY9QM'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> How to build and deploy a website without writing any code for
<ide> free
<ide> </a>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.wix.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Wix
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://www.squarespace.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Square Space
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://wordpress.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> WordPress
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://xprs.imcreator.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Imcreator.com
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://causesignal.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Cause Signal
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://www.thedatabank.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> The Data Bank
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.donorsnap.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Donor Snap
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.donorperfect.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Donor Perfect
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> }
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> E Tapestry
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.z2systems.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Z2 Systems
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.regpacks.com/volunteer-management'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Reg Packs
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://sumac.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Sumac
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.volgistics.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Volgistics
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://www.ordoro.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Ordoro
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.unleashedsoftware.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Unleashed Software
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://www.ezofficeinventory.com/industries/non-profits'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> EZ Office Inventory
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.dokeos.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Dokeos
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.efrontlearning.net/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> E Front Learning
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://moodle.org/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Moodle
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://sakaiproject.org/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Sakai Project
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='https://civicrm.org/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> CiviCRM
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://tcmgr.com/'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Total Community Manager
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.google.com/forms'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Google Forms
<ide> </a>
<ide> </li>
<ide> function SoftwareResourcesForNonProfits() {
<ide> href='http://www.typeform.com'
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<del> >
<add> >
<ide> Typeform
<ide> </a>
<ide> </li>
<ide><path>client/src/pages/update-email.js
<ide> class UpdateEmail extends Component {
<ide> <FormGroup
<ide> controlId='emailInput'
<ide> validationState={this.getEmailValidationState()}
<del> >
<add> >
<ide> <Col
<ide> className='email-label'
<ide> componentClass={ControlLabel}
<ide> sm={2}
<del> >
<add> >
<ide> Email
<ide> </Col>
<ide> <Col sm={10}>
<ide> class UpdateEmail extends Component {
<ide> bsStyle='primary'
<ide> disabled={this.getEmailValidationState() !== 'success'}
<ide> type='submit'
<del> >
<add> >
<ide> {isNewEmail ? 'Update my Email' : 'Verify Email'}
<ide> </Button>
<ide> </Form>
<ide><path>client/src/templates/Challenges/classic/DesktopLayout.js
<ide> class DesktopLayout extends Component {
<ide> renderOnResize={true}
<ide> renderOnResizeRate={20}
<ide> {...resizeProps}
<del> >
<add> >
<ide> {editor}
<ide> </ReflexElement>
<ide> <ReflexSplitter propagate={true} {...resizeProps} />
<ide> class DesktopLayout extends Component {
<ide> renderOnResize={true}
<ide> renderOnResizeRate={20}
<ide> {...resizeProps}
<del> >
<add> >
<ide> {testOutput}
<ide> </ReflexElement>
<ide> </ReflexContainer>
<ide><path>client/src/templates/Challenges/classic/MobileLayout.js
<ide> class MobileLayout extends Component {
<ide> defaultActiveKey={1}
<ide> id='challenge-page-tabs'
<ide> onSelect={moveToTab}
<del> >
<add> >
<ide> <TabPane eventKey={1} title='Instructions'>
<ide> {instructions}
<ide> </TabPane>
<ide><path>client/src/templates/Challenges/components/Challenge-Description.js
<ide> const propTypes = {
<ide> };
<ide>
<ide> function emptyInstruction(instructions) {
<del> return (/^<section\s+id\s*=\s*("|')instructions\1\s*>\s*<\/section>$/).test(
<add> return /^<section\s+id\s*=\s*("|')instructions\1\s*>\s*<\/section>$/.test(
<ide> instructions
<ide> );
<ide> }
<ide><path>client/src/templates/Challenges/components/CompletionModal.js
<ide> export class CompletionModal extends Component {
<ide> onHide={close}
<ide> onKeyDown={isOpen ? handleKeypress : noop}
<ide> show={isOpen}
<del> >
<add> >
<ide> <Modal.Header
<ide> className='challenge-list-header fcc-modal'
<ide> closeButton={true}
<del> >
<add> >
<ide> <Modal.Title className='text-center'>{message}</Modal.Title>
<ide> </Modal.Header>
<ide> <Modal.Body className='completion-modal-body'>
<ide> export class CompletionModal extends Component {
<ide> bsSize='large'
<ide> bsStyle='primary'
<ide> onClick={submitChallenge}
<del> >
<add> >
<ide> Submit and go to next challenge{' '}
<ide> <span className='hidden-xs'>(Ctrl + Enter)</span>
<ide> </Button>
<ide> export class CompletionModal extends Component {
<ide> className='btn-invert'
<ide> download={`${dashedName}.json`}
<ide> href={this.state.downloadURL}
<del> >
<add> >
<ide> Download my solution
<ide> </Button>
<ide> ) : null}
<ide><path>client/src/templates/Challenges/components/HelpModal.js
<ide> export class HelpModal extends Component {
<ide> <Modal.Header
<ide> className='help-modal-header fcc-modal'
<ide> closeButton={true}
<del> >
<add> >
<ide> <Modal.Title className='text-center'>Ask for help?</Modal.Title>
<ide> </Modal.Header>
<ide> <Modal.Body className='help-modal-body text-center'>
<ide> export class HelpModal extends Component {
<ide> rel='noopener noreferrer'
<ide> target='_blank'
<ide> title='Read, search, ask'
<del> >
<add> >
<ide> Read-Search-Ask
<ide> </a>
<ide> method, then you can ask for help on the freeCodeCamp forum.
<ide> export class HelpModal extends Component {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> onClick={createQuestion}
<del> >
<add> >
<ide> Create a help post on the forum
<ide> </Button>
<ide> <Button
<ide> block={true}
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> onClick={closeHelpModal}
<del> >
<add> >
<ide> Cancel
<ide> </Button>
<ide> </Modal.Body>
<ide><path>client/src/templates/Challenges/components/ResetModal.js
<ide> const propTypes = {
<ide> reset: PropTypes.func.isRequired
<ide> };
<ide>
<del>const mapStateToProps = createSelector(isResetModalOpenSelector, isOpen => ({
<del> isOpen
<del>}));
<add>const mapStateToProps = createSelector(
<add> isResetModalOpenSelector,
<add> isOpen => ({
<add> isOpen
<add> })
<add>);
<ide>
<ide> const mapDispatchToProps = dispatch =>
<ide> bindActionCreators(
<ide> function ResetModal({ reset, close, isOpen }) {
<ide> keyboard={true}
<ide> onHide={close}
<ide> show={isOpen}
<del> >
<add> >
<ide> <Modal.Header className='reset-modal-header' closeButton={true}>
<ide> <Modal.Title className='text-center'>Reset this lesson?</Modal.Title>
<ide> </Modal.Header>
<ide> function ResetModal({ reset, close, isOpen }) {
<ide> bsSize='large'
<ide> bsStyle='danger'
<ide> onClick={withActions(reset, close)}
<del> >
<add> >
<ide> Reset this Lesson
<ide> </Button>
<ide> </Modal.Footer>
<ide><path>client/src/templates/Challenges/components/Side-Panel.js
<ide> import { initConsole, challengeTestsSelector } from '../redux';
<ide> import { createSelector } from 'reselect';
<ide> import './side-panel.css';
<ide>
<del>const mapStateToProps = createSelector(challengeTestsSelector, tests => ({
<del> tests
<del>}));
<add>const mapStateToProps = createSelector(
<add> challengeTestsSelector,
<add> tests => ({
<add> tests
<add> })
<add>);
<ide>
<ide> const mapDispatchToProps = dispatch =>
<ide> bindActionCreators(
<ide><path>client/src/templates/Challenges/components/Test-Suite.js
<ide> function TestSuite({ tests }) {
<ide> className='test-result'
<ide> key={text.slice(-6) + index}
<ide> tabIndex='0'
<del> >
<add> >
<ide> <div className='test-status-icon'>
<ide> {isInitial ? <Initial /> : statusIcon}
<ide> </div>
<ide><path>client/src/templates/Challenges/components/Tool-Panel.js
<ide> function ToolPanel({
<ide> className={`tool-panel-group ${
<ide> isMobile ? 'tool-panel-group-mobile' : ''
<ide> }`}
<del> >
<add> >
<ide> <Button block={true} bsStyle='primary' onClick={executeChallenge}>
<ide> {isMobile ? 'Run' : 'Run the Tests'}
<ide> </Button>
<ide> function ToolPanel({
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={openResetModal}
<del> >
<add> >
<ide> {isMobile ? 'Reset' : 'Reset All Code'}
<ide> </Button>
<ide> {guideUrl ? (
<ide> function ToolPanel({
<ide> className='btn-invert'
<ide> href={guideUrl}
<ide> target='_blank'
<del> >
<add> >
<ide> {isMobile ? 'Hint' : 'Get a hint'}
<ide> </Button>
<ide> ) : null}
<ide> function ToolPanel({
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={openVideoModal}
<del> >
<add> >
<ide> {isMobile ? 'Video' : 'Watch a video'}
<ide> </Button>
<ide> ) : null}
<ide> function ToolPanel({
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={openHelpModal}
<del> >
<add> >
<ide> {isMobile ? 'Help' : 'Ask for help'}
<ide> </Button>
<ide> </div>
<ide><path>client/src/templates/Challenges/components/VideoModal.js
<ide> export class VideoModal extends Component {
<ide> dialogClassName='video-modal'
<ide> onHide={closeVideoModal}
<ide> show={isOpen}
<del> >
<add> >
<ide> <Modal.Header
<ide> className='video-modal-header fcc-modal'
<ide> closeButton={true}
<del> >
<add> >
<ide> <Modal.Title className='text-center'>Watch A Video</Modal.Title>
<ide> </Modal.Header>
<ide> <Modal.Body className='video-modal-body'>
<ide><path>client/src/templates/Challenges/components/icons/Fail.js
<ide> function RedFail() {
<ide> viewBox='0 0 200 200'
<ide> width='50'
<ide> xmlns='http://www.w3.org/2000/svg'
<del> >
<add> >
<ide> <g>
<ide> <title>Test failed</title>
<ide> <circle
<ide><path>client/src/templates/Challenges/components/icons/GreenNotCompleted.js
<ide> function GreenNotCompleted(props) {
<ide> width='50'
<ide> xmlns='http://www.w3.org/2000/svg'
<ide> {...props}
<del> >
<add> >
<ide> <g>
<ide> <title>Not Passed</title>
<ide> <circle
<ide><path>client/src/templates/Challenges/components/icons/GreenPass.js
<ide> function GreenPass(props) {
<ide> width='50'
<ide> xmlns='http://www.w3.org/2000/svg'
<ide> {...props}
<del> >
<add> >
<ide> <g>
<ide> <title>Passed</title>
<ide> <circle
<ide><path>client/src/templates/Challenges/components/icons/Initial.js
<ide> function Initial(props) {
<ide> width='50'
<ide> xmlns='http://www.w3.org/2000/svg'
<ide> {...props}
<del> >
<add> >
<ide> <g>
<ide> <title>Initial</title>
<ide> <circle
<ide> function Initial(props) {
<ide> viewBox='-13 -12 50 50'
<ide> width='200'
<ide> xmlns='http://www.w3.org/2000/svg'
<del> >
<add> >
<ide> <path
<ide> d={
<ide> 'M8 1c0-.552.448-1 1-1h6c.553 0 1 .448 1 1s-.447 1-1 1h-6c-' +
<ide><path>client/src/templates/Challenges/project/Tool-Panel.js
<ide> export class ToolPanel extends Component {
<ide> className='btn-invert'
<ide> href={guideUrl}
<ide> target='_blank'
<del> >
<add> >
<ide> Get a hint
<ide> </Button>
<ide> )}
<ide> export class ToolPanel extends Component {
<ide> bsStyle='primary'
<ide> className='btn-invert'
<ide> onClick={openHelpModal}
<del> >
<add> >
<ide> Ask for help
<ide> </Button>
<ide> </div>
<ide> export default connect(
<ide> mapStateToProps,
<ide> mapDispatchToProps
<ide> )(ToolPanel);
<del>
<ide><path>client/src/templates/Challenges/redux/code-storage-epic.js
<ide> function loadCodeEpic(action$, state$) {
<ide> const codeFound = getCode(id);
<ide> if (codeFound && isFilesAllPoly(codeFound)) {
<ide> finalFiles = {
<del> ...fileKeys.map(key => files[key]).reduce(
<del> (files, file) => ({
<del> ...files,
<del> [file.key]: {
<del> ...file,
<del> contents: codeFound[file.key]
<del> ? codeFound[file.key].contents
<del> : file.contents
<del> }
<del> }),
<del> {}
<del> )
<add> ...fileKeys
<add> .map(key => files[key])
<add> .reduce(
<add> (files, file) => ({
<add> ...files,
<add> [file.key]: {
<add> ...file,
<add> contents: codeFound[file.key]
<add> ? codeFound[file.key].contents
<add> : file.contents
<add> }
<add> }),
<add> {}
<add> )
<ide> };
<ide> } else {
<ide> const legacyCode = getLegacyCode(legacyKey);
<ide><path>client/src/templates/Challenges/utils/build.js
<ide> function getJSTestRunner({ build, sources }, proxyLogger) {
<ide>
<ide> const testWorker = createWorker('test-evaluator');
<ide>
<del> return async(testString, testTimeout) => {
<add> return async (testString, testTimeout) => {
<ide> try {
<ide> testWorker.on('LOG', proxyLogger);
<ide> return await testWorker.execute(
<ide><path>client/src/templates/Challenges/utils/frame.js
<ide> const initTestFrame = frameReady => ctx => {
<ide> resolve();
<ide> }
<ide> });
<del> contentLoaded.then(async() => {
<add> contentLoaded.then(async () => {
<ide> const { sources, loadEnzyme } = ctx;
<ide> // default for classic challenges
<ide> // should not be used for modern
<ide><path>client/src/templates/Introduction/Intro.js
<ide> const propTypes = {
<ide> };
<ide>
<ide> function renderMenuItems({ edges = [] }) {
<del> return edges.map(({ node }) => node).map(({ title, fields: { slug } }) => (
<del> <Link key={'intro-' + slug} to={slug}>
<del> <ListGroupItem>{title}</ListGroupItem>
<del> </Link>
<del> ));
<add> return edges
<add> .map(({ node }) => node)
<add> .map(({ title, fields: { slug } }) => (
<add> <Link key={'intro-' + slug} to={slug}>
<add> <ListGroupItem>{title}</ListGroupItem>
<add> </Link>
<add> ));
<ide> }
<ide>
<ide> function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) {
<ide> function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) {
<ide> <Link
<ide> className='btn btn-lg btn-primary btn-block'
<ide> to={firstLessonPath}
<del> >
<add> >
<ide> Go to the first lesson
<ide> </Link>
<ide> <ButtonSpacer />
<ide><path>curriculum/md-translation.js
<ide> async function translateChallenge(file) {
<ide> translateText(instructions),
<ide> ...tests.map(
<ide> test =>
<del> new Promise(async(resolve, reject) => {
<add> new Promise(async (resolve, reject) => {
<ide> const { testString, text } = test;
<ide> const translatedText = await translateText(text).catch(reject);
<ide> return resolve({
<ide> async function translateChallenge(file) {
<ide> const { files = {}, solutions = [], ...challengeMeta } = challenge;
<ide> const md = `---
<ide> ${YAML.dump(
<del> Object.assign(challengeMeta, {
<del> localeTitle: title ? title.join(' ').trim() : ''
<del> }),
<del> { lineWidth: 10000 }
<del> )}---
<add> Object.assign(challengeMeta, {
<add> localeTitle: title ? title.join(' ').trim() : ''
<add> }),
<add> { lineWidth: 10000 }
<add>)}---
<ide>
<ide> ## Description
<ide> ${description}
<ide> ${generateChallengeSeed(files)}
<ide> <section id='solution'>
<ide>
<ide> ${
<del> solutions.length === 0
<del> ? `\`\`\`js
<add> solutions.length === 0
<add> ? `\`\`\`js
<ide> // solution required
<ide> \`\`\``
<del> : solutions
<del> .map(
<del> solution => `
<add> : solutions
<add> .map(
<add> solution => `
<ide> \`\`\`js
<ide> ${solution}
<ide> \`\`\`
<ide> `
<del> )
<del> .join('\n')
<del> }
<add> )
<add> .join('\n')
<add>}
<ide> </section>
<ide> `;
<ide>
<ide> ${contents}
<ide>
<ide> </div>
<ide> ${
<del> head.length
<del> ? `
<add> head.length
<add> ? `
<ide> ### Before Test
<ide> <div id='${ext}-setup'>
<ide>
<ide> ${head}
<ide> \`\`\`
<ide>
<ide> </div>`
<del> : ''
<del> }
<add> : ''
<add>}
<ide> ${
<del> tail.length
<del> ? `
<add> tail.length
<add> ? `
<ide> ### After Test
<ide> <div id='${ext}-teardown'>
<ide>
<ide> console.info('after the test');
<ide> \`\`\`
<ide>
<ide> </div>`
<del> : ''
<del> }
<add> : ''
<add>}
<ide> `;
<ide> });
<ide> }
<ide><path>curriculum/test/test-challenges.js
<ide> async function createTestRunnerForDOMChallenge(
<ide> await context.reload();
<ide> await context.setContent(build);
<ide> await context.evaluate(
<del> async(sources, loadEnzyme) => {
<add> async (sources, loadEnzyme) => {
<ide> const code = sources && 'index' in sources ? sources['index'] : '';
<ide> const getUserInput = fileName => sources[fileName];
<ide> await document.__initTestFrame({ code, getUserInput, loadEnzyme });
<ide> async function createTestRunnerForDOMChallenge(
<ide> loadEnzyme
<ide> );
<ide>
<del> return async({ text, testString }) => {
<add> return async ({ text, testString }) => {
<ide> try {
<ide> const { pass, err } = await Promise.race([
<ide> new Promise((_, reject) => setTimeout(() => reject('timeout'), 5000)),
<ide> async function createTestRunnerForJSChallenge({ files }, solution) {
<ide> const code = sources && 'index' in sources ? sources['index'] : '';
<ide>
<ide> const testWorker = createWorker('test-evaluator');
<del> return async({ text, testString }) => {
<add> return async ({ text, testString }) => {
<ide> try {
<ide> const { pass, err } = await testWorker.execute(
<ide> { testString, build, code, sources },
<ide><path>tools/challenge-md-parser/text-to-data.js
<ide> function textToData(sectionIds) {
<ide> const lines = child.value.split('\n');
<ide> if (lines.filter(Boolean).length > 0) {
<ide> lines.forEach((line, index) => {
<del> if ((/^\s*$/).test(line)) {
<add> if (/^\s*$/.test(line)) {
<ide> currentParagraph = null;
<ide> } else {
<ide> if (!currentParagraph || index > 0) {
<ide><path>tools/scripts/ci/ensure-challenge-formatting.js
<ide> const challengeFrontmatterValidator = file => frontmatter => {
<ide>
<ide> function isChallengeParseable(file) {
<ide> const { stat, fullPath } = file;
<del> if (!stat.isFile() || (/_meta/).test(fullPath)) {
<add> if (!stat.isFile() || /_meta/.test(fullPath)) {
<ide> return Promise.resolve(true);
<ide> }
<ide> return parseMarkdown(fullPath); | 70 |
Go | Go | use ms_private instead of ms_slave | 757b5775725fb90262cee1fa6068fa9dcbbff59f | <ide><path>pkg/libcontainer/nsinit/mount.go
<ide> const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NOD
<ide> // is no longer in use, the mounts will be removed automatically
<ide> func setupNewMountNamespace(rootfs, console string, readonly bool) error {
<ide> // mount as slave so that the new mounts do not propagate to the host
<del> if err := system.Mount("", "/", "", syscall.MS_SLAVE|syscall.MS_REC, ""); err != nil {
<add> if err := system.Mount("", "/", "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
<ide> return fmt.Errorf("mounting / as slave %s", err)
<ide> }
<ide> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, ""); err != nil { | 1 |
Javascript | Javascript | fix typo in comment | bb36bc7edf4f87a41d4269b619fc88ba662ef4df | <ide><path>src/Angular.js
<ide> function shallowCopy(src, dst) {
<ide>
<ide> for(var key in src) {
<ide> // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
<del> // so we don't need to worry hasOwnProperty here
<add> // so we don't need to worry about using our custom hasOwnProperty here
<ide> if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
<ide> dst[key] = src[key];
<ide> } | 1 |
Ruby | Ruby | fix tests that assumed implicit order by id | c50223b76fdb843dc7e4d4522627a5b20f955a03 | <ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb
<ide> def test_count_with_include_should_alias_join_table
<ide> end
<ide>
<ide> def test_get_ids
<del> assert_equal [posts(:welcome).id, posts(:authorless).id], people(:michael).post_ids
<add> assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort
<ide> end
<ide>
<ide> def test_get_ids_for_loaded_associations
<ide> def test_get_ids_for_loaded_associations
<ide> def test_get_ids_for_unloaded_associations_does_not_load_them
<ide> person = people(:michael)
<ide> assert !person.posts.loaded?
<del> assert_equal [posts(:welcome).id, posts(:authorless).id], person.post_ids
<add> assert_equal [posts(:welcome).id, posts(:authorless).id].sort, person.post_ids.sort
<ide> assert !person.posts.loaded?
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix typos across the project | 285529a643de078fae1a286c5b092494713f2945 | <ide><path>lib/AbstractMethodError.js
<ide> function Message() {
<ide> * @example
<ide> * class FooClass {
<ide> * abstractMethod() {
<del> * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overriden.
<add> * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden.
<ide> * }
<ide> * }
<ide> *
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/DelegatedModule.js
<ide> class DelegatedModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/DllModule.js
<ide> class DllModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/FileSystemInfo.js
<ide> const getManagedItem = (managedPath, path) => {
<ide>
<ide> /**
<ide> * @param {FileSystemInfoEntry} entry file system info entry
<del> * @returns {boolean} existance flag
<add> * @returns {boolean} existence flag
<ide> */
<ide> const toExistance = entry => {
<ide> return Boolean(entry);
<ide> class FileSystemInfo {
<ide> this.logger.debug(`${path} invalidated because ${reason}`, ...args);
<ide> if (--this._remainingLogs === 0) {
<ide> this.logger.debug(
<del> "Logging limit has been reached and no futher logging will be emitted by FileSystemInfo"
<add> "Logging limit has been reached and no further logging will be emitted by FileSystemInfo"
<ide> );
<ide> }
<ide> }
<ide> class FileSystemInfo {
<ide> };
<ide> const invalidWithError = (path, err) => {
<ide> if (this._remainingLogs > 0) {
<del> this._log(path, `error occured: %s`, err);
<add> this._log(path, `error occurred: %s`, err);
<ide> }
<ide> invalid();
<ide> };
<ide> class FileSystemInfo {
<ide> */
<ide> const checkExistance = (path, current, snap) => {
<ide> if (!current !== !snap) {
<del> // If existance of item differs
<add> // If existence of item differs
<ide> // it's invalid
<ide> if (this._remainingLogs > 0) {
<ide> this._log(
<ide> class FileSystemInfo {
<ide> const checkFile = (path, current, snap) => {
<ide> if (current === snap) return true;
<ide> if (!current !== !snap) {
<del> // If existance of item differs
<add> // If existence of item differs
<ide> // it's invalid
<ide> if (this._remainingLogs > 0) {
<ide> this._log(
<ide> class FileSystemInfo {
<ide> }
<ide> }
<ide> if (missingExistance) {
<del> for (const [path, existance] of missingExistance) {
<add> for (const [path, existence] of missingExistance) {
<ide> const cache = this._fileTimestamps.get(path);
<ide> if (cache !== undefined) {
<ide> if (
<ide> cache !== "ignore" &&
<del> !checkExistance(path, toExistance(cache), existance)
<add> !checkExistance(path, toExistance(cache), existence)
<ide> ) {
<ide> invalid();
<ide> return;
<ide> class FileSystemInfo {
<ide> jobs++;
<ide> this.fileTimestampQueue.add(path, (err, entry) => {
<ide> if (err) return invalidWithError(path, err);
<del> if (!checkExistance(path, toExistance(entry), existance)) {
<add> if (!checkExistance(path, toExistance(entry), existence)) {
<ide> invalid();
<ide> } else {
<ide> jobDone();
<ide> class FileSystemInfo {
<ide> path.endsWith("node_modules") &&
<ide> (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
<ide> ) {
<del> // we are only interested in existance of this special directory
<add> // we are only interested in existence of this special directory
<ide> this._managedItems.set(path, "exists");
<ide> return callback(null, "exists");
<ide> }
<ide><path>lib/Module.js
<ide> class Module extends DependenciesBlock {
<ide> * @returns {void}
<ide> */
<ide> invalidateBuild() {
<del> // should be overriden to support this feature
<add> // should be overridden to support this feature
<ide> }
<ide>
<ide> /**
<ide> class Module extends DependenciesBlock {
<ide>
<ide> /**
<ide> * @abstract
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> // Better override this method to return the correct types
<ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> * @param {Object} options options object
<ide> * @param {string} options.type module type
<ide> * @param {string} options.request request string
<del> * @param {string} options.userRequest request intented by user (without loaders from config)
<add> * @param {string} options.userRequest request intended by user (without loaders from config)
<ide> * @param {string} options.rawRequest request without resolving
<ide> * @param {LoaderItem[]} options.loaders list of loaders
<ide> * @param {string} options.resource path + query of the real resource
<ide> class NormalModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return this.generator.getTypes(this);
<ide><path>lib/RawModule.js
<ide> class RawModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/ResolverFactory.js
<ide> const { cachedCleverMerge } = require("./util/cleverMerge");
<ide>
<ide> /** @typedef {Resolver & WithOptions} ResolverWithOptions */
<ide>
<del>const EMTPY_RESOLVE_OPTIONS = {};
<add>const EMPTY_RESOLVE_OPTIONS = {};
<ide>
<ide> /**
<ide> * @typedef {Object} ResolverCache
<ide> module.exports = class ResolverFactory {
<ide> * @param {Object=} resolveOptions options
<ide> * @returns {ResolverWithOptions} the resolver
<ide> */
<del> get(type, resolveOptions = EMTPY_RESOLVE_OPTIONS) {
<add> get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) {
<ide> let typedCaches = this.cache.get(type);
<ide> if (!typedCaches) {
<ide> typedCaches = {
<ide><path>lib/RuntimeModule.js
<ide> class RuntimeModule extends Module {
<ide> }
<ide>
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/Template.js
<ide> class Template {
<ide> .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
<ide> }
<ide>
<del> // map number to a single character a-z, A-Z or mulitple characters if number is too big
<add> // map number to a single character a-z, A-Z or multiple characters if number is too big
<ide> /**
<ide> * @param {number} n number to convert to ident
<ide> * @returns {string} returns single character ident
<ide><path>lib/Watching.js
<ide> class Watching {
<ide> /**
<ide> * @param {Iterable<string>} files watched files
<ide> * @param {Iterable<string>} dirs watched directories
<del> * @param {Iterable<string>} missing watched existance entries
<add> * @param {Iterable<string>} missing watched existence entries
<ide> * @returns {void}
<ide> */
<ide> watch(files, dirs, missing) {
<ide><path>lib/cache/IdleFileCachePlugin.js
<ide> class IdleFileCachePlugin {
<ide> }
<ide> currentIdlePromise = Promise.all(promises);
<ide> currentIdlePromise.then(() => {
<del> // Allow to exit the process inbetween
<add> // Allow to exit the process between
<ide> setTimeout(processIdleTasks, 0).unref();
<ide> });
<ide> return;
<ide><path>lib/cache/PackFileCacheStrategy.js
<ide> class Pack {
<ide> }
<ide> }
<ide>
<del> // 2. Check if minimium number is reached
<add> // 2. Check if minimum number is reached
<ide> let mergedIndices;
<ide> if (
<ide> smallUsedContents.length >= CONTENT_COUNT_TO_MERGE ||
<ide><path>lib/library/AssignLibraryPlugin.js
<ide> const accessWithInit = (accessor, existingLength, initLast = false) => {
<ide> propsSoFar = [];
<ide> }
<ide>
<del> // all remainig properties (except the last one when initLast is not set)
<add> // all remaining properties (except the last one when initLast is not set)
<ide> // should be printed as initializer
<ide> const initUntil = initLast ? accessor.length : accessor.length - 1;
<ide> for (; i < initUntil; i++) {
<ide><path>lib/logging/createConsoleLogger.js
<ide> const { LogType } = require("./Logger");
<ide>
<ide> /**
<ide> * @param {FilterItemTypes} item an input item
<del> * @returns {FilterFunction} filter funtion
<add> * @returns {FilterFunction} filter function
<ide> */
<ide> const filterToFunction = item => {
<ide> if (typeof item === "string") {
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> this._orderedConcatenationList = m._orderedConcatenationList;
<ide> }
<ide> /**
<del> * @returns {Set<string>} types availiable (do not mutate)
<add> * @returns {Set<string>} types available (do not mutate)
<ide> */
<ide> getSourceTypes() {
<ide> return TYPES;
<ide><path>lib/optimize/LimitChunkCountPlugin.js
<ide> class LimitChunkCountPlugin {
<ide>
<ide> // list of modified chunks during this run
<ide> // combinations affected by this change are skipped to allow
<del> // futher optimizations
<add> // further optimizations
<ide> /** @type {Set<Chunk>} */
<ide> const modifiedChunks = new Set();
<ide>
<ide><path>lib/rules/RuleSetCompiler.js
<ide> class RuleSetCompiler {
<ide> /**
<ide> * @param {string} path current path
<ide> * @param {any} value value at the error location
<del> * @param {string} message message explaning the problem
<add> * @param {string} message message explaining the problem
<ide> * @returns {Error} an error object
<ide> */
<ide> error(path, value, message) {
<ide><path>lib/stats/DefaultStatsPrinterPlugin.js
<ide> const ITEM_NAMES = {
<ide> "moduleTraceItem.dependencies[]": "moduleTraceDependency"
<ide> };
<ide>
<del>const ERROR_PREFERED_ORDER = [
<add>const ERROR_PREFERRED_ORDER = [
<ide> "compilerPath",
<ide> "chunkId",
<ide> "chunkEntry",
<ide> const ERROR_PREFERED_ORDER = [
<ide> ];
<ide>
<ide> /** @type {Record<string, string[]>} */
<del>const PREFERED_ORDERS = {
<add>const PREFERRED_ORDERS = {
<ide> compilation: [
<ide> "name",
<ide> "hash",
<ide> const PREFERED_ORDERS = {
<ide> "filteredModules"
<ide> ],
<ide> chunkOrigin: ["request", "moduleId", "moduleName", "loc"],
<del> error: ERROR_PREFERED_ORDER,
<del> warning: ERROR_PREFERED_ORDER,
<add> error: ERROR_PREFERRED_ORDER,
<add> warning: ERROR_PREFERRED_ORDER,
<ide> "chunk.childrenByOrder[]": ["type", "children"],
<ide> loggingGroup: [
<ide> "debug",
<ide> class DefaultStatsPrinterPlugin {
<ide> );
<ide> }
<ide>
<del> for (const key of Object.keys(PREFERED_ORDERS)) {
<del> const preferedOrder = PREFERED_ORDERS[key];
<add> for (const key of Object.keys(PREFERRED_ORDERS)) {
<add> const preferedOrder = PREFERRED_ORDERS[key];
<ide> stats.hooks.sortElements
<ide> .for(key)
<ide> .tap("DefaultStatsPrinterPlugin", (elements, context) => {
<ide><path>test/configCases/concatenate-modules/rename-10168/index.js
<ide> import { A, B, CC, D, E } from "./all";
<ide> require("./all");
<ide> require("./D");
<ide>
<del>it("should not rename classes unneccessary", () => {
<add>it("should not rename classes unnecessary", () => {
<ide> expect(A.name).toBe("A");
<ide> expect(B.name).toBe("B_B");
<ide> expect(CC.name).toBe("C"); | 22 |
Javascript | Javascript | fix a tiny typo | 2eb9a128e2aded663f3b68f89bf3666cc317dad2 | <ide><path>test/benchmark/core/TriangleClosestPoint.js
<ide> s.add('9^3 points, 20 triangles', function() {
<ide> var target = new THREE.Vector3();
<ide> for (var tidx = 0; tidx < triangles.length; tidx++) {
<del> triangle = triangles[tidx];
<add> var triangle = triangles[tidx];
<ide> for (var pidx = 0; pidx < testPoints.length; pidx++) {
<ide> triangle.closestPointToPoint(testPoints[pidx], target);
<ide> } | 1 |
Python | Python | fix tests with mock timezone | a0a2c5cb370ff80a95deaa8d23f099acc4e5e0c5 | <ide><path>tests/test_fields.py
<ide> class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
<ide> }
<ide> outputs = {}
<ide>
<del> class MockTimezone:
<add> class MockTimezone(pytz.BaseTzInfo):
<ide> @staticmethod
<ide> def localize(value, is_dst):
<ide> raise pytz.InvalidTimeError() | 1 |
Text | Text | remove trailing slash in url's | 7f09b3c3ba8fc26c09df5c1cc87020c5f9a681dd | <ide><path>README.md
<ide> This architecture might seem like an overkill for a counter app, but the beauty
<ide>
<ide> ### Discussion
<ide>
<del>Join the **#redux** channel of the [Reactiflux](http://reactiflux.com/) Slack community.
<add>Join the **#redux** channel of the [Reactiflux](http://reactiflux.com) Slack community.
<ide>
<ide> ### Thanks
<ide>
<ide> Join the **#redux** channel of the [Reactiflux](http://reactiflux.com/) Slack co
<ide> * [Cycle](https://github.com/staltz/cycle) for showing how often a function is the best tool;
<ide> * [React](https://github.com/facebook/react) for the pragmatic innovation.
<ide>
<del>Special thanks to [Jamie Paton](http://jdpaton.github.io/) for handing over the `redux` NPM package name.
<add>Special thanks to [Jamie Paton](http://jdpaton.github.io) for handing over the `redux` NPM package name.
<ide>
<ide> ### Patrons
<ide> | 1 |
Ruby | Ruby | require base64 in the places we're using it | d04dbcfcbd4b8ef0a7d4c607949c5d9c7860346f | <ide><path>activerecord/lib/active_record/encryption/cipher/aes256_gcm.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "openssl"
<del>require "base64"
<ide>
<ide> module ActiveRecord
<ide> module Encryption
<ide><path>activerecord/lib/active_record/encryption/message_serializer.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "base64"
<add>
<ide> module ActiveRecord
<ide> module Encryption
<ide> # A message serializer that serializes +Messages+ with JSON.
<ide><path>activerecord/lib/active_record/fixture_set/render_context.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "base64"
<add>
<ide> # NOTE: This class has to be defined in compact style in
<ide> # order for rendering context subclassing to work correctly.
<ide> class ActiveRecord::FixtureSet::RenderContext # :nodoc:
<ide><path>activerecord/test/cases/encryption/message_serializer_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "cases/encryption/helper"
<add>require "base64"
<ide>
<ide> class ActiveRecord::Encryption::MessageSerializerTest < ActiveRecord::EncryptionTestCase
<ide> setup do | 4 |
Python | Python | fail tests if malformed status file | 02590b4cfa2cefc512cdee4244490a09676a58b2 | <ide><path>tools/test.py
<ide> def ReadConfigurationInto(path, sections, defs):
<ide> if prefix_match:
<ide> prefix = SplitPath(prefix_match.group(1).strip())
<ide> continue
<del> print "Malformed line: '%s'." % line
<del> return False
<del> return True
<add> raise Exception("Malformed line: '%s'." % line)
<ide>
<ide>
<ide> # --------------- | 1 |
Ruby | Ruby | fix an error on 1.8.7 | b1ae796284850e29d5ad0fc769e55ed4a43676a4 | <ide><path>actionpack/lib/action_dispatch/testing/integration.rb
<ide> def cookies
<ide>
<ide> # Create and initialize a new Session instance.
<ide> def initialize(app)
<del> super
<add> super()
<ide> @app = app
<ide>
<ide> # If the app is a Rails app, make url_helpers available on the session | 1 |
PHP | PHP | add test for merging associative properties | d2cde877778e2058d61b6c9e215330f0c49fadfe | <ide><path>tests/TestCase/Utility/MergeVariablesTraitTest.php
<ide> class Child extends Base {
<ide> 'Orange'
<ide> ];
<ide>
<add> public $nestedProperty = [
<add> 'Red' => [
<add> 'apple' => 'gala',
<add> ],
<add> 'Green' => [
<add> 'citrus' => 'lime'
<add> ],
<add> ];
<add>
<ide> }
<ide>
<ide> class Grandchild extends Child {
<ide> class Grandchild extends Child {
<ide> 'Green' => ['apple'],
<ide> 'Yellow' => ['banana']
<ide> ];
<add>
<add> public $nestedProperty = [
<add> 'Red' => [
<add> 'apple' => 'mcintosh',
<add> 'citrus' => 'blood orange',
<add> ],
<add> 'Green' => [
<add> 'citrus' => 'key lime'
<add> ],
<add> ];
<ide> }
<ide>
<ide> /**
<ide> public function testMergeVarsAsList() {
<ide> }
<ide>
<ide> /**
<del> * Test merging vars as an assoc list.
<add> * Test merging vars as an associative list.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testMergeVarsAsAssoc() {
<ide> $this->assertEquals($expected, $object->assocProperty);
<ide> }
<ide>
<add>/**
<add> * Test merging variable in associated properties that contain
<add> * additional keys.
<add> *
<add> * @return void
<add> */
<add> public function testMergeVarsAsAssocWithKeyValues() {
<add> $object = new Grandchild();
<add> $object->mergeVars(['nestedProperty'], ['associative' => ['nestedProperty']]);
<add>
<add> $expected = [
<add> 'Red' => [
<add> 'apple' => 'mcintosh',
<add> 'citrus' => 'blood orange',
<add> ],
<add> 'Green' => [
<add> 'citrus' => 'key lime',
<add> ],
<add> ];
<add> $this->assertEquals($expected, $object->nestedProperty);
<add> }
<add>
<ide> /**
<ide> * Test merging vars with mixed modes.
<add> *
<add> * @return void
<ide> */
<ide> public function testMergeVarsMixedModes() {
<ide> $object = new Grandchild(); | 1 |
Ruby | Ruby | fix hombrew typo | 95f226cf51ae3df39ed3930cf27a77e077a177f0 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> # Unbrewed uses the PREFIX, which will exist
<ide> # Things below use the CELLAR, which doesn't until the first formula is installed.
<ide> unless HOMEBREW_CELLAR.exist?
<del> raise NoSuchKegError, Hombrew.args.named.first if args.named.present?
<add> raise NoSuchKegError, args.named.first if args.named.present?
<ide>
<ide> return
<ide> end | 1 |
Ruby | Ruby | improve bottle error messages | 4b0e663c2c36db0870688e99fc8a28a758968021 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_filename f, bottle_version=nil
<ide> end
<ide>
<ide> def install_bottle? f
<del> return true if ARGV.include? '--install-bottle'
<add> return true if ARGV.include? '--install-bottle' and MacOS.bottles_supported?(true)
<ide> return true if f.downloader and defined? f.downloader.local_bottle_path \
<ide> and f.downloader.local_bottle_path
<ide> not ARGV.build_from_source? \
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def build_32_bit?
<ide> end
<ide>
<ide> def build_bottle?
<del> include? '--build-bottle' and MacOS.bottles_supported?
<add> include? '--build-bottle' and MacOS.bottles_supported?(true)
<ide> end
<ide>
<ide> def build_from_source?
<ide><path>Library/Homebrew/macos.rb
<ide> def pkgutil_info id
<ide> `/usr/sbin/pkgutil --pkg-info "#{id}" 2>/dev/null`.strip
<ide> end
<ide>
<del> def bottles_supported?
<add> def bottles_supported? raise_if_failed=false
<ide> # We support bottles on all versions of OS X except 32-bit Snow Leopard.
<del> (Hardware.is_64_bit? or not MacOS.version >= :snow_leopard) \
<del> and HOMEBREW_PREFIX.to_s == '/usr/local' \
<del> and HOMEBREW_CELLAR.to_s == '/usr/local/Cellar' \
<add> unless Hardware.is_64_bit? or MacOS.version >= :snow_leopard
<add> return false unless raise_if_failed
<add> raise "Bottles are not supported on 32-bit Snow Leopard."
<add> end
<add>
<add> unless HOMEBREW_PREFIX.to_s == '/usr/local'
<add> return false unless raise_if_failed
<add> raise "Bottles are only supported with a /usr/local prefix."
<add> end
<add>
<add> unless HOMEBREW_CELLAR.to_s == '/usr/local/Cellar'
<add> return false unless raise_if_failed
<add> raise "Bottles are only supported with a /usr/local/Cellar cellar."
<add> end
<add>
<add> true
<ide> end
<ide> end
<ide> | 3 |
Python | Python | use get_flags_version to set version cmd flags | cb082e0ec4da42ac1f2022754d98c0a03a38d020 | <ide><path>numpy/distutils/fcompiler/__init__.py
<ide> def customize(self, dist = None):
<ide> # methods may call self.get_version.
<ide> vers_cmd = self.command_vars.version_cmd
<ide> if vers_cmd:
<del> vflags = self.flag_vars.version
<add> vflags = self.get_flags_version()
<add> assert None not in vflags,`vflags`
<ide> self.set_executables(version_cmd=[vers_cmd]+vflags)
<ide>
<ide> f77flags = [] | 1 |
Ruby | Ruby | use an encapsulated factory method | a2d55dfdc3878521793a8472c00b7a648ff21ae3 | <ide><path>lib/action_cable/connection/base.rb
<ide> def initialize(server, env)
<ide>
<ide> @server, @env = server, env
<ide>
<del> @logger = TaggedLoggerProxy.new(server.logger, tags: log_tags)
<add> @logger = initialize_tagged_logger
<ide>
<ide> @heartbeat = ActionCable::Connection::Heartbeat.new(self)
<ide> @subscriptions = ActionCable::Connection::Subscriptions.new(self)
<ide> def finished_request_message
<ide> end
<ide>
<ide>
<del> def log_tags
<del> server.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize }
<add> # Tags are declared in the server but computed in the connection. This allows us per-connection tailored tags.
<add> def initialize_tagged_logger
<add> TaggedLoggerProxy.new server.logger,
<add> tags: server.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize }
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | apply fixes from styleci | a1226cb5ad3b4fae45b8d20d4f8d9275c759b7d2 | <ide><path>tests/Integration/Queue/JobChainingTest.php
<ide> public function tearDown()
<ide> public function test_jobs_can_be_chained_on_success()
<ide> {
<ide> JobChainingTestFirstJob::dispatch()->chain([
<del> new JobChainingTestSecondJob
<add> new JobChainingTestSecondJob,
<ide> ]);
<ide>
<ide> $this->assertTrue(JobChainingTestFirstJob::$ran);
<ide> public function test_jobs_can_be_chained_on_success()
<ide> public function test_jobs_can_be_chained_via_queue()
<ide> {
<ide> Queue::connection('sync')->push((new JobChainingTestFirstJob)->chain([
<del> new JobChainingTestSecondJob
<add> new JobChainingTestSecondJob,
<ide> ]));
<ide>
<ide> $this->assertTrue(JobChainingTestFirstJob::$ran);
<ide> public function test_jobs_can_be_chained_via_queue()
<ide> public function test_second_job_is_not_fired_if_first_was_already_deleted()
<ide> {
<ide> Queue::connection('sync')->push((new JobChainingTestFailingJob)->chain([
<del> new JobChainingTestSecondJob
<add> new JobChainingTestSecondJob,
<ide> ]));
<ide>
<ide> $this->assertFalse(JobChainingTestSecondJob::$ran); | 1 |
Ruby | Ruby | resolve hash with `url` key as a `urlconfig` | 94256a0aeb57e4031b1bbe5d782ed29e31fdd1ec | <ide><path>activerecord/lib/active_record/connection_adapters/resolver.rb
<ide> def resolve(config_or_env, pool_name = nil)
<ide> when String
<ide> DatabaseConfigurations::UrlConfig.new(env, "primary", config_or_env)
<ide> when Hash
<del> DatabaseConfigurations::HashConfig.new(env, "primary", config_or_env)
<add> resolve_hash_configuration(env, config_or_env.symbolize_keys)
<ide> when DatabaseConfigurations::DatabaseConfig
<ide> config_or_env
<ide> else
<ide> def resolve(config_or_env, pool_name = nil)
<ide> end
<ide>
<ide> private
<add> # Resolve a hash to a valid configuration object. This method will
<add> # either return a HashConfig, or a UrlConfig if the passed Hash
<add> # contains a `:url` key.
<add> def resolve_hash_configuration(env, config)
<add> if config.has_key?(:url)
<add> url = config[:url]
<add> config_without_url = config.dup
<add> config_without_url.delete :url
<add> DatabaseConfigurations::UrlConfig.new(env, "primary", url, config)
<add> else
<add> DatabaseConfigurations::HashConfig.new(env, "primary", config)
<add> end
<add> end
<add>
<ide> # Takes the environment such as +:production+ or +:development+ and a
<ide> # pool name the corresponds to the name given by the connection pool
<ide> # to the connection. That pool name is merged into the hash with the
<ide><path>activerecord/lib/active_record/database_configurations/hash_config.rb
<ide> class HashConfig < DatabaseConfig
<ide> def initialize(env_name, spec_name, config)
<ide> super(env_name, spec_name)
<ide> @config = config.symbolize_keys
<del>
<del> resolve_url_key
<ide> end
<ide>
<ide> def configuration_hash
<ide> def replica?
<ide> def migrations_paths
<ide> configuration_hash[:migrations_paths]
<ide> end
<del>
<del> private
<del> def resolve_url_key
<del> if configuration_hash[:url] && !configuration_hash[:url].match?(/^jdbc:/)
<del> connection_hash = ConnectionUrlResolver.new(configuration_hash[:url]).to_hash
<del> configuration_hash.merge!(connection_hash)
<del> end
<del> end
<ide> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | move `normalizeinjectionshash` definition to debug | 774a192ece628d08a3fcd877f8395f858aa33972 | <ide><path>packages/container/lib/container.js
<ide> class FactoryManager {
<ide> }
<ide>
<ide> toString() {
<del> if (!this.madeToString) {
<add> if (this.madeToString === undefined) {
<ide> this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
<ide> }
<ide>
<ide><path>packages/container/lib/registry.js
<ide> Registry.prototype = {
<ide> return VALID_FULL_NAME_REGEXP.test(fullName);
<ide> },
<ide>
<del> normalizeInjectionsHash(hash) {
<del> let injections = [];
<del>
<del> for (let key in hash) {
<del> if (hash.hasOwnProperty(key)) {
<del> assert(`Expected a proper full name, given '${hash[key]}'`, this.validateFullName(hash[key]));
<del>
<del> injections.push({
<del> property: key,
<del> fullName: hash[key]
<del> });
<del> }
<del> }
<del>
<del> return injections;
<del> },
<del>
<ide> getInjections(fullName) {
<ide> let injections = this._injections[fullName] || [];
<ide> if (this.fallback) {
<ide> function deprecateResolverFunction(registry) {
<ide> }
<ide>
<ide> if (DEBUG) {
<add> Registry.prototype.normalizeInjectionsHash = function(hash) {
<add> let injections = [];
<add>
<add> for (let key in hash) {
<add> if (hash.hasOwnProperty(key)) {
<add> assert(`Expected a proper full name, given '${hash[key]}'`, this.validateFullName(hash[key]));
<add>
<add> injections.push({
<add> property: key,
<add> fullName: hash[key]
<add> });
<add> }
<add> }
<add>
<add> return injections;
<add> }
<add>
<ide> Registry.prototype.validateInjections = function(injections) {
<ide> if (!injections) { return; }
<ide> | 2 |
Go | Go | normalize comment formatting | 0b155db389715aaf60aef50e4015d3a4e0768c5f | <ide><path>pkg/jsonmessage/jsonmessage.go
<ide> func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error {
<ide> clearLine(out)
<ide> endl = "\r"
<ide> fmt.Fprint(out, endl)
<del> } else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal
<add> } else if jm.Progress != nil && jm.Progress.String() != "" { // disable progressbar in non-terminal
<ide> return nil
<ide> }
<ide> if jm.TimeNano != 0 { | 1 |
Javascript | Javascript | fix crypto test case to use correct encoding | 5160dd0365a1493a0238a2119f2a7c185db49b46 | <ide><path>test/parallel/test-crypto-authenticated.js
<ide> for (const test of TEST_CASES) {
<ide> assert.strictEqual(msg, test.plain);
<ide> } else {
<ide> // assert that final throws if input data could not be verified!
<del> assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth);
<add> assert.throws(function() { decrypt.final('hex'); }, errMessages.auth);
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | change compiled path | 203a0c3ba176dba6ddf2e4aecd3648452ca2273c | <ide><path>config/view.php
<ide> |
<ide> */
<ide>
<del> 'compiled' => realpath(storage_path().'/framework/views'),
<add> 'compiled' => realpath(storage_path().'/framework/templates'),
<ide>
<ide> ]; | 1 |
PHP | PHP | move httpclienttrait to http package | 6a5626e943689302c46c97cfc7af29097bdf78d4 | <ide><path>src/Http/TestSuite/HttpClientTrait.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http\TestSuite;
<add>
<add>use Cake\Http\Client;
<add>use Cake\Http\Client\Response;
<add>
<add>/**
<add> * Define mock responses and have mocks automatically cleared.
<add> */
<add>trait HttpClientTrait
<add>{
<add> /**
<add> * Resets mocked responses
<add> *
<add> * @after
<add> * @return void
<add> */
<add> public function cleanupMockResponses(): void
<add> {
<add> Client::clearMockResponses();
<add> }
<add>
<add> /**
<add> * Create a new response.
<add> *
<add> * @param int $code The response code to use. Defaults to 200
<add> * @param array<string> $headers A list of headers for the response. Example `Content-Type: application/json`
<add> * @param string $body The body for the response.
<add> * @return \Cake\Http\Client\Response
<add> */
<add> public function newClientResponse(int $code = 200, array $headers = [], string $body = ''): Response
<add> {
<add> $headers = array_merge(["HTTP/1.1 {$code}"], $headers);
<add>
<add> return new Response($headers, $body);
<add> }
<add>
<add> /**
<add> * Add a mock response for a POST request.
<add> *
<add> * @param string $url The URL to mock
<add> * @param \Cake\Http\Client\Response $response The response for the mock.
<add> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<add> * @return void
<add> */
<add> public function mockClientPost(string $url, Response $response, array $options = []): void
<add> {
<add> Client::addMockResponse('POST', $url, $response, $options);
<add> }
<add>
<add> /**
<add> * Add a mock response for a GET request.
<add> *
<add> * @param string $url The URL to mock
<add> * @param \Cake\Http\Client\Response $response The response for the mock.
<add> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<add> * @return void
<add> */
<add> public function mockClientGet(string $url, Response $response, array $options = []): void
<add> {
<add> Client::addMockResponse('GET', $url, $response, $options);
<add> }
<add>
<add> /**
<add> * Add a mock response for a PATCH request.
<add> *
<add> * @param string $url The URL to mock
<add> * @param \Cake\Http\Client\Response $response The response for the mock.
<add> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<add> * @return void
<add> */
<add> public function mockClientPatch(string $url, Response $response, array $options = []): void
<add> {
<add> Client::addMockResponse('PATCH', $url, $response, $options);
<add> }
<add>
<add> /**
<add> * Add a mock response for a PUT request.
<add> *
<add> * @param string $url The URL to mock
<add> * @param \Cake\Http\Client\Response $response The response for the mock.
<add> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<add> * @return void
<add> */
<add> public function mockClientPut(string $url, Response $response, array $options = []): void
<add> {
<add> Client::addMockResponse('PUT', $url, $response, $options);
<add> }
<add>
<add> /**
<add> * Add a mock response for a DELETE request.
<add> *
<add> * @param string $url The URL to mock
<add> * @param \Cake\Http\Client\Response $response The response for the mock.
<add> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<add> * @return void
<add> */
<add> public function mockClientDelete(string $url, Response $response, array $options = []): void
<add> {
<add> Client::addMockResponse('DELETE', $url, $response, $options);
<add> }
<add>}
<ide><path>src/TestSuite/HttpClientTrait.php
<ide> <?php
<ide> declare(strict_types=1);
<ide>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 4.3.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\TestSuite;
<add>use Cake\Http\TestSuite\HttpClientTrait;
<ide>
<del>use Cake\Http\Client;
<del>use Cake\Http\Client\Response;
<del>
<del>/**
<del> * Define mock responses and have mocks automatically cleared.
<del> */
<del>trait HttpClientTrait
<del>{
<del> /**
<del> * Resets mocked responses
<del> *
<del> * @after
<del> * @return void
<del> */
<del> public function cleanupMockResponses(): void
<del> {
<del> Client::clearMockResponses();
<del> }
<del>
<del> /**
<del> * Create a new response.
<del> *
<del> * @param int $code The response code to use. Defaults to 200
<del> * @param array<string> $headers A list of headers for the response. Example `Content-Type: application/json`
<del> * @param string $body The body for the response.
<del> * @return \Cake\Http\Client\Response
<del> */
<del> public function newClientResponse(int $code = 200, array $headers = [], string $body = ''): Response
<del> {
<del> $headers = array_merge(["HTTP/1.1 {$code}"], $headers);
<del>
<del> return new Response($headers, $body);
<del> }
<del>
<del> /**
<del> * Add a mock response for a POST request.
<del> *
<del> * @param string $url The URL to mock
<del> * @param \Cake\Http\Client\Response $response The response for the mock.
<del> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<del> * @return void
<del> */
<del> public function mockClientPost(string $url, Response $response, array $options = []): void
<del> {
<del> Client::addMockResponse('POST', $url, $response, $options);
<del> }
<del>
<del> /**
<del> * Add a mock response for a GET request.
<del> *
<del> * @param string $url The URL to mock
<del> * @param \Cake\Http\Client\Response $response The response for the mock.
<del> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<del> * @return void
<del> */
<del> public function mockClientGet(string $url, Response $response, array $options = []): void
<del> {
<del> Client::addMockResponse('GET', $url, $response, $options);
<del> }
<del>
<del> /**
<del> * Add a mock response for a PATCH request.
<del> *
<del> * @param string $url The URL to mock
<del> * @param \Cake\Http\Client\Response $response The response for the mock.
<del> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<del> * @return void
<del> */
<del> public function mockClientPatch(string $url, Response $response, array $options = []): void
<del> {
<del> Client::addMockResponse('PATCH', $url, $response, $options);
<del> }
<del>
<del> /**
<del> * Add a mock response for a PUT request.
<del> *
<del> * @param string $url The URL to mock
<del> * @param \Cake\Http\Client\Response $response The response for the mock.
<del> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<del> * @return void
<del> */
<del> public function mockClientPut(string $url, Response $response, array $options = []): void
<del> {
<del> Client::addMockResponse('PUT', $url, $response, $options);
<del> }
<del>
<del> /**
<del> * Add a mock response for a DELETE request.
<del> *
<del> * @param string $url The URL to mock
<del> * @param \Cake\Http\Client\Response $response The response for the mock.
<del> * @param array<string, mixed> $options Additional options. See Client::addMockResponse()
<del> * @return void
<del> */
<del> public function mockClientDelete(string $url, Response $response, array $options = []): void
<del> {
<del> Client::addMockResponse('DELETE', $url, $response, $options);
<del> }
<del>}
<add>class_alias(HttpClientTrait::class, 'Cake\TestSuite\HttpClientTrait');
<add><path>tests/TestCase/Http/TestSuite/HttpClientTraitTest.php
<del><path>tests/TestCase/TestSuite/HttpClientTraitTest.php
<ide> * @since 4.3.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Test\TestCase\TestSuite;
<add>namespace Cake\Test\TestCase\Http\TestSuite;
<ide>
<ide> use Cake\Http\Client;
<del>use Cake\TestSuite\HttpClientTrait;
<add>use Cake\Http\TestSuite\HttpClientTrait;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> class HttpClientTraitTest extends TestCase | 3 |
Ruby | Ruby | require a class for cache computations | 64669c11174162560aa490b57f2f8b0e45620fc7 | <ide><path>activerecord/lib/active_record/associations/preloader.rb
<ide> class Preloader #:nodoc:
<ide> def initialize(records, associations, preload_scope = nil)
<ide> @records = Array.wrap(records).compact.uniq
<ide> @associations = Array.wrap(associations)
<del> @preload_scope = preload_scope || Relation.create(nil, nil)
<add> @preload_scope = preload_scope || Relation.new(nil, nil)
<ide> end
<ide>
<ide> def run
<ide><path>activerecord/lib/active_record/relation/delegation.rb
<ide> def create(klass, *args)
<ide> # Cache the constants in @@subclasses because looking them up via const_get
<ide> # make instantiation significantly slower.
<ide> def relation_class_for(klass)
<del> if klass && (klass_name = klass.name)
<add> klass_name = klass.name
<add>
<add> if klass_name
<ide> my_cache = @@subclasses.compute_if_absent(self) { ThreadSafe::Cache.new }
<ide> # This hash is keyed by klass.name to avoid memory leaks in development mode
<ide> my_cache.compute_if_absent(klass_name) do | 2 |
Python | Python | fix a typo | 7f678aaf5a066ff71289743a64e5cd685b660428 | <ide><path>flask/exthook.py
<ide> def is_important_frame(self, important_module, tb):
<ide> if module_name == important_module:
<ide> return True
<ide>
<del> # Some python versions will will clean up modules so early that the
<add> # Some python versions will clean up modules so early that the
<ide> # module name at that point is no longer set. Try guessing from
<ide> # the filename then.
<ide> filename = os.path.abspath(tb.tb_frame.f_code.co_filename) | 1 |
Javascript | Javascript | remove redundant initialisation | ce7425f2692abaa1a6b3a16828f7aa343657bef7 | <ide><path>src/extras/helpers/DirectionalLightHelper.js
<ide> THREE.DirectionalLightHelper = function ( light, sphereSize ) {
<ide> this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
<ide> this.targetLine.properties.isGizmo = true;
<ide>
<del> }
<del> else {
<del>
<del> this.targetSphere = null;
<del>
<ide> }
<ide>
<ide> //
<ide><path>src/extras/helpers/SpotLightHelper.js
<ide> THREE.SpotLightHelper = function ( light, sphereSize ) {
<ide> this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
<ide> this.targetLine.properties.isGizmo = true;
<ide>
<del> }
<del> else {
<del>
<del> this.targetSphere = null;
<del>
<ide> }
<ide>
<ide> // | 2 |
Java | Java | fix classcastexception in reactmodulespecprocessor | 379b60d5e8a2418f438e4291bf5ba140778db5bc | <ide><path>ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java
<ide> public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
<ide> Set<? extends Element> reactModuleListElements = roundEnv.getElementsAnnotatedWith(
<ide> ReactModuleList.class);
<ide> for (Element reactModuleListElement : reactModuleListElements) {
<add> if (!(reactModuleListElement instanceof TypeElement)) {
<add> continue;
<add> }
<add>
<ide> TypeElement typeElement = (TypeElement) reactModuleListElement;
<ide> ReactModuleList reactModuleList = typeElement.getAnnotation(ReactModuleList.class);
<ide> if (reactModuleList == null) { | 1 |
Python | Python | fix parsing of hostvirtual record names | 11b71d296b6a256c2660530a3630671efbe52501 | <ide><path>libcloud/dns/drivers/hostvirtual.py
<ide> def _to_records(self, items, zone=None):
<ide> def _to_record(self, item, zone=None):
<ide> extra = {'ttl': item['ttl']}
<ide> type = self._string_to_record_type(item['type'])
<del> record = Record(id=item['id'], name=item['name'],
<add> name = item['name'][:-len(zone.domain) - 1]
<add> record = Record(id=item['id'], name=name,
<ide> type=type, data=item['content'],
<ide> zone=zone, driver=self, extra=extra)
<ide> return record
<ide><path>libcloud/test/dns/test_hostvirtual.py
<ide> def test_list_records(self):
<ide> self.assertEqual(len(records), 3)
<ide>
<ide> record = records[1]
<del> self.assertEqual(record.name, 'www.t.com')
<add> self.assertEqual(record.name, 'www')
<ide> self.assertEqual(record.id, '300719')
<ide> self.assertEqual(record.type, RecordType.A)
<ide> self.assertEqual(record.data, '208.111.35.173')
<ide> def test_get_zone(self):
<ide> def test_get_record(self):
<ide> record = self.driver.get_record(zone_id='47234', record_id='300377')
<ide> self.assertEqual(record.id, '300377')
<del> self.assertEqual(record.name, '*.t.com')
<add> self.assertEqual(record.name, '*')
<ide> self.assertEqual(record.type, RecordType.CNAME)
<ide> self.assertEqual(record.data, 't.com')
<ide>
<ide> def test_update_zone(self):
<ide> self.assertEqual(updated_zone.type, zone.type)
<ide> self.assertEqual(updated_zone.ttl, '3600')
<ide>
<add> def test_create_record_no_name(self):
<add> zone = self.driver.list_zones()[0]
<add> record = self.driver.create_record(
<add> name='', zone=zone,
<add> type=RecordType.A, data='127.0.0.1'
<add> )
<add>
<add> self.assertEqual(record.id, '300377')
<add> self.assertEqual(record.name, '')
<add> self.assertEqual(record.zone, zone)
<add> self.assertEqual(record.type, RecordType.A)
<add> self.assertEqual(record.data, '127.0.0.1')
<add>
<ide> def test_create_record(self):
<ide> zone = self.driver.list_zones()[0]
<ide> record = self.driver.create_record( | 2 |
Python | Python | reduce the time spent for the tf slow tests | 2acae50a0c32b52f5d0b83cd06c75b98a0d44233 | <ide><path>src/transformers/modeling_tf_utils.py
<ide> def booleans_processing(config, **kwargs):
<ide>
<ide> if "use_cache" in kwargs:
<ide> final_booleans["use_cache"] = kwargs["use_cache"] if kwargs["use_cache"] is not None else config.use_cache
<del>
<ide> else:
<ide> if (
<ide> kwargs["output_attentions"] is not None
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_saved_model_creation(self):
<ide> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<ide> self.assertTrue(os.path.exists(saved_model_dir))
<ide>
<add> @slow
<add> def test_saved_model_creation_extended(self):
<add> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<add> config.output_hidden_states = True
<add> config.output_attentions = True
<add>
<add> if hasattr(config, "use_cache"):
<add> config.use_cache = True
<add>
<add> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length)
<add> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<add>
<add> for model_class in self.all_model_classes:
<add> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<add> model = model_class(config)
<add> num_out = len(model(class_inputs_dict))
<add>
<add> with tempfile.TemporaryDirectory() as tmpdirname:
<add> model.save_pretrained(tmpdirname, saved_model=True)
<add> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<add> model = tf.keras.models.load_model(saved_model_dir)
<add> outputs = model(class_inputs_dict)
<add>
<add> if self.is_encoder_decoder:
<add> output_hidden_states = outputs["encoder_hidden_states"]
<add> output_attentions = outputs["encoder_attentions"]
<add> else:
<add> output_hidden_states = outputs["hidden_states"]
<add> output_attentions = outputs["attentions"]
<add>
<add> self.assertEqual(len(outputs), num_out)
<add>
<add> expected_num_layers = getattr(
<add> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<add> )
<add>
<add> self.assertEqual(len(output_hidden_states), expected_num_layers)
<add> self.assertListEqual(
<add> list(output_hidden_states[0].shape[-2:]),
<add> [self.model_tester.seq_length, self.model_tester.hidden_size],
<add> )
<add>
<add> self.assertEqual(len(output_attentions), self.model_tester.num_hidden_layers)
<add> self.assertListEqual(
<add> list(output_attentions[0].shape[-3:]),
<add> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<add> )
<add>
<ide> def test_onnx_compliancy(self):
<ide> if not self.test_onnx:
<ide> return
<ide> def test_onnx_runtime_optimize(self):
<ide>
<ide> onnxruntime.InferenceSession(onnx_model.SerializeToString())
<ide>
<del> @slow
<del> def test_saved_model_creation_extended(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.output_hidden_states = True
<del> config.output_attentions = True
<del>
<del> if hasattr(config, "use_cache"):
<del> config.use_cache = True
<del>
<del> for model_class in self.all_model_classes:
<del> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<del> model = model_class(config)
<del>
<del> model(class_inputs_dict)
<del>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<del> model.save_pretrained(tmpdirname, saved_model=True)
<del> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<del> self.assertTrue(os.path.exists(saved_model_dir))
<del>
<del> @slow
<del> def test_saved_model_with_hidden_states_output(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.output_hidden_states = True
<del> config.output_attentions = False
<del>
<del> if hasattr(config, "use_cache"):
<del> config.use_cache = False
<del>
<del> for model_class in self.all_model_classes:
<del> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<del> model = model_class(config)
<del> num_out = len(model(class_inputs_dict))
<del>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<del> model.save_pretrained(tmpdirname, saved_model=True)
<del> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<del> model = tf.keras.models.load_model(saved_model_dir)
<del> outputs = model(class_inputs_dict)
<del>
<del> if self.is_encoder_decoder:
<del> output = outputs["encoder_hidden_states"]
<del> else:
<del> output = outputs["hidden_states"]
<del>
<del> self.assertEqual(len(outputs), num_out)
<del>
<del> expected_num_layers = getattr(
<del> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<del> )
<del>
<del> self.assertEqual(len(output), expected_num_layers)
<del> self.assertListEqual(
<del> list(output[0].shape[-2:]),
<del> [self.model_tester.seq_length, self.model_tester.hidden_size],
<del> )
<del>
<del> @slow
<del> def test_saved_model_with_attentions_output(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.output_attentions = True
<del> config.output_hidden_states = False
<del>
<del> if hasattr(config, "use_cache"):
<del> config.use_cache = False
<del>
<del> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length)
<del> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<del>
<del> for model_class in self.all_model_classes:
<del> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<del> model = model_class(config)
<del> num_out = len(model(class_inputs_dict))
<del>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<del> model.save_pretrained(tmpdirname, saved_model=True)
<del> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<del> model = tf.keras.models.load_model(saved_model_dir)
<del> outputs = model(class_inputs_dict)
<del>
<del> if self.is_encoder_decoder:
<del> output = outputs["encoder_attentions"]
<del> else:
<del> output = outputs["attentions"]
<del>
<del> self.assertEqual(len(outputs), num_out)
<del> self.assertEqual(len(output), self.model_tester.num_hidden_layers)
<del> self.assertListEqual(
<del> list(output[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del>
<ide> def test_mixed_precision(self):
<ide> tf.keras.mixed_precision.experimental.set_policy("mixed_float16")
<ide>
<ide> def test_train_pipeline_custom_model(self):
<ide> shared = TFSharedEmbeddings(self.model_tester.vocab_size, self.model_tester.hidden_size, name="shared")
<ide> config.use_cache = False
<ide> main_layer = main_layer_class(config, embed_tokens=shared)
<del> del inputs_dict["use_cache"]
<ide> else:
<ide> main_layer = main_layer_class(config)
<ide>
<ide><path>tests/test_modeling_tf_convbert.py
<ide> def test_for_token_classification(self):
<ide> self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
<ide>
<ide> @slow
<del> def test_saved_model_with_attentions_output(self):
<add> def test_saved_model_creation_extended(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<add> config.output_hidden_states = True
<ide> config.output_attentions = True
<del> config.output_hidden_states = False
<ide>
<ide> if hasattr(config, "use_cache"):
<del> config.use_cache = False
<add> config.use_cache = True
<ide>
<ide> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length)
<ide> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<ide> def test_saved_model_with_attentions_output(self):
<ide>
<ide> with tempfile.TemporaryDirectory() as tmpdirname:
<ide> model.save_pretrained(tmpdirname, saved_model=True)
<del> model = tf.keras.models.load_model(os.path.join(tmpdirname, "saved_model", "1"))
<add> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<add> model = tf.keras.models.load_model(saved_model_dir)
<ide> outputs = model(class_inputs_dict)
<del> output = outputs["attentions"]
<add>
<add> if self.is_encoder_decoder:
<add> output_hidden_states = outputs["encoder_hidden_states"]
<add> output_attentions = outputs["encoder_attentions"]
<add> else:
<add> output_hidden_states = outputs["hidden_states"]
<add> output_attentions = outputs["attentions"]
<ide>
<ide> self.assertEqual(len(outputs), num_out)
<del> self.assertEqual(len(output), self.model_tester.num_hidden_layers)
<add>
<add> expected_num_layers = getattr(
<add> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<add> )
<add>
<add> self.assertEqual(len(output_hidden_states), expected_num_layers)
<add> self.assertListEqual(
<add> list(output_hidden_states[0].shape[-2:]),
<add> [self.model_tester.seq_length, self.model_tester.hidden_size],
<add> )
<add>
<add> self.assertEqual(len(output_attentions), self.model_tester.num_hidden_layers)
<ide> self.assertListEqual(
<del> list(output[0].shape[-3:]),
<add> list(output_attentions[0].shape[-3:]),
<ide> [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],
<ide> )
<ide>
<ide><path>tests/test_modeling_tf_led.py
<ide> def test_xla_mode(self):
<ide> # TODO JP: Make LED XLA compliant
<ide> pass
<ide>
<del> def test_saved_model_with_attentions_output(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<del> @slow
<del> def test_saved_model_with_hidden_states_output(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<ide> def test_saved_model_creation(self):
<ide> # This test is too long (>30sec) and makes fail the CI
<ide> pass
<ide>
<del> @slow
<del> def test_saved_model_creation_extended(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<ide>
<ide> def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
<ide> """If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
<ide><path>tests/test_modeling_tf_longformer.py
<ide> def test_for_multiple_choice(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
<ide>
<del> @slow
<del> def test_saved_model_with_attentions_output(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<del> @slow
<del> def test_saved_model_with_hidden_states_output(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<ide> def test_saved_model_creation(self):
<ide> # This test is too long (>30sec) and makes fail the CI
<ide> pass
<ide>
<del> @slow
<del> def test_saved_model_creation_extended(self):
<del> # Temporarily disable this test in order to find
<del> # how to better handle it without timing out the CI
<del> pass
<del>
<ide> def test_mixed_precision(self):
<ide> # TODO JP: Make Longformer float16 compliant
<ide> pass
<ide><path>tests/test_modeling_tf_lxmert.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<add>import os
<ide> import tempfile
<ide> import unittest
<ide>
<ide> def test_mixed_precision(self):
<ide> pass
<ide>
<ide> @slow
<del> def test_saved_model_with_hidden_states_output(self):
<add> def test_saved_model_creation_extended(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide> config.output_hidden_states = True
<add> config.output_attentions = True
<add>
<add> if hasattr(config, "use_cache"):
<add> config.use_cache = True
<add>
<add> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length)
<add> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<ide>
<ide> for model_class in self.all_model_classes:
<ide> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<ide> model = model_class(config)
<del> model._saved_model_inputs_spec = None
<del> model._set_save_spec(class_inputs_dict)
<add> num_out = len(model(class_inputs_dict))
<ide>
<ide> with tempfile.TemporaryDirectory() as tmpdirname:
<del> tf.saved_model.save(model, tmpdirname)
<del> model = tf.keras.models.load_model(tmpdirname)
<add> model.save_pretrained(tmpdirname, saved_model=True)
<add> saved_model_dir = os.path.join(tmpdirname, "saved_model", "1")
<add> model = tf.keras.models.load_model(saved_model_dir)
<ide> outputs = model(class_inputs_dict)
<del>
<ide> language_hidden_states = outputs["language_hidden_states"]
<ide> vision_hidden_states = outputs["vision_hidden_states"]
<add> language_attentions = outputs["language_attentions"]
<add> vision_attentions = outputs["vision_attentions"]
<add> cross_encoder_attentions = outputs["cross_encoder_attentions"]
<add>
<add> self.assertEqual(len(outputs), num_out)
<ide>
<ide> self.assertEqual(len(language_hidden_states), self.model_tester.num_hidden_layers["language"] + 1)
<ide> self.assertEqual(len(vision_hidden_states), self.model_tester.num_hidden_layers["vision"] + 1)
<ide> def test_saved_model_with_hidden_states_output(self):
<ide> [num_visual_features, self.model_tester.hidden_size],
<ide> )
<ide>
<del> @slow
<del> def test_saved_model_with_attentions_output(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.output_attentions = True
<del>
<del> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length)
<del> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<del>
<del> for model_class in self.all_model_classes:
<del> class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
<del> model = model_class(config)
<del> model._saved_model_inputs_spec = None
<del> model._set_save_spec(class_inputs_dict)
<del>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<del> tf.saved_model.save(model, tmpdirname)
<del> model = tf.keras.models.load_model(tmpdirname)
<del> outputs = model(class_inputs_dict)
<del>
<del> language_attentions = outputs["language_attentions"]
<del> vision_attentions = outputs["vision_attentions"]
<del> cross_encoder_attentions = outputs["cross_encoder_attentions"]
<del>
<ide> self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers["language"])
<ide> self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers["vision"])
<ide> self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers["cross_encoder"])
<ide><path>tests/test_modeling_tf_t5.py
<ide> def prepare_config_and_inputs_for_common(self):
<ide> "input_ids": input_ids,
<ide> "decoder_input_ids": input_ids,
<ide> "decoder_attention_mask": input_mask,
<del> "use_cache": False,
<ide> }
<ide> return config, inputs_dict
<ide> | 7 |
Text | Text | fix broken link | f9453d15e5342bb5a60498916635f1a5e5c6cb14 | <ide><path>README.md
<ide> You can use it to experiment with completions generated by `GPT2Model`, `Transfo
<ide>
<ide> > “🦄 Write with transformer is to writing what calculators are to calculus.”
<ide>
<del>
<add>
<ide>
<ide> ## Quick tour
<ide> | 1 |
Python | Python | add support for `np.dtype(ctypes.union)` | 1466e788a43b8d4356fe35951bf0c3b0aedb554f | <ide><path>numpy/core/_dtype_ctypes.py
<ide> def dtype_from_ctypes_scalar(t):
<ide> return np.dtype(t._type_)
<ide>
<ide>
<add>def dtype_from_ctypes_union(t):
<add> formats = []
<add> offsets = []
<add> names = []
<add> for fname, ftyp in t._fields_:
<add> names.append(fname)
<add> formats.append(dtype_from_ctypes_type(ftyp))
<add> offsets.append(0) # Union fields are offset to 0
<add>
<add> return np.dtype(dict(
<add> formats=formats,
<add> offsets=offsets,
<add> names=names,
<add> itemsize=ctypes.sizeof(t)))
<add>
<add>
<ide> def dtype_from_ctypes_type(t):
<ide> """
<ide> Construct a dtype object from a ctypes type
<ide> def dtype_from_ctypes_type(t):
<ide> elif issubclass(t, _ctypes.Structure):
<ide> return _from_ctypes_structure(t)
<ide> elif issubclass(t, _ctypes.Union):
<del> # TODO
<del> raise NotImplementedError(
<del> "conversion from ctypes.Union types like {} to dtype"
<del> .format(t.__name__))
<add> return dtype_from_ctypes_union(t)
<ide> elif isinstance(t._type_, str):
<ide> return dtype_from_ctypes_scalar(t)
<ide> else:
<ide><path>numpy/core/tests/test_dtype.py
<ide> def test_pointer(self):
<ide> p_uint8 = ctypes.POINTER(ctypes.c_uint8)
<ide> assert_raises(TypeError, np.dtype, p_uint8)
<ide>
<del> @pytest.mark.xfail(
<del> reason="Unions are not implemented",
<del> raises=NotImplementedError)
<ide> def test_union(self):
<ide> class Union(ctypes.Union):
<ide> _fields_ = [
<ide> class Union(ctypes.Union):
<ide> ))
<ide> self.check(Union, expected)
<ide>
<add> def test_union_with_struct_packed(self):
<add> class Struct(ctypes.Structure):
<add> _pack_ = 1
<add> _fields_ = [
<add> ('one', ctypes.c_uint8),
<add> ('two', ctypes.c_uint32)
<add> ]
<add>
<add> class Union(ctypes.Union):
<add> _fields_ = [
<add> ('a', ctypes.c_uint8),
<add> ('b', ctypes.c_uint16),
<add> ('c', ctypes.c_uint32),
<add> ('d', Struct),
<add> ]
<add> expected = np.dtype(dict(
<add> names=['a', 'b', 'c', 'd'],
<add> formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
<add> offsets=[0, 0, 0, 0],
<add> itemsize=ctypes.sizeof(Union)
<add> ))
<add> self.check(Union, expected)
<add>
<add> def test_union_packed(self):
<add> class Struct(ctypes.Structure):
<add> _fields_ = [
<add> ('one', ctypes.c_uint8),
<add> ('two', ctypes.c_uint32)
<add> ]
<add> _pack_ = 1
<add> class Union(ctypes.Union):
<add> _pack_ = 1
<add> _fields_ = [
<add> ('a', ctypes.c_uint8),
<add> ('b', ctypes.c_uint16),
<add> ('c', ctypes.c_uint32),
<add> ('d', Struct),
<add> ]
<add> expected = np.dtype(dict(
<add> names=['a', 'b', 'c', 'd'],
<add> formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
<add> offsets=[0, 0, 0, 0],
<add> itemsize=ctypes.sizeof(Union)
<add> ))
<add> self.check(Union, expected)
<add>
<ide> def test_packed_structure(self):
<ide> class PackedStructure(ctypes.Structure):
<ide> _pack_ = 1 | 2 |
Mixed | Ruby | add support for minitest flags in testrunner | 176b57c5430ddae7668114994c35b3293b0a05a5 | <ide><path>guides/source/testing.md
<ide> Rails creates a `test` folder for you as soon as you create a Rails project usin
<ide>
<ide> ```bash
<ide> $ ls -F test
<del>
<ide> controllers/ helpers/ mailers/ test_helper.rb
<ide> fixtures/ integration/ models/
<ide> ```
<ide> Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
<ide> 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
<ide> ```
<ide>
<del>You can also run a particular test method from the test case by running the test using Ruby and use the `-n` switch with the `test method name`.
<add>You can also run a particular test method from the test case by running the test and use the `-n` switch with the `test method name`.
<ide>
<ide> ```bash
<del>Run options: -n test_the_truth --seed 23064
<del>
<del># Running tests:
<del>
<add>$ rails test test/models/post_test.rb -n test_the_truth
<ide> .
<ide>
<ide> Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
<ide> end
<ide> Let us run this newly added test.
<ide>
<ide> ```bash
<del>Run options: -n test_should_not_save_post_without_title --seed 38984
<del>
<del># Running tests:
<del>
<add>$ rails test test/models/post_test.rb -n test_should_not_save_post_without_title
<ide> F
<ide>
<ide> Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
<ide> end
<ide> Now the test should pass. Let us verify by running the test again:
<ide>
<ide> ```bash
<del>$ ruby -Itest test/models/post_test.rb -n test_should_not_save_post_without_title
<del>Run options: -n test_should_not_save_post_without_title --seed 62114
<del>
<del># Running tests:
<del>
<add>$ rails test test/models/post_test.rb -n test_should_not_save_post_without_title
<ide> .
<ide>
<ide> Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
<ide> end
<ide> Now you can see even more output in the console from running the tests:
<ide>
<ide> ```bash
<del>$ ruby -Itest test/models/post_test.rb -n test_should_report_error
<del>Run options: -n test_should_report_error --seed 22995
<del>
<del># Running tests:
<del>
<add>$ rails test test/models/post_test.rb -n test_should_report_error
<ide> E
<ide>
<ide> Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
<ide><path>railties/lib/rails/commands.rb
<ide> when 'test'
<ide> $LOAD_PATH.unshift("./test")
<ide> require 'rails/commands/test_runner'
<del> if ["-h", "--help"].include?(ARGV.first)
<del> Rails::TestRunner.help_message
<del> exit
<del> else
<del> require APP_PATH
<del> Rails.application.require_environment!
<del> Rails.application.load_tasks
<del> Rails::TestRunner.start(ARGV)
<del> end
<add> options = Rails::TestRunner.parse_arguments(ARGV)
<add>
<add> require APP_PATH
<add> Rails.application.require_environment!
<add> Rails.application.load_tasks
<add> Rails::TestRunner.start(ARGV, options)
<ide>
<ide> when 'dbconsole'
<ide> require 'rails/commands/dbconsole'
<ide><path>railties/lib/rails/commands/test_runner.rb
<ide> class << self
<ide> # of file to a new +TestRunner+ object, then invoke the evaluation. If
<ide> # the argument is not a test suite name, it will be treated as a file
<ide> # name and passed to the +TestRunner+ instance right away.
<del> def start(arguments)
<del> case arguments.first
<add> def start(files, options)
<add> case files.first
<ide> when nil
<del> new(Dir['test/**/*_test.rb']).run
<add> new(Dir['test/**/*_test.rb'], options).run
<ide> when 'models'
<del> new(Dir['test/models/**/*_test.rb']).run
<add> new(Dir['test/models/**/*_test.rb'], options).run
<ide> when 'helpers'
<del> new(Dir['test/helpers/**/*_test.rb']).run
<add> new(Dir['test/helpers/**/*_test.rb'], options).run
<ide> when 'units'
<del> new(Dir['test/{models,helpers,unit}/**/*_test.rb']).run
<add> new(Dir['test/{models,helpers,unit}/**/*_test.rb'], options).run
<ide> when 'controllers'
<del> new(Dir['test/controllers/**/*_test.rb']).run
<add> new(Dir['test/controllers/**/*_test.rb'], options).run
<ide> when 'mailers'
<del> new(Dir['test/mailers/**/*_test.rb']).run
<add> new(Dir['test/mailers/**/*_test.rb'], options).run
<ide> when 'functionals'
<del> new(Dir['test/{controllers,mailers,functional}/**/*_test.rb']).run
<add> new(Dir['test/{controllers,mailers,functional}/**/*_test.rb'], options).run
<ide> when 'integration'
<del> new(Dir['test/integration/**/*_test.rb']).run
<add> new(Dir['test/integration/**/*_test.rb'], options).run
<ide> else
<del> new(arguments).run
<add> new(files, options).run
<ide> end
<ide> end
<ide>
<del> # Print out the help message which listed all of the test suite names.
<del> def help_message
<del> puts "Usage: rails test [path to test file(s) or test suite type]"
<del> puts ""
<del> puts "Run single test file, or a test suite, under Rails'"
<del> puts "environment. If the file name(s) or suit name is omitted,"
<del> puts "Rails will run all the test suites."
<del> puts ""
<del> puts "Support types of test suites:"
<del> puts "-------------------------------------------------------------"
<del> puts "* models (test/models/**/*)"
<del> puts "* helpers (test/helpers/**/*)"
<del> puts "* units (test/{models,helpers,unit}/**/*"
<del> puts "* controllers (test/controllers/**/*)"
<del> puts "* mailers (test/mailers/**/*)"
<del> puts "* functionals (test/{controllers,mailers,functional}/**/*)"
<del> puts "* integration (test/integration/**/*)"
<del> puts "-------------------------------------------------------------"
<add> # Parse arguments and set them as option flags
<add> def parse_arguments(arguments)
<add> options = {}
<add> orig_arguments = arguments.dup
<add>
<add> OptionParser.new do |opts|
<add> opts.banner = "Usage: rails test [path to test file(s) or test suite type]"
<add>
<add> opts.separator ""
<add> opts.separator "Run single test file, or a test suite, under Rails'"
<add> opts.separator "environment. If the file name(s) or suit name is omitted,"
<add> opts.separator "Rails will run all the test suites."
<add> opts.separator ""
<add> opts.separator "Specific options:"
<add>
<add> opts.on '-h', '--help', 'Display this help.' do
<add> puts opts
<add> exit
<add> end
<add>
<add> opts.on '-s', '--seed SEED', Integer, "Sets random seed" do |m|
<add> options[:seed] = m.to_i
<add> end
<add>
<add> opts.on '-v', '--verbose', "Verbose. Show progress processing files." do
<add> options[:verbose] = true
<add> end
<add>
<add> opts.on '-n', '--name PATTERN', "Filter test names on pattern (e.g. /foo/)" do |a|
<add> options[:filter] = a
<add> end
<add>
<add> opts.separator ""
<add> opts.separator "Support types of test suites:"
<add> opts.separator "-------------------------------------------------------------"
<add> opts.separator "* models (test/models/**/*)"
<add> opts.separator "* helpers (test/helpers/**/*)"
<add> opts.separator "* units (test/{models,helpers,unit}/**/*"
<add> opts.separator "* controllers (test/controllers/**/*)"
<add> opts.separator "* mailers (test/mailers/**/*)"
<add> opts.separator "* functionals (test/{controllers,mailers,functional}/**/*)"
<add> opts.separator "* integration (test/integration/**/*)"
<add> opts.separator "-------------------------------------------------------------"
<add>
<add> opts.parse! arguments
<add> orig_arguments -= arguments
<add> end
<add> options
<ide> end
<ide> end
<ide>
<ide> # Create a new +TestRunner+ object with a list of test file paths.
<del> def initialize(files)
<add> def initialize(files, options)
<ide> @files = files
<ide> Rake::Task['test:prepare'].invoke
<add> MiniTest::Unit.runner.options = options
<ide> MiniTest::Unit.output = SilentUntilSyncStream.new(MiniTest::Unit.output)
<ide> end
<ide>
<ide><path>railties/test/application/test_runner_test.rb
<ide> def test_run_whole_suite
<ide> end
<ide> end
<ide>
<add> def test_run_named_test
<add> app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY
<add> require 'test_helper'
<add>
<add> class Chu2KoiTest < ActiveSupport::TestCase
<add> def test_rikka
<add> puts 'Rikka'
<add> end
<add>
<add> def test_sanae
<add> puts 'Sanae'
<add> end
<add> end
<add> RUBY
<add>
<add> run_test_command('test/unit/chu_2_koi_test.rb -n test_rikka').tap do |output|
<add> assert_match /Rikka/, output
<add> assert_no_match /Sanae/, output
<add> end
<add> end
<add>
<ide> private
<ide> def run_test_command(arguments = 'test/unit/test_test.rb')
<ide> Dir.chdir(app_path) { `bundle exec rails test #{arguments}` } | 4 |
Javascript | Javascript | copy array with slice instead of for loop | 8eabc5463c795d87f37e5a9eacbbb14435024061 | <ide><path>src/ng/filter/orderBy.js
<ide> function orderByFilter($parse) {
<ide> return compare(get(a),get(b));
<ide> }, descending);
<ide> });
<del> var arrayCopy = [];
<del> for (var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
<del> return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
<add> return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
<ide>
<ide> function comparator(o1, o2) {
<ide> for (var i = 0; i < sortPredicate.length; i++) { | 1 |
Text | Text | add link to boilerplate glitch file | 24b3bed83ff9e89cbdcd848147a4cd1609bc622b | <ide><path>curriculum/challenges/english/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.english.md
<ide> We recommend to keep the log panel open while working at these challenges. By re
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<add>
<add>If you have not already done so, please read the instructions in [the introduction](/learn/apis-and-microservices/basic-node-and-express/) and start a new project on Glitch using [this link](https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-express/).
<add>
<ide> Modify the <code>myApp.js</code> file to log "Hello World" to the console.
<add>
<ide> </section>
<ide>
<ide> ## Tests | 1 |
Go | Go | remove perm change in archive | 6bc483fa59adc0be65ea9c804c69d861a02435bd | <ide><path>archive/diff.go
<ide> func ApplyLayer(dest string, layer ArchiveReader) error {
<ide> parent := filepath.Dir(hdr.Name)
<ide> parentPath := filepath.Join(dest, parent)
<ide> if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
<del> err = os.MkdirAll(parentPath, 0700)
<add> err = os.MkdirAll(parentPath, 0600)
<ide> if err != nil {
<ide> return err
<ide> } | 1 |
PHP | PHP | fix magic quotes | 8d169166308972158b380f2f8fb729882216026e | <ide><path>laravel/laravel.php
<ide>
<ide> error_reporting(-1);
<ide>
<add>/*
<add>|--------------------------------------------------------------------------
<add>| Magic Quotes Strip Slashes
<add>|--------------------------------------------------------------------------
<add>|
<add>| Even though "Magic Quotes" are deprecated in PHP 5.3.x, they may still
<add>| be enabled on the server. To account for this, we will strip slashes
<add>| on all input arrays if magic quotes are enabled for the server.
<add>|
<add>*/
<add>
<add>if (magic_quotes())
<add>{
<add> $magics = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
<add>
<add> foreach ($magics as &$magic)
<add> {
<add> $magic = array_strip_slashes($magic);
<add> }
<add>}
<add>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Create The HttpFoundation Request
<ide> |
<ide> */
<ide>
<del>use Symfony\Component\HttpFoundation\Request as FoundationRequest;
<add>use Symfony\Component\HttpFoundation\LaravelRequest as RequestFoundation;
<ide>
<del>Request::$foundation = FoundationRequest::createFromGlobals();
<add>Request::$foundation = RequestFoundation::createFromGlobals();
<ide>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide><path>vendor/Symfony/Component/HTTPFoundation/LaravelRequest.php
<add><?php namespace Symfony\Component\HttpFoundation;
<add>
<add>class LaravelRequest extends Request {
<add>
<add> /**
<add> * Creates a new request with values from PHP's super globals.
<add> *
<add> * @return Request A new request
<add> *
<add> * @api
<add> */
<add> static public function createFromGlobals()
<add> {
<add> $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
<add>
<add> if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
<add> && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
<add> ) {
<add> parse_str($request->getContent(), $data);
<add> if (magic_quotes()) $data = array_strip_slashes($data);
<add> $request->request = new ParameterBag($data);
<add> }
<add>
<add> return $request;
<add> }
<add>
<add>}
<ide>\ No newline at end of file | 2 |
Python | Python | support new marian models | ba21001f4c6709a72c7a663078677cd5f9e5306b | <ide><path>src/transformers/models/marian/configuration_marian.py
<ide> class MarianConfig(PretrainedConfig):
<ide> def __init__(
<ide> self,
<ide> vocab_size=50265,
<add> decoder_vocab_size=None,
<ide> max_position_embeddings=1024,
<ide> encoder_layers=12,
<ide> encoder_ffn_dim=4096,
<ide> def __init__(
<ide> pad_token_id=58100,
<ide> eos_token_id=0,
<ide> forced_eos_token_id=0,
<add> share_encoder_decoder_embeddings=True,
<ide> **kwargs
<ide> ):
<ide> self.vocab_size = vocab_size
<add> self.decoder_vocab_size = decoder_vocab_size or vocab_size
<ide> self.max_position_embeddings = max_position_embeddings
<ide> self.d_model = d_model
<ide> self.encoder_ffn_dim = encoder_ffn_dim
<ide> def __init__(
<ide> self.use_cache = use_cache
<ide> self.num_hidden_layers = encoder_layers
<ide> self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
<add> self.share_encoder_decoder_embeddings = share_encoder_decoder_embeddings
<ide> super().__init__(
<ide> pad_token_id=pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide><path>src/transformers/models/marian/convert_marian_to_pytorch.py
<ide> def load_layers_(layer_lst: nn.ModuleList, opus_state: dict, converter, is_decod
<ide> for i, layer in enumerate(layer_lst):
<ide> layer_tag = f"decoder_l{i + 1}_" if is_decoder else f"encoder_l{i + 1}_"
<ide> sd = convert_encoder_layer(opus_state, layer_tag, converter)
<del> layer.load_state_dict(sd, strict=True)
<add> layer.load_state_dict(sd, strict=False)
<ide>
<ide>
<ide> def find_pretrained_model(src_lang: str, tgt_lang: str) -> List[str]:
<ide> def _parse_readme(lns):
<ide> return subres
<ide>
<ide>
<del>def save_tokenizer_config(dest_dir: Path):
<add>def save_tokenizer_config(dest_dir: Path, separate_vocabs=False):
<ide> dname = dest_dir.name.split("-")
<del> dct = dict(target_lang=dname[-1], source_lang="-".join(dname[:-1]))
<add> dct = dict(target_lang=dname[-1], source_lang="-".join(dname[:-1]), separate_vocabs=separate_vocabs)
<ide> save_json(dct, dest_dir / "tokenizer_config.json")
<ide>
<ide>
<ide> def find_vocab_file(model_dir):
<ide> return list(model_dir.glob("*vocab.yml"))[0]
<ide>
<ide>
<del>def add_special_tokens_to_vocab(model_dir: Path) -> None:
<del> vocab = load_yaml(find_vocab_file(model_dir))
<del> vocab = {k: int(v) for k, v in vocab.items()}
<del> num_added = add_to_vocab_(vocab, ["<pad>"])
<del> print(f"added {num_added} tokens to vocab")
<del> save_json(vocab, model_dir / "vocab.json")
<del> save_tokenizer_config(model_dir)
<add>def find_src_vocab_file(model_dir):
<add> return list(model_dir.glob("*src.vocab.yml"))[0]
<add>
<add>
<add>def find_tgt_vocab_file(model_dir):
<add> return list(model_dir.glob("*trg.vocab.yml"))[0]
<add>
<add>
<add>def add_special_tokens_to_vocab(model_dir: Path, separate_vocab=False) -> None:
<add> if separate_vocab:
<add> vocab = load_yaml(find_src_vocab_file(model_dir))
<add> vocab = {k: int(v) for k, v in vocab.items()}
<add> num_added = add_to_vocab_(vocab, ["<pad>"])
<add> save_json(vocab, model_dir / "vocab.json")
<add>
<add> vocab = load_yaml(find_tgt_vocab_file(model_dir))
<add> vocab = {k: int(v) for k, v in vocab.items()}
<add> num_added = add_to_vocab_(vocab, ["<pad>"])
<add> save_json(vocab, model_dir / "target_vocab.json")
<add> save_tokenizer_config(model_dir, separate_vocabs=separate_vocab)
<add> else:
<add> vocab = load_yaml(find_vocab_file(model_dir))
<add> vocab = {k: int(v) for k, v in vocab.items()}
<add> num_added = add_to_vocab_(vocab, ["<pad>"])
<add> print(f"added {num_added} tokens to vocab")
<add> save_json(vocab, model_dir / "vocab.json")
<add> save_tokenizer_config(model_dir)
<ide>
<ide>
<ide> def check_equal(marian_cfg, k1, k2):
<ide> def check_equal(marian_cfg, k1, k2):
<ide>
<ide> def check_marian_cfg_assumptions(marian_cfg):
<ide> assumed_settings = {
<del> "tied-embeddings-all": True,
<ide> "layer-normalization": False,
<ide> "right-left": False,
<ide> "transformer-ffn-depth": 2,
<ide> def check_marian_cfg_assumptions(marian_cfg):
<ide> actual = marian_cfg[k]
<ide> if actual != v:
<ide> raise ValueError(f"Unexpected config value for {k} expected {v} got {actual}")
<del> check_equal(marian_cfg, "transformer-ffn-activation", "transformer-aan-activation")
<del> check_equal(marian_cfg, "transformer-ffn-depth", "transformer-aan-depth")
<del> check_equal(marian_cfg, "transformer-dim-ffn", "transformer-dim-aan")
<ide>
<ide>
<ide> BIAS_KEY = "decoder_ff_logit_out_b"
<ide> def __init__(self, source_dir, eos_token_id=0):
<ide> if "Wpos" in self.state_dict:
<ide> raise ValueError("Wpos key in state dictionary")
<ide> self.state_dict = dict(self.state_dict)
<del> self.wemb, self.final_bias = add_emb_entries(self.state_dict["Wemb"], self.state_dict[BIAS_KEY], 1)
<del> self.pad_token_id = self.wemb.shape[0] - 1
<del> cfg["vocab_size"] = self.pad_token_id + 1
<add> self.share_encoder_decoder_embeddings = cfg["tied-embeddings-src"]
<add>
<add> # create the tokenizer here because we need to know the eos_token_id
<add> self.source_dir = source_dir
<add> self.tokenizer = self.load_tokenizer()
<add> # retrieve EOS token and set correctly
<add> tokenizer_has_eos_token_id = (
<add> hasattr(self.tokenizer, "eos_token_id") and self.tokenizer.eos_token_id is not None
<add> )
<add> eos_token_id = self.tokenizer.eos_token_id if tokenizer_has_eos_token_id else 0
<add>
<add> if cfg["tied-embeddings-src"]:
<add> self.wemb, self.final_bias = add_emb_entries(self.state_dict["Wemb"], self.state_dict[BIAS_KEY], 1)
<add> self.pad_token_id = self.wemb.shape[0] - 1
<add> cfg["vocab_size"] = self.pad_token_id + 1
<add> else:
<add> self.wemb, _ = add_emb_entries(self.state_dict["encoder_Wemb"], self.state_dict[BIAS_KEY], 1)
<add> self.dec_wemb, self.final_bias = add_emb_entries(
<add> self.state_dict["decoder_Wemb"], self.state_dict[BIAS_KEY], 1
<add> )
<add> # still assuming that vocab size is same for encoder and decoder
<add> self.pad_token_id = self.wemb.shape[0] - 1
<add> cfg["vocab_size"] = self.pad_token_id + 1
<add> cfg["decoder_vocab_size"] = self.pad_token_id + 1
<add>
<add> if cfg["vocab_size"] != self.tokenizer.vocab_size:
<add> raise ValueError(
<add> f"Original vocab size {cfg['vocab_size']} and new vocab size {len(self.tokenizer.encoder)} mismatched."
<add> )
<add>
<ide> # self.state_dict['Wemb'].sha
<ide> self.state_keys = list(self.state_dict.keys())
<ide> if "Wtype" in self.state_dict:
<ide> raise ValueError("Wtype key in state dictionary")
<ide> self._check_layer_entries()
<del> self.source_dir = source_dir
<ide> self.cfg = cfg
<ide> hidden_size, intermediate_shape = self.state_dict["encoder_l1_ffn_W1"].shape
<del> if hidden_size != 512 or cfg["dim-emb"] != 512:
<del> raise ValueError(f"Hidden size {hidden_size} and configured size {cfg['dim_emb']} mismatched or not 512")
<add> if hidden_size != cfg["dim-emb"]:
<add> raise ValueError(f"Hidden size {hidden_size} and configured size {cfg['dim_emb']} mismatched")
<ide>
<ide> # Process decoder.yml
<ide> decoder_yml = cast_marian_config(load_yaml(source_dir / "decoder.yml"))
<ide> check_marian_cfg_assumptions(cfg)
<ide> self.hf_config = MarianConfig(
<ide> vocab_size=cfg["vocab_size"],
<add> decoder_vocab_size=cfg.get("decoder_vocab_size", cfg["vocab_size"]),
<add> share_encoder_decoder_embeddings=cfg["tied-embeddings-src"],
<ide> decoder_layers=cfg["dec-depth"],
<ide> encoder_layers=cfg["enc-depth"],
<ide> decoder_attention_heads=cfg["transformer-heads"],
<ide> def __init__(self, source_dir, eos_token_id=0):
<ide> scale_embedding=True,
<ide> normalize_embedding="n" in cfg["transformer-preprocess"],
<ide> static_position_embeddings=not cfg["transformer-train-position-embeddings"],
<add> tie_word_embeddings=cfg["tied-embeddings"],
<ide> dropout=0.1, # see opus-mt-train repo/transformer-dropout param.
<ide> # default: add_final_layer_norm=False,
<ide> num_beams=decoder_yml["beam-size"],
<ide> def extra_keys(self):
<ide> if (
<ide> k.startswith("encoder_l")
<ide> or k.startswith("decoder_l")
<del> or k in [CONFIG_KEY, "Wemb", "Wpos", "decoder_ff_logit_out_b"]
<add> or k in [CONFIG_KEY, "Wemb", "encoder_Wemb", "decoder_Wemb", "Wpos", "decoder_ff_logit_out_b"]
<ide> ):
<ide> continue
<ide> else:
<ide> def extra_keys(self):
<ide> def sub_keys(self, layer_prefix):
<ide> return [remove_prefix(k, layer_prefix) for k in self.state_dict if k.startswith(layer_prefix)]
<ide>
<add> def load_tokenizer(self):
<add> # save tokenizer
<add> add_special_tokens_to_vocab(self.source_dir, not self.share_encoder_decoder_embeddings)
<add> return MarianTokenizer.from_pretrained(str(self.source_dir))
<add>
<ide> def load_marian_model(self) -> MarianMTModel:
<ide> state_dict, cfg = self.state_dict, self.hf_config
<ide>
<ide> def load_marian_model(self) -> MarianMTModel:
<ide> load_layers_(model.model.decoder.layers, state_dict, BART_CONVERTER, is_decoder=True)
<ide>
<ide> # handle tensors not associated with layers
<del> wemb_tensor = nn.Parameter(torch.FloatTensor(self.wemb))
<del> bias_tensor = nn.Parameter(torch.FloatTensor(self.final_bias))
<del> model.model.shared.weight = wemb_tensor
<del> model.model.encoder.embed_tokens = model.model.decoder.embed_tokens = model.model.shared
<add> if self.cfg["tied-embeddings-src"]:
<add> wemb_tensor = nn.Parameter(torch.FloatTensor(self.wemb))
<add> bias_tensor = nn.Parameter(torch.FloatTensor(self.final_bias))
<add> model.model.shared.weight = wemb_tensor
<add> model.model.encoder.embed_tokens = model.model.decoder.embed_tokens = model.model.shared
<add> else:
<add> wemb_tensor = nn.Parameter(torch.FloatTensor(self.wemb))
<add> model.model.encoder.embed_tokens.weight = wemb_tensor
<add>
<add> decoder_wemb_tensor = nn.Parameter(torch.FloatTensor(self.dec_wemb))
<add> bias_tensor = nn.Parameter(torch.FloatTensor(self.final_bias))
<add> model.model.decoder.embed_tokens.weight = decoder_wemb_tensor
<ide>
<ide> model.final_logits_bias = bias_tensor
<ide>
<ide> def load_marian_model(self) -> MarianMTModel:
<ide>
<ide> if self.extra_keys:
<ide> raise ValueError(f"Failed to convert {self.extra_keys}")
<del> if model.model.shared.padding_idx != self.pad_token_id:
<del> raise ValueError(f"Padding tokens {model.model.shared.padding_idx} and {self.pad_token_id} mismatched")
<add>
<add> if model.get_input_embeddings().padding_idx != self.pad_token_id:
<add> raise ValueError(
<add> f"Padding tokens {model.get_input_embeddings().padding_idx} and {self.pad_token_id} mismatched"
<add> )
<ide> return model
<ide>
<ide>
<ide> def convert(source_dir: Path, dest_dir):
<ide> dest_dir = Path(dest_dir)
<ide> dest_dir.mkdir(exist_ok=True)
<ide>
<del> add_special_tokens_to_vocab(source_dir)
<del> tokenizer = MarianTokenizer.from_pretrained(str(source_dir))
<del> tokenizer.save_pretrained(dest_dir)
<add> opus_state = OpusState(source_dir)
<ide>
<del> # retrieve EOS token and set correctly
<del> tokenizer_has_eos_token_id = hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None
<del> eos_token_id = tokenizer.eos_token_id if tokenizer_has_eos_token_id else 0
<add> # save tokenizer
<add> opus_state.tokenizer.save_pretrained(dest_dir)
<ide>
<del> opus_state = OpusState(source_dir, eos_token_id=eos_token_id)
<del> if opus_state.cfg["vocab_size"] != len(tokenizer.encoder):
<del> raise ValueError(
<del> f"Original vocab size {opus_state.cfg['vocab_size']} and new vocab size {len(tokenizer.encoder)} mismatched"
<del> )
<ide> # save_json(opus_state.cfg, dest_dir / "marian_original_config.json")
<ide> # ^^ Uncomment to save human readable marian config for debugging
<ide>
<ide><path>src/transformers/models/marian/modeling_marian.py
<ide> def __init__(self, config: MarianConfig, embed_tokens: Optional[nn.Embedding] =
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide>
<add> def get_input_embeddings(self):
<add> return self.embed_tokens
<add>
<add> def set_input_embeddings(self, value):
<add> self.embed_tokens = value
<add>
<ide> def forward(
<ide> self,
<ide> input_ids=None,
<ide> def __init__(self, config: MarianConfig, embed_tokens: Optional[nn.Embedding] =
<ide> if embed_tokens is not None:
<ide> self.embed_tokens = embed_tokens
<ide> else:
<del> self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
<add> self.embed_tokens = nn.Embedding(config.decoder_vocab_size, config.d_model, self.padding_idx)
<ide>
<ide> self.embed_positions = MarianSinusoidalPositionalEmbedding(
<ide> config.max_position_embeddings,
<ide> def __init__(self, config: MarianConfig):
<ide> super().__init__(config)
<ide>
<ide> padding_idx, vocab_size = config.pad_token_id, config.vocab_size
<add>
<add> # We always use self.shared for token embeddings to ensure compatibility with all marian models
<ide> self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
<add> if self.config.share_encoder_decoder_embeddings:
<add> encoder_embed_tokens = decoder_embed_tokens = self.shared
<add> else:
<add> # Since the embeddings are not shared, deepcopy the embeddings here for encoder
<add> # and decoder to make sure they are not tied.
<add> encoder_embed_tokens = copy.deepcopy(self.shared)
<add> decoder_embed_tokens = copy.deepcopy(self.shared)
<add> self.shared = None
<ide>
<del> self.encoder = MarianEncoder(config, self.shared)
<del> self.decoder = MarianDecoder(config, self.shared)
<add> self.encoder = MarianEncoder(config, encoder_embed_tokens)
<add> self.decoder = MarianDecoder(config, decoder_embed_tokens)
<ide>
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide>
<ide> def get_input_embeddings(self):
<del> return self.shared
<add> # This will return shared embeddings if they are shared else specific to encoder.
<add> return self.get_encoder().get_input_embeddings()
<ide>
<ide> def set_input_embeddings(self, value):
<del> self.shared = value
<del> self.encoder.embed_tokens = self.shared
<del> self.decoder.embed_tokens = self.shared
<add> if self.config.share_encoder_decoder_embeddings:
<add> self.shared = value
<add> self.encoder.embed_tokens = self.shared
<add> self.decoder.embed_tokens = self.shared
<add> else: # if not shared only set encoder embeedings
<add> self.encoder.embed_tokens = value
<add>
<add> def get_decoder_input_embeddings(self):
<add> if self.config.share_encoder_decoder_embeddings:
<add> raise ValueError(
<add> "`get_decoder_input_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
<add> "is `True`. Please use `get_input_embeddings` instead."
<add> )
<add> return self.get_decoder().get_input_embeddings()
<add>
<add> def set_decoder_input_embeddings(self, value):
<add> if self.config.share_encoder_decoder_embeddings:
<add> raise ValueError(
<add> "`config.share_encoder_decoder_embeddings` is set to `True` meaning the decoder input embeddings "
<add> "are shared with the encoder. In order to set the decoder input embeddings, you should simply set "
<add> "the encoder input embeddings by calling `set_input_embeddings` with the appropriate embeddings."
<add> )
<add> self.decoder.embed_tokens = value
<ide>
<ide> def get_encoder(self):
<ide> return self.encoder
<ide>
<ide> def get_decoder(self):
<ide> return self.decoder
<ide>
<add> def resize_decoder_token_embeddings(self, new_num_tokens):
<add> if self.config.share_encoder_decoder_embeddings:
<add> raise ValueError(
<add> "`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
<add> "is `True`. Please use `resize_token_embeddings` instead."
<add> )
<add>
<add> old_embeddings = self.get_decoder_input_embeddings()
<add> new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
<add> self.set_decoder_input_embeddings(new_embeddings)
<add>
<add> model_embeds = self.get_decoder_input_embeddings()
<add>
<add> if new_num_tokens is None:
<add> return model_embeds
<add>
<add> # Update base model and current model config
<add> self.config.decoder_vocab_size = new_num_tokens
<add>
<add> # Tie weights again if needed
<add> self.tie_weights()
<add>
<add> return model_embeds
<add>
<ide> @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
<ide> @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> class MarianMTModel(MarianPreTrainedModel):
<ide> def __init__(self, config: MarianConfig):
<ide> super().__init__(config)
<ide> self.model = MarianModel(config)
<del> self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
<del> self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
<add>
<add> self.target_vocab_size = (
<add> config.vocab_size if config.share_encoder_decoder_embeddings else config.decoder_vocab_size
<add> )
<add> self.register_buffer("final_logits_bias", torch.zeros((1, self.target_vocab_size)))
<add> self.lm_head = nn.Linear(config.d_model, self.target_vocab_size, bias=False)
<ide>
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide> def get_decoder(self):
<ide>
<ide> def resize_token_embeddings(self, new_num_tokens: int) -> nn.Embedding:
<ide> new_embeddings = super().resize_token_embeddings(new_num_tokens)
<del> self._resize_final_logits_bias(new_num_tokens)
<add> if self.config.share_encoder_decoder_embeddings:
<add> self._resize_final_logits_bias(new_num_tokens)
<ide> return new_embeddings
<ide>
<add> def _resize_token_embeddings(self, new_num_tokens):
<add> old_embeddings = self.get_input_embeddings()
<add> new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
<add> self.set_input_embeddings(new_embeddings)
<add>
<add> # if word embeddings are not tied, make sure that lm head is resized as well
<add> if (
<add> self.config.share_encoder_decoder_embeddings
<add> and self.get_output_embeddings() is not None
<add> and not self.config.tie_word_embeddings
<add> ):
<add> old_lm_head = self.get_output_embeddings()
<add> new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens)
<add> self.set_output_embeddings(new_lm_head)
<add>
<add> return self.get_input_embeddings()
<add>
<add> def resize_decoder_token_embeddings(self, new_num_tokens):
<add> if self.config.share_encoder_decoder_embeddings:
<add> raise ValueError(
<add> "`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
<add> "is `True`. Please use `resize_token_embeddings` instead."
<add> )
<add>
<add> old_embeddings = self.model.get_decoder_input_embeddings()
<add> new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
<add> self.model.set_decoder_input_embeddings(new_embeddings)
<add>
<add> # if word embeddings are not tied, make sure that lm head is resized as well
<add> if self.get_output_embeddings() is not None and not self.config.tie_word_embeddings:
<add> old_lm_head = self.get_output_embeddings()
<add> new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens)
<add> self.set_output_embeddings(new_lm_head)
<add>
<add> model_embeds = self.model.get_decoder_input_embeddings()
<add>
<add> if new_num_tokens is None:
<add> return model_embeds
<add>
<add> # Update base model and current model config
<add> self.config.decoder_vocab_size = new_num_tokens
<add>
<add> # Tie weights again if needed
<add> self.tie_weights()
<add>
<add> self._resize_final_logits_bias(new_num_tokens)
<add>
<add> return model_embeds
<add>
<ide> def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
<ide> old_num_tokens = self.final_logits_bias.shape[-1]
<ide> if new_num_tokens <= old_num_tokens:
<ide> def get_output_embeddings(self):
<ide> def set_output_embeddings(self, new_embeddings):
<ide> self.lm_head = new_embeddings
<ide>
<add> def tie_weights(self):
<add> """
<add> Tie the weights between the input embeddings and the output embeddings.
<add>
<add> If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the
<add> weights instead.
<add> """
<add> output_embeddings = self.get_output_embeddings()
<add> if output_embeddings is not None and getattr(self.config, "tie_word_embeddings", True):
<add> # if embeddings are shared this will return shared embeddings otherwise decoder embed_tokens
<add> word_embeddings = self.get_decoder().get_input_embeddings()
<add> self._tie_or_clone_weights(output_embeddings, word_embeddings)
<add>
<add> if getattr(self.config, "is_encoder_decoder", False) and getattr(self.config, "tie_encoder_decoder", False):
<add> if hasattr(self, self.base_model_prefix):
<add> self = getattr(self, self.base_model_prefix)
<add> self._tie_encoder_decoder_weights(self.encoder, self.decoder, self.base_model_prefix)
<add>
<add> for module in self.modules():
<add> if hasattr(module, "_tie_weights"):
<add> module._tie_weights()
<add>
<ide> @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
<ide> @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
<ide> @add_end_docstrings(MARIAN_GENERATION_EXAMPLE)
<ide> def forward(
<ide> masked_lm_loss = None
<ide> if labels is not None:
<ide> loss_fct = CrossEntropyLoss()
<del> masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
<add> masked_lm_loss = loss_fct(lm_logits.view(-1, self.target_vocab_size), labels.view(-1))
<ide>
<ide> if not return_dict:
<ide> output = (lm_logits,) + outputs[1:]
<ide><path>src/transformers/models/marian/tokenization_marian.py
<ide> "source_spm": "source.spm",
<ide> "target_spm": "target.spm",
<ide> "vocab": "vocab.json",
<add> "target_vocab_file": "target_vocab.json",
<ide> "tokenizer_config_file": "tokenizer_config.json",
<ide> }
<ide>
<ide> class MarianTokenizer(PreTrainedTokenizer):
<ide>
<ide> def __init__(
<ide> self,
<del> vocab,
<ide> source_spm,
<ide> target_spm,
<add> vocab,
<add> target_vocab_file=None,
<ide> source_lang=None,
<ide> target_lang=None,
<ide> unk_token="<unk>",
<ide> eos_token="</s>",
<ide> pad_token="<pad>",
<ide> model_max_length=512,
<ide> sp_model_kwargs: Optional[Dict[str, Any]] = None,
<add> separate_vocabs=False,
<ide> **kwargs
<ide> ) -> None:
<ide> self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
<ide> def __init__(
<ide> pad_token=pad_token,
<ide> model_max_length=model_max_length,
<ide> sp_model_kwargs=self.sp_model_kwargs,
<add> target_vocab_file=target_vocab_file,
<add> separate_vocabs=separate_vocabs,
<ide> **kwargs,
<ide> )
<ide> assert Path(source_spm).exists(), f"cannot find spm source {source_spm}"
<add>
<add> self.separate_vocabs = separate_vocabs
<ide> self.encoder = load_json(vocab)
<ide> if self.unk_token not in self.encoder:
<ide> raise KeyError("<unk> token must be in vocab")
<ide> assert self.pad_token in self.encoder
<del> self.decoder = {v: k for k, v in self.encoder.items()}
<add>
<add> if separate_vocabs:
<add> self.target_encoder = load_json(target_vocab_file)
<add> self.decoder = {v: k for k, v in self.target_encoder.items()}
<add> self.supported_language_codes = []
<add> else:
<add> self.decoder = {v: k for k, v in self.encoder.items()}
<add> self.supported_language_codes: list = [k for k in self.encoder if k.startswith(">>") and k.endswith("<<")]
<ide>
<ide> self.source_lang = source_lang
<ide> self.target_lang = target_lang
<del> self.supported_language_codes: list = [k for k in self.encoder if k.startswith(">>") and k.endswith("<<")]
<ide> self.spm_files = [source_spm, target_spm]
<ide>
<ide> # load SentencePiece model for pre-processing
<ide> self.spm_source = load_spm(source_spm, self.sp_model_kwargs)
<ide> self.spm_target = load_spm(target_spm, self.sp_model_kwargs)
<ide> self.current_spm = self.spm_source
<add> self.current_encoder = self.encoder
<ide>
<ide> # Multilingual target side: default to using first supported language code.
<ide>
<ide> def normalize(self, x: str) -> str:
<ide> return self.punc_normalizer(x) if x else ""
<ide>
<ide> def _convert_token_to_id(self, token):
<del> return self.encoder.get(token, self.encoder[self.unk_token])
<add> return self.current_encoder.get(token, self.current_encoder[self.unk_token])
<ide>
<ide> def remove_language_code(self, text: str):
<ide> """Remove language codes like >>fr<< before sentencepiece"""
<ide> def as_target_tokenizer(self):
<ide> sequence-to-sequence models that need a slightly different processing for the labels.
<ide> """
<ide> self.current_spm = self.spm_target
<add> if self.separate_vocabs:
<add> self.current_encoder = self.target_encoder
<ide> yield
<ide> self.current_spm = self.spm_source
<add> self.current_encoder = self.encoder
<ide>
<ide> @property
<ide> def vocab_size(self) -> int:
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] =
<ide> logger.error(f"Vocabulary path ({save_directory}) should be a directory")
<ide> return
<ide> saved_files = []
<del> out_vocab_file = os.path.join(
<del> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]
<del> )
<ide>
<del> save_json(self.encoder, out_vocab_file)
<del> saved_files.append(out_vocab_file)
<add> if self.separate_vocabs:
<add> out_src_vocab_file = os.path.join(
<add> save_directory,
<add> (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"],
<add> )
<add> out_tgt_vocab_file = os.path.join(
<add> save_directory,
<add> (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["target_vocab_file"],
<add> )
<add> save_json(self.encoder, out_src_vocab_file)
<add> save_json(self.target_encoder, out_tgt_vocab_file)
<add> saved_files.append(out_src_vocab_file)
<add> saved_files.append(out_tgt_vocab_file)
<add> else:
<add> out_vocab_file = os.path.join(
<add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]
<add> )
<add> save_json(self.encoder, out_vocab_file)
<add> saved_files.append(out_vocab_file)
<ide>
<ide> for spm_save_filename, spm_orig_path, spm_model in zip(
<ide> [VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]],
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] =
<ide> return tuple(saved_files)
<ide>
<ide> def get_vocab(self) -> Dict:
<del> vocab = self.encoder.copy()
<del> vocab.update(self.added_tokens_encoder)
<del> return vocab
<add> return self.get_src_vocab()
<add>
<add> def get_src_vocab(self):
<add> return dict(self.encoder, **self.added_tokens_encoder)
<add>
<add> def get_tgt_vocab(self):
<add> return dict(self.target_encoder, **self.added_tokens_decoder)
<ide>
<ide> def __getstate__(self) -> Dict:
<ide> state = self.__dict__.copy()
<del> state.update({k: None for k in ["spm_source", "spm_target", "current_spm", "punc_normalizer"]})
<add> state.update(
<add> {k: None for k in ["spm_source", "spm_target", "current_spm", "punc_normalizer", "target_vocab_file"]}
<add> )
<ide> return state
<ide>
<ide> def __setstate__(self, d: Dict) -> None:
<ide><path>tests/marian/test_modeling_marian.py
<ide> def test_generate_fp16(self):
<ide> model.generate(input_ids, attention_mask=attention_mask)
<ide> model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
<ide>
<add> def test_share_encoder_decoder_embeddings(self):
<add> config, input_dict = self.model_tester.prepare_config_and_inputs()
<add>
<add> # check if embeddings are shared by default
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add> self.assertIs(model.get_encoder().embed_tokens, model.get_decoder().embed_tokens)
<add> self.assertIs(model.get_encoder().embed_tokens.weight, model.get_decoder().embed_tokens.weight)
<add>
<add> # check if embeddings are not shared when config.share_encoder_decoder_embeddings = False
<add> config.share_encoder_decoder_embeddings = False
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add> self.assertIsNot(model.get_encoder().embed_tokens, model.get_decoder().embed_tokens)
<add> self.assertIsNot(model.get_encoder().embed_tokens.weight, model.get_decoder().embed_tokens.weight)
<add>
<add> # check if a model with shared embeddings can be saved and loaded with share_encoder_decoder_embeddings = False
<add> config, _ = self.model_tester.prepare_config_and_inputs()
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add> with tempfile.TemporaryDirectory() as tmpdirname:
<add> model.save_pretrained(tmpdirname)
<add> model = model_class.from_pretrained(tmpdirname, share_encoder_decoder_embeddings=False)
<add> self.assertIsNot(model.get_encoder().embed_tokens, model.get_decoder().embed_tokens)
<add> self.assertIsNot(model.get_encoder().embed_tokens.weight, model.get_decoder().embed_tokens.weight)
<add>
<add> def test_resize_decoder_token_embeddings(self):
<add> config, _ = self.model_tester.prepare_config_and_inputs()
<add>
<add> # check if resize_decoder_token_embeddings raises an error when embeddings are shared
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add> with self.assertRaises(ValueError):
<add> model.resize_decoder_token_embeddings(config.vocab_size + 1)
<add>
<add> # check if decoder embeddings are resized when config.share_encoder_decoder_embeddings = False
<add> config.share_encoder_decoder_embeddings = False
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add> model.resize_decoder_token_embeddings(config.vocab_size + 1)
<add> self.assertEqual(model.get_decoder().embed_tokens.weight.shape, (config.vocab_size + 1, config.d_model))
<add>
<add> # check if lm_head is also resized
<add> config, _ = self.model_tester.prepare_config_and_inputs()
<add> config.share_encoder_decoder_embeddings = False
<add> model = MarianMTModel(config)
<add> model.resize_decoder_token_embeddings(config.vocab_size + 1)
<add> self.assertEqual(model.lm_head.weight.shape, (config.vocab_size + 1, config.d_model))
<add>
<add> def test_tie_word_embeddings_decoder(self):
<add> pass
<add>
<ide>
<ide> def assert_tensors_close(a, b, atol=1e-12, prefix=""):
<ide> """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
<ide> def test_pipeline(self):
<ide> self.assertEqual(self.expected_text, [x["translation_text"] for x in output])
<ide>
<ide>
<add>@require_sentencepiece
<add>@require_tokenizers
<add>class TestMarian_FI_EN_V2(MarianIntegrationTest):
<add> src = "fi"
<add> tgt = "en"
<add> src_text = [
<add> "minä tykkään kirjojen lukemisesta",
<add> "Pidän jalkapallon katsomisesta",
<add> ]
<add> expected_text = ["I like to read books", "I like watching football"]
<add>
<add> @classmethod
<add> def setUpClass(cls) -> None:
<add> cls.model_name = "hf-internal-testing/test-opus-tatoeba-fi-en-v2"
<add> return cls
<add>
<add> @slow
<add> def test_batch_generation_en_fr(self):
<add> self._assert_generated_batch_equal_expected()
<add>
<add>
<ide> @require_torch
<ide> class TestConversionUtils(unittest.TestCase):
<ide> def test_renaming_multilingual(self):
<ide><path>tests/marian/test_tokenization_marian.py
<ide> def test_tokenizer_integration(self):
<ide> revision="1a8c2263da11e68e50938f97e10cd57820bd504c",
<ide> decode_kwargs={"use_source_tokenizer": True},
<ide> )
<add>
<add> def test_tokenizer_integration_seperate_vocabs(self):
<add> tokenizer = MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs")
<add>
<add> source_text = "Tämä on testi"
<add> target_text = "This is a test"
<add>
<add> expected_src_ids = [76, 7, 2047, 2]
<add> expected_target_ids = [69, 12, 11, 940, 2]
<add>
<add> src_ids = tokenizer(source_text).input_ids
<add> self.assertListEqual(src_ids, expected_src_ids)
<add>
<add> with tokenizer.as_target_tokenizer():
<add> target_ids = tokenizer(target_text).input_ids
<add> self.assertListEqual(target_ids, expected_target_ids)
<add>
<add> decoded = tokenizer.decode(target_ids, skip_special_tokens=True)
<add> self.assertEqual(decoded, target_text) | 6 |
Text | Text | add the example for broadcast receiver | 7accf8929bf17fbdc7ecaac733c7df15a8ac61b5 | <ide><path>guide/english/android-development/core-components/index.md
<ide> There are three kinds of services:
<ide> 
<ide>
<ide> ### [Broadcast receivers](https://developer.android.com/guide/components/broadcasts)
<del>A _Broadcast receiver_ is another component without user interface (except an optional status bar notification) that provides a gateway for the system to deliver events from/to the app, even when the latter hasn't been previously launched.
<add>A _Broadcast receiver_ is another component without user interface (except an optional status bar notification) that provides a gateway for the system to deliver events from/to the app, even when the latter hasn't been previously launched. For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging.
<ide>
<ide> ### [Content providers](https://developer.android.com/guide/topics/providers/content-providers)
<ide> A _Content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme.
<ide> For detailed information about the topic, see the official [Android fundamentals
<ide>
<ide> ### Advanced Android Development
<ide> To learn advanced Android programming concepts, see Google's [Advanced Android Development](https://developers.google.com/training/courses/android-advanced) course.
<del> | 1 |
Java | Java | fix failing test | 1a8629d40825c073b6863ae2ab748b647b28506a | <ide><path>spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java
<ide> protected void writeToResult(T t, HttpHeaders headers, Result result) throws IOE
<ide> */
<ide> protected XMLInputFactory createXmlInputFactory() {
<ide> XMLInputFactory inputFactory = XMLInputFactory.newInstance();
<del> inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
<add> inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
<ide> return inputFactory;
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java
<ide> public void readXmlTypeSet() throws Exception {
<ide>
<ide> @Test
<ide> @SuppressWarnings("unchecked")
<del> public void readXmlRootElementWithExternalEntity() throws Exception {
<add> public void readXmlRootElementExternalEntityDisabled() throws Exception {
<ide>
<ide> Resource external = new ClassPathResource("external.txt", getClass());
<ide> String content = "<!DOCTYPE root [" +
<ide> public void readXmlRootElementExternalEntityEnabled() throws Exception {
<ide> " <list><rootElement><type s=\"1\"/><external>&ext;</external></rootElement></list>";
<ide> MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
<ide>
<del> // Now read with
<ide> Jaxb2CollectionHttpMessageConverter<?> c = new Jaxb2CollectionHttpMessageConverter<Collection<Object>>() {
<ide> @Override
<ide> protected XMLInputFactory createXmlInputFactory() { | 2 |
PHP | PHP | add test for bigint primary keys in sqlite | d8fac4ef159716ca75196bbd27cbf16906825c9a | <ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testColumnSqlPrimaryKey() {
<ide> $this->assertEquals('', $result, 'Integer primary keys are special in sqlite.');
<ide> }
<ide>
<add>/**
<add> * Test generating a bigint column that is a primary key.
<add> *
<add> * @return void
<add> */
<add> public function testColumnSqlPrimaryKeyBigInt() {
<add> $driver = $this->_getMockedDriver();
<add> $schema = new SqliteSchema($driver);
<add>
<add> $table = new Table('articles');
<add> $table->addColumn('id', [
<add> 'type' => 'biginteger',
<add> 'null' => false
<add> ])
<add> ->addConstraint('primary', [
<add> 'type' => 'primary',
<add> 'columns' => ['id']
<add> ]);
<add> $result = $schema->columnSql($table, 'id');
<add> $this->assertEquals($result, '"id" BIGINT NOT NULL');
<add>
<add> $result = $schema->constraintSql($table, 'primary');
<add> $this->assertEquals('CONSTRAINT "primary" PRIMARY KEY ("id")', $result, 'Bigint primary keys are not special.');
<add> }
<add>
<ide> /**
<ide> * Provide data for testing constraintSql
<ide> * | 1 |
PHP | PHP | add method assertsessionmissing(), fixe | 12a1823803ac007fbd650227c8236ba2915621c1 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithSession.php
<ide> public function assertSessionHasAll(array $bindings)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Assert that the session has not a given key.
<add> *
<add> * @param string|array $key
<add> * @return void
<add> */
<add> public function assertSessionMissing($key)
<add> {
<add> if (is_array($key)) {
<add> foreach( $key as $k )
<add> $this->assertSessionMissing($k);
<add> return ;
<add> }
<add>
<add> PHPUnit::assertFalse($this->app['session.store']->has($key), "Session has key: $key");
<add> }
<add>
<ide> /**
<ide> * Assert that the session has errors bound.
<ide> * | 1 |
Java | Java | fix javadoc errors | bfdc99ab799f652f33379bf8cc50d0cc5d08fd8a | <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java
<ide> public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
<ide> * FactoryBean will get proxied. This default behavior applies as of Spring 2.0.
<ide> * If you intend to proxy a FactoryBean instance itself (a rare use case, but
<ide> * Spring 1.2's default behavior), specify the bean name of the FactoryBean
<del> * including the factory-bean prefix "&": e.g. "&myFactoryBean".
<add> * including the factory-bean prefix "&": e.g. "&myFactoryBean".
<ide> * @see org.springframework.beans.factory.FactoryBean
<ide> * @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
<ide> */
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java
<ide> *
<ide> * def reader = new GroovyBeanDefinitionReader(myApplicationContext)
<ide> * reader.beans {
<del> * dataSource(BasicDataSource) { // <--- invokeMethod
<add> * dataSource(BasicDataSource) { // <--- invokeMethod
<ide> * driverClassName = "org.hsqldb.jdbcDriver"
<ide> * url = "jdbc:hsqldb:mem:grailsDB"
<del> * username = "sa" // <-- setProperty
<add> * username = "sa" // <-- setProperty
<ide> * password = ""
<ide> * settings = [mynew:"setting"]
<ide> * }
<ide> * sessionFactory(SessionFactory) {
<del> * dataSource = dataSource // <-- getProperty for retrieving references
<add> * dataSource = dataSource // <-- getProperty for retrieving references
<ide> * }
<ide> * myService(MyService) {
<del> * nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean
<add> * nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean
<ide> * dataSource = dataSource
<ide> * }
<ide> * }
<ide> * dataSource = dataSource
<ide> * }
<ide> * myService(MyService) {
<del> * nestedBean = { AnotherBean bean ->
<add> * nestedBean = { AnotherBean bean ->
<ide> * dataSource = dataSource
<ide> * }
<ide> * }
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/Configuration.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> * @Configuration
<ide> * public class AppConfig {
<ide> *
<del> * @Autowired Environment env;
<add> * @Autowired Environment env;
<ide> *
<ide> * @Bean
<ide> * public MyBean myBean() {
<ide> * @PropertySource("classpath:/com/acme/app.properties")
<ide> * public class AppConfig {
<ide> *
<del> * @Inject Environment env;
<add> * @Inject Environment env;
<ide> *
<ide> * @Bean
<ide> * public MyBean myBean() {
<ide> * @PropertySource("classpath:/com/acme/app.properties")
<ide> * public class AppConfig {
<ide> *
<del> * @Value("${bean.name}") String beanName;
<add> * @Value("${bean.name}") String beanName;
<ide> *
<ide> * @Bean
<ide> * public MyBean myBean() {
<ide> * @ImportResource("classpath:/com/acme/database-config.xml")
<ide> * public class AppConfig {
<ide> *
<del> * @Inject DataSource dataSource; // from XML
<add> * @Inject DataSource dataSource; // from XML
<ide> *
<ide> * @Bean
<ide> * public MyBean myBean() {
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * @EnableAspectJAutoProxy
<ide> * public class AppConfig {
<ide> *
<del> * // no explicit @Bean definitions required
<add> * // no explicit @Bean definitions required
<ide> * }</pre>
<ide> *
<ide> * <b>Note: {@code @EnableAspectJAutoProxy} applies to its local application context only,
<ide><path>spring-context/src/main/java/org/springframework/context/support/GenericGroovyApplicationContext.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> *
<ide> * def context = new GenericGroovyApplicationContext()
<ide> * context.reader.beans {
<del> * dataSource(BasicDataSource) { // <--- invokeMethod
<add> * dataSource(BasicDataSource) { // <--- invokeMethod
<ide> * driverClassName = "org.hsqldb.jdbcDriver"
<ide> * url = "jdbc:hsqldb:mem:grailsDB"
<del> * username = "sa" // <-- setProperty
<add> * username = "sa" // <-- setProperty
<ide> * password = ""
<ide> * settings = [mynew:"setting"]
<ide> * }
<ide> * sessionFactory(SessionFactory) {
<del> * dataSource = dataSource // <-- getProperty for retrieving references
<add> * dataSource = dataSource // <-- getProperty for retrieving references
<ide> * }
<ide> * myService(MyService) {
<del> * nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean
<add> * nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean
<ide> * dataSource = dataSource
<ide> * }
<ide> * }
<ide> * dataSource = dataSource
<ide> * }
<ide> * myService(MyService) {
<del> * nestedBean = { AnotherBean bean ->
<add> * nestedBean = { AnotherBean bean ->
<ide> * dataSource = dataSource
<ide> * }
<ide> * }
<ide><path>spring-context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> protected MessageFormat resolveCode(String code, Locale locale) {
<ide> * for a Locale, after merging all specified resource bundles.
<ide> * Either fetches the holder from the cache or freshly loads it.
<ide> * <p>Only used when caching resource bundle contents forever, i.e.
<del> * with cacheSeconds < 0. Therefore, merged properties are always
<add> * with cacheSeconds < 0. Therefore, merged properties are always
<ide> * cached forever.
<ide> */
<ide> protected PropertiesHolder getMergedProperties(Locale locale) {
<ide><path>spring-context/src/main/java/org/springframework/format/support/DefaultFormattingConversionService.java
<ide> * as {@code DefaultConversionService} exposes its own
<ide> * {@link DefaultConversionService#addDefaultConverters addDefaultConverters} method.
<ide> *
<del> * <p>Automatically registers formatters for JSR-354 Money & Currency, JSR-310 Date-Time
<add> * <p>Automatically registers formatters for JSR-354 Money & Currency, JSR-310 Date-Time
<ide> * and/or Joda-Time 2.x, depending on the presence of the corresponding API on the classpath.
<ide> *
<ide> * @author Chris Beams
<ide> public DefaultFormattingConversionService(
<ide>
<ide> /**
<ide> * Add formatters appropriate for most environments: including number formatters,
<del> * JSR-354 Money & Currency formatters, JSR-310 Date-Time and/or Joda-Time formatters,
<add> * JSR-354 Money & Currency formatters, JSR-310 Date-Time and/or Joda-Time formatters,
<ide> * depending on the presence of the corresponding API on the classpath.
<ide> * @param formatterRegistry the service to register default formatters with
<ide> */
<ide><path>spring-context/src/main/java/org/springframework/validation/Validator.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * wholly of whitespace), and that any password that is present is
<ide> * at least {@code 'MINIMUM_PASSWORD_LENGTH'} characters in length.
<ide> *
<del> * <pre class="code"> public class UserLoginValidator implements Validator {
<add> * <pre class="code">public class UserLoginValidator implements Validator {
<ide> *
<ide> * private static final int MINIMUM_PASSWORD_LENGTH = 6;
<ide> *
<ide> * ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
<ide> * UserLogin login = (UserLogin) target;
<ide> * if (login.getPassword() != null
<del> * && login.getPassword().trim().length() < MINIMUM_PASSWORD_LENGTH) {
<add> * && login.getPassword().trim().length() < MINIMUM_PASSWORD_LENGTH) {
<ide> * errors.rejectValue("password", "field.min.length",
<ide> * new Object[]{Integer.valueOf(MINIMUM_PASSWORD_LENGTH)},
<ide> * "The password must be at least [" + MINIMUM_PASSWORD_LENGTH + "] characters in length.");
<ide><path>spring-core/src/main/java/org/springframework/core/env/CommandLinePropertySource.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * evaluate true:
<ide> *
<ide> * <pre class="code">
<del> * CommandLinePropertySource<?> ps = ...
<add> * CommandLinePropertySource<?> ps = ...
<ide> * assert ps.containsProperty("o1") == true;
<ide> * assert ps.containsProperty("o2") == true;
<ide> * assert ps.containsProperty("o3") == false;
<ide> * will evaluate true:
<ide> *
<ide> * <pre class="code">
<del> * CommandLinePropertySource<?> ps = ...
<add> * CommandLinePropertySource<?> ps = ...
<ide> * assert ps.containsProperty("o1") == true;
<ide> * assert ps.containsProperty("o2") == true;
<ide> * assert ps.containsProperty("nonOptionArgs") == true;
<ide><path>spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * parser.accepts("option1");
<ide> * parser.accepts("option2").withRequiredArg();
<ide> * OptionSet options = parser.parse(args);
<del> * PropertySource<?> ps = new JOptCommandLinePropertySource(options);
<add> * PropertySource<?> ps = new JOptCommandLinePropertySource(options);
<ide> * // ...
<ide> * }</pre>
<ide> *
<ide><path>spring-core/src/main/java/org/springframework/core/env/SimpleCommandLinePropertySource.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> * <h3>Typical usage</h3>
<ide> * <pre class="code">
<ide> * public static void main(String[] args) {
<del> * PropertySource<?> ps = new SimpleCommandLinePropertySource(args);
<add> * PropertySource<?> ps = new SimpleCommandLinePropertySource(args);
<ide> * // ...
<ide> * }</pre>
<ide> *
<ide><path>spring-jms/src/main/java/org/springframework/jms/annotation/EnableJms.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * }
<ide> *
<ide> * @Bean
<del> * public JmsListenerContainerFactory<?> myJmsListenerContainerFactory() {
<add> * public JmsListenerContainerFactory<?> myJmsListenerContainerFactory() {
<ide> * // factory settings
<ide> * }
<ide> *
<ide> * }
<ide> *
<ide> * @Bean
<del> * public JmsListenerEndpointRegistry<?> myJmsListenerEndpointRegistry() {
<add> * public JmsListenerEndpointRegistry<?> myJmsListenerEndpointRegistry() {
<ide> * // registry configuration
<ide> * }
<ide> *
<ide> * }
<ide> *
<ide> * @Bean
<del> * public JmsListenerContainerFactory<?> anotherJmsListenerContainerFactory() {
<add> * public JmsListenerContainerFactory<?> anotherJmsListenerContainerFactory() {
<ide> * // ...
<ide> * }
<ide> *
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/AbstractMessageCondition.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public String toString() {
<ide>
<ide> /**
<ide> * The notation to use when printing discrete items of content.
<del> * For example " || " for URL patterns or " && " for param expressions.
<add> * For example " || " for URL patterns or " && " for param expressions.
<ide> */
<ide> protected abstract String getToStringInfix();
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateOperations.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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 interface HibernateOperations {
<ide> * @param firstResult the index of the first result object to be retrieved
<ide> * (numbered from 0)
<ide> * @param maxResults the maximum number of result objects to retrieve
<del> * (or <=0 for no limit)
<add> * (or <=0 for no limit)
<ide> * @return a {@link List} containing 0 or more persistent instances
<ide> * @throws DataAccessException in case of Hibernate errors
<ide> * @see DetachedCriteria#getExecutableCriteria(org.hibernate.Session)
<ide> public interface HibernateOperations {
<ide> * @param firstResult the index of the first result object to be retrieved
<ide> * (numbered from 0)
<ide> * @param maxResults the maximum number of result objects to retrieve
<del> * (or <=0 for no limit)
<add> * (or <=0 for no limit)
<ide> * @return a {@link List} containing 0 or more persistent instances
<ide> * @throws DataAccessException in case of Hibernate errors
<ide> * @see org.hibernate.criterion.Example#create(Object)
<ide> public interface HibernateOperations {
<ide> * @param firstResult the index of the first result object to be retrieved
<ide> * (numbered from 0)
<ide> * @param maxResults the maximum number of result objects to retrieve
<del> * (or <=0 for no limit)
<add> * (or <=0 for no limit)
<ide> * @return a {@link List} containing 0 or more persistent instances
<ide> * @throws DataAccessException in case of Hibernate errors
<ide> * @see org.hibernate.criterion.Example#create(Object)
<ide><path>spring-web/src/main/java/org/springframework/http/HttpStatus.java
<ide> public enum HttpStatus {
<ide> I_AM_A_TEAPOT(418, Series.CLIENT_ERROR, "I'm a teapot"),
<ide> /**
<ide> * @deprecated See
<del> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
<add> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff{@literal &}url2=draft-ietf-webdav-protocol-06.txt">
<ide> * WebDAV Draft Changes</a>
<ide> */
<ide> @Deprecated
<ide> INSUFFICIENT_SPACE_ON_RESOURCE(419, Series.CLIENT_ERROR, "Insufficient Space On Resource"),
<ide> /**
<ide> * @deprecated See
<del> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
<add> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff{@literal &}url2=draft-ietf-webdav-protocol-06.txt">
<ide> * WebDAV Draft Changes</a>
<ide> */
<ide> @Deprecated
<ide> METHOD_FAILURE(420, Series.CLIENT_ERROR, "Method Failure"),
<ide> /**
<ide> * @deprecated
<del> * See <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt">
<add> * See <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff{@literal &}url2=draft-ietf-webdav-protocol-06.txt">
<ide> * WebDAV Draft Changes</a>
<ide> */
<ide> @Deprecated
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>:
<ide> * support for other Java 8 types like {@link java.util.Optional}</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
<del> * support for Java 8 Date & Time API types</li>
<add> * support for Java 8 Date & Time API types</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
<ide> * support for Joda-Time types</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> * <p>Example usage with
<ide> * {@link MappingJackson2HttpMessageConverter}:
<ide> *
<del> * <pre class="code">
<del> * <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<del> * <property name="objectMapper">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<add> * <pre class="code">{@code
<add> * <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<add> * <property name="objectMapper">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<ide> * p:autoDetectFields="false"
<ide> * p:autoDetectGettersSetters="false"
<ide> * p:annotationIntrospector-ref="jaxbAnnotationIntrospector" />
<del> * </property>
<del> * </bean>
<del> * </pre>
<add> * </property>
<add> * </bean>
<add> * }</pre>
<ide> *
<ide> * <p>Example usage with MappingJackson2JsonView:
<ide> *
<del> * <pre class="code">
<del> * <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<del> * <property name="objectMapper">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<add> * <pre class="code">{@code
<add> * <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<add> * <property name="objectMapper">
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
<ide> * p:failOnEmptyBeans="false"
<ide> * p:indentOutput="true">
<del> * <property name="serializers">
<del> * <array>
<del> * <bean class="org.mycompany.MyCustomSerializer" />
<del> * </array>
<del> * </property>
<del> * </bean>
<del> * </property>
<del> * </bean>
<del> * </pre>
<add> * <property name="serializers">
<add> * <array>
<add> * <bean class="org.mycompany.MyCustomSerializer" />
<add> * </array>
<add> * </property>
<add> * </bean>
<add> * </property>
<add> * </bean>
<add> * }</pre>
<ide> *
<ide> * <p>In case there are no specific setters provided (for some rarely used options),
<ide> * you can still use the more general methods {@link #setFeaturesToEnable} and
<ide> * {@link #setFeaturesToDisable}.
<ide> *
<del> * <pre class="code">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<del> * <property name="featuresToEnable">
<del> * <array>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/>
<del> * </array>
<del> * </property>
<del> * <property name="featuresToDisable">
<del> * <array>
<del> * <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/>
<del> * </array>
<del> * </property>
<del> * </bean>
<del> * </pre>
<add> * <pre class="code">{@code
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<add> * <property name="featuresToEnable">
<add> * <array>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/>
<add> * </array>
<add> * </property>
<add> * <property name="featuresToDisable">
<add> * <array>
<add> * <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/>
<add> * </array>
<add> * </property>
<add> * </bean>
<add> * }</pre>
<ide> *
<ide> * <p>It also automatically registers the following well-known modules if they are
<ide> * detected on the classpath:
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-jdk8">jackson-datatype-jdk8</a>:
<ide> * support for other Java 8 types like {@link java.util.Optional}</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
<del> * support for Java 8 Date & Time API types</li>
<add> * support for Java 8 Date & Time API types</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
<ide> * support for Joda-Time types</li>
<ide> * <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
<ide> * <p>In case you want to configure Jackson's {@link ObjectMapper} with a custom {@link Module},
<ide> * you can register one or more such Modules by class name via {@link #setModulesToInstall}:
<ide> *
<del> * <pre class="code">
<del> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<del> * <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/>
<del> * </bean
<del> * </pre>
<add> * <pre class="code">{@code
<add> * <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<add> * <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/>
<add> * </bean
<add> * }</pre>
<ide> *
<ide> * <p>Compatible with Jackson 2.9 to 2.12, as of Spring 5.3.
<ide> *
<ide><path>spring-web/src/main/java/org/springframework/web/util/HtmlUtils.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 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 HtmlUtils {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding
<ide> * entity reference (e.g. {@code <}).
<ide> * <p>Reference:
<ide> public static String htmlEscape(String input) {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding
<ide> * entity reference (e.g. {@code <}) at least as required by the
<ide> * specified encoding. In other words, if a special character does
<ide> public static String htmlEscape(String input, String encoding) {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding numeric
<del> * reference in decimal format (&#<i>Decimal</i>;).
<add> * reference in decimal format (&#<i>Decimal</i>;).
<ide> * <p>Reference:
<ide> * <a href="https://www.w3.org/TR/html4/sgml/entities.html">
<ide> * https://www.w3.org/TR/html4/sgml/entities.html
<ide> public static String htmlEscapeDecimal(String input) {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding numeric
<del> * reference in decimal format (&#<i>Decimal</i>;) at least as required by the
<add> * reference in decimal format (&#<i>Decimal</i>;) at least as required by the
<ide> * specified encoding. In other words, if a special character does
<ide> * not have to be escaped for the given encoding, it may not be.
<ide> * <p>Reference:
<ide> public static String htmlEscapeDecimal(String input, String encoding) {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding numeric
<del> * reference in hex format (&#x<i>Hex</i>;).
<add> * reference in hex format (&#x<i>Hex</i>;).
<ide> * <p>Reference:
<ide> * <a href="https://www.w3.org/TR/html4/sgml/entities.html">
<ide> * https://www.w3.org/TR/html4/sgml/entities.html
<ide> public static String htmlEscapeHex(String input) {
<ide>
<ide> /**
<ide> * Turn special characters into HTML character references.
<del> * <p>Handles complete character set defined in HTML 4.01 recommendation.
<add> * <p>Handles the complete character set defined in the HTML 4.01 recommendation.
<ide> * <p>Escapes all special characters to their corresponding numeric
<del> * reference in hex format (&#x<i>Hex</i>;) at least as required by the
<add> * reference in hex format (&#x<i>Hex</i>;) at least as required by the
<ide> * specified encoding. In other words, if a special character does
<ide> * not have to be escaped for the given encoding, it may not be.
<ide> * <p>Reference:
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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 List<String> getVariableNames() {
<ide> * UriTemplate template = new UriTemplate("https://example.com/hotels/{hotel}/bookings/{booking}");
<ide> * Map<String, String> uriVariables = new HashMap<String, String>();
<ide> * uriVariables.put("booking", "42");
<del> * uriVariables.put("hotel", "Rest & Relax");
<add> * uriVariables.put("hotel", "Rest & Relax");
<ide> * System.out.println(template.expand(uriVariables));
<ide> * </pre>
<ide> * will print: <blockquote>{@code https://example.com/hotels/Rest%20%26%20Relax/bookings/42}</blockquote>
<ide> public URI expand(Map<String, ?> uriVariables) {
<ide> * <p>Example:
<ide> * <pre class="code">
<ide> * UriTemplate template = new UriTemplate("https://example.com/hotels/{hotel}/bookings/{booking}");
<del> * System.out.println(template.expand("Rest & Relax", 42));
<add> * System.out.println(template.expand("Rest & Relax", 42));
<ide> * </pre>
<ide> * will print: <blockquote>{@code https://example.com/hotels/Rest%20%26%20Relax/bookings/42}</blockquote>
<ide> * @param uriVariableValues the array of URI variables
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriUtils.java
<ide> public static String encodeQueryParam(String queryParam, Charset charset) {
<ide> * Encode the query parameters from the given {@code MultiValueMap} with UTF-8.
<ide> * <p>This can be used with {@link UriComponentsBuilder#queryParams(MultiValueMap)}
<ide> * when building a URI from an already encoded template.
<del> * <pre class="code">
<del> * MultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
<add> * <pre class="code">{@code
<add> * MultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
<ide> * // add to params...
<ide> *
<ide> * ServletUriComponentsBuilder.fromCurrentRequest()
<ide> * .queryParams(UriUtils.encodeQueryParams(params))
<ide> * .build(true)
<ide> * .toUriString();
<del> * </pre>
<add> * }</pre>
<ide> * @param params the parameters to encode
<ide> * @return a new {@code MultiValueMap} with the encoded names and values
<ide> * @since 5.2.3
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/CompositeRequestCondition.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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>
<ide> /**
<ide> * Implements the {@link RequestCondition} contract by delegating to multiple
<del> * {@code RequestCondition} types and using a logical conjunction (' && ') to
<add> * {@code RequestCondition} types and using a logical conjunction ({@code ' && '}) to
<ide> * ensure all conditions match a given request.
<ide> *
<ide> * <p>When {@code CompositeRequestCondition} instances are combined or compared
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/HeadersRequestCondition.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * A logical conjunction (' && ') request condition that matches a request against
<add> * A logical conjunction ({@code ' && '}) request condition that matches a request against
<ide> * a set of header expressions with syntax defined in {@link RequestMapping#headers()}.
<ide> *
<ide> * <p>Expressions passed to the constructor with header names 'Accept' or
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ParamsRequestCondition.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * A logical conjunction (' && ') request condition that matches a request against
<add> * A logical conjunction ({@code ' && '}) request condition that matches a request against
<ide> * a set parameter expressions with syntax defined in {@link RequestMapping#params()}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/CompositeRequestCondition.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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>
<ide> /**
<ide> * Implements the {@link RequestCondition} contract by delegating to multiple
<del> * {@code RequestCondition} types and using a logical conjunction (' && ') to
<add> * {@code RequestCondition} types and using a logical conjunction ({@code ' && '}) to
<ide> * ensure all conditions match a given request.
<ide> *
<ide> * <p>When {@code CompositeRequestCondition} instances are combined or compared
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/HeadersRequestCondition.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> import org.springframework.web.cors.CorsUtils;
<ide>
<ide> /**
<del> * A logical conjunction (' && ') request condition that matches a request against
<add> * A logical conjunction ({@code ' && '}) request condition that matches a request against
<ide> * a set of header expressions with syntax defined in {@link RequestMapping#headers()}.
<ide> *
<ide> * <p>Expressions passed to the constructor with header names 'Accept' or
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ParamsRequestCondition.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> import org.springframework.web.util.WebUtils;
<ide>
<ide> /**
<del> * A logical conjunction (' && ') request condition that matches a request against
<add> * A logical conjunction ({@code ' && '}) request condition that matches a request against
<ide> * a set parameter expressions with syntax defined in {@link RequestMapping#params()}.
<ide> *
<ide> * @author Arjen Poutsma
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
<ide> public static <T> T controller(Class<T> controllerType) {
<ide> * A JSP can prepare a URL to the controller method as follows:
<ide> *
<ide> * <pre class="code">
<del> * <%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<add> * <%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<ide> *
<ide> * <a href="${s:mvcUrl('PC#getPerson').arg(0,"123").build()}">Get Person</a>
<ide> * </pre>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java
<ide> String createUrl() throws JspException {
<ide> * @param usedParams set of parameter names that have been applied as
<ide> * template params
<ide> * @param includeQueryStringDelimiter true if the query string should start
<del> * with a '?' instead of '&'
<add> * with a '?' instead of '&'
<ide> * @return the query string
<ide> */
<ide> protected String createQueryString(List<Param> params, Set<String> usedParams, boolean includeQueryStringDelimiter) | 28 |
Javascript | Javascript | remove dead code | 717f24feb43cb71538a7c07e4aa013c916640006 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.dump = function(object) {
<ide> </pre>
<ide> *
<ide> * Now we setup the mock backend and create the test specs.
<del> *
<add> *
<ide> <pre>
<ide> // testing controller
<ide> describe('MyController', function() {
<ide> angular.mock.dump = function(object) {
<ide> it('should send auth header', function() {
<ide> var controller = createController();
<ide> $httpBackend.flush();
<del>
<add>
<ide> $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
<ide> // check if the header was send, if it wasn't the expectation won't
<ide> // match the request and the test will fail
<ide> angular.mock.clearDataCache = function() {
<ide> };
<ide>
<ide>
<del>window.jstestdriver && (function(window) {
<del> /**
<del> * Global method to output any number of objects into JSTD console. Useful for debugging.
<del> */
<del> window.dump = function() {
<del> var args = [];
<del> angular.forEach(arguments, function(arg) {
<del> args.push(angular.mock.dump(arg));
<del> });
<del> jstestdriver.console.log.apply(jstestdriver.console, args);
<del> if (window.console) {
<del> window.console.log.apply(window.console, args);
<del> }
<del> };
<del>})(window);
<del>
<ide>
<ide> (window.jasmine || window.mocha) && (function(window) {
<ide>
<ide><path>test/ngMock/angular-mocksSpec.js
<ide> describe('ngMock', function() {
<ide> expect(d($rootScope)).toMatch(/Scope\(.*\): \{/);
<ide> expect(d($rootScope)).toMatch(/{"abc":"123"}/);
<ide> }));
<del>
<del>
<del> it('should be published on window', function(){
<del> expect(window.dump instanceof Function).toBe(true);
<del> });
<ide> });
<ide>
<ide> | 2 |
Ruby | Ruby | preserve backtrace for download errors | 912a586d15daaa9daf4c4831dc5cc9022acc2b62 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(formula)
<ide>
<ide> # Raised in Resource.fetch
<ide> class DownloadError < RuntimeError
<del> def initialize(resource, e)
<add> def initialize(resource, cause)
<ide> super <<-EOS.undent
<ide> Failed to download resource #{resource.download_name.inspect}
<del> #{e.message}
<add> #{cause.message}
<ide> EOS
<add> set_backtrace(cause.backtrace)
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | improve coverage on worker threads | 068efba973001901767ba4354d5bc459fc7d27fc | <ide><path>test/parallel/test-worker-unsupported-things.js
<ide> if (!process.env.HAS_STARTED_WORKER) {
<ide> assert.strictEqual(process.debugPort, before);
<ide> }
<ide>
<add> {
<add> const mask = 0o600;
<add> assert.throws(() => { process.umask(mask); }, {
<add> code: 'ERR_WORKER_UNSUPPORTED_OPERATION',
<add> message: 'Setting process.umask() is not supported in workers'
<add> });
<add> }
<add>
<ide> const stubs = ['abort', 'chdir', 'send', 'disconnect'];
<ide>
<ide> if (!common.isWindows) {
<ide> if (!process.env.HAS_STARTED_WORKER) {
<ide> assert.strictEqual(process[fn].disabled, true);
<ide> assert.throws(() => {
<ide> process[fn]();
<del> }, { code: 'ERR_WORKER_UNSUPPORTED_OPERATION' });
<add> }, {
<add> code: 'ERR_WORKER_UNSUPPORTED_OPERATION',
<add> message: `process.${fn}() is not supported in workers`
<add> });
<ide> });
<ide>
<ide> ['channel', 'connected'].forEach((fn) => {
<ide> assert.throws(() => {
<ide> process[fn]; // eslint-disable-line no-unused-expressions
<del> }, { code: 'ERR_WORKER_UNSUPPORTED_OPERATION' });
<add> }, {
<add> code: 'ERR_WORKER_UNSUPPORTED_OPERATION',
<add> message: `process.${fn} is not supported in workers`
<add> });
<ide> });
<ide>
<ide> assert.strictEqual('_startProfilerIdleNotifier' in process, false); | 1 |
Python | Python | modify some examples | 1220d2d3cae9382338c34f9a0be3a9c116cd63e0 | <ide><path>examples/app/myapp.py
<ide> from celery import Celery
<ide>
<ide> app = Celery('myapp', broker='amqp://guest@localhost//')
<del>
<add># New When celery > 3.1, must specify result_backend
<add>app.conf.CELERY_RESULT_BACKEND = 'amqp'
<ide>
<ide> @app.task()
<ide> def add(x, y):
<ide><path>examples/celery_http_gateway/settings.py
<ide>
<ide> MANAGERS = ADMINS
<ide>
<add># Notes: Django 1.3 deprecated the old-style way of specifying databases,
<add># using 'django.db.backends.XXX' where XXX is one of:
<ide> # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
<del>DATABASE_ENGINE = 'sqlite3'
<add>import django
<add>if django.VERSION[:3] > (1, 3):
<add> DATABASE_ENGINE = 'django.db.backends.sqlite3'
<add>else:
<add> DATABASE_ENGINE = 'sqlite3'
<ide>
<ide> # path to database file if using sqlite3.
<ide> DATABASE_NAME = 'development.db'
<ide> # Set to empty string for default. Not used with sqlite3.
<ide> DATABASE_PORT = ''
<ide>
<add>DATABASES = {
<add> 'default': {
<add> 'ENGINE': DATABASE_ENGINE,
<add> 'NAME': DATABASE_NAME,
<add> 'USER': DATABASE_USER,
<add> 'PASSWORD': DATABASE_PASSWORD,
<add> 'HOST': DATABASE_HOST,
<add> 'PORT': DATABASE_PORT,
<add> }
<add>}
<add>
<ide> # Local time zone for this installation. Choices can be found here:
<ide> # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
<ide> # although not all choices may be available on all operating systems. | 2 |
Javascript | Javascript | use helper for readability" | ff3989572acd50419e5b833776b1d2d0546fa616 | <ide><path>lib/internal/js_stream_socket.js
<ide> const kCurrentWriteRequest = Symbol('kCurrentWriteRequest');
<ide> const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest');
<ide> const kPendingShutdownRequest = Symbol('kPendingShutdownRequest');
<ide>
<del>function checkReusedHandle(self) {
<del> let socket = self[owner_symbol];
<add>function isClosing() {
<add> let socket = this[owner_symbol];
<ide>
<del> if (socket.constructor.name === 'ReusedHandle')
<add> if (socket.constructor.name === 'ReusedHandle') {
<ide> socket = socket.handle;
<del>
<del> return socket;
<del>}
<del>
<del>function isClosing() {
<del> const socket = checkReusedHandle(this);
<add> }
<ide>
<ide> return socket.isClosing();
<ide> }
<ide>
<ide> function onreadstart() {
<del> const socket = checkReusedHandle(this);
<add> let socket = this[owner_symbol];
<add>
<add> if (socket.constructor.name === 'ReusedHandle') {
<add> socket = socket.handle;
<add> }
<ide>
<ide> return socket.readStart();
<ide> }
<ide>
<ide> function onreadstop() {
<del> const socket = checkReusedHandle(this);
<add> let socket = this[owner_symbol];
<add>
<add> if (socket.constructor.name === 'ReusedHandle') {
<add> socket = socket.handle;
<add> }
<ide>
<ide> return socket.readStop();
<ide> }
<ide>
<ide> function onshutdown(req) {
<del> const socket = checkReusedHandle(this);
<add> let socket = this[owner_symbol];
<add>
<add> if (socket.constructor.name === 'ReusedHandle') {
<add> socket = socket.handle;
<add> }
<ide>
<ide> return socket.doShutdown(req);
<ide> }
<ide>
<ide> function onwrite(req, bufs) {
<del> const socket = checkReusedHandle(this);
<add> let socket = this[owner_symbol];
<add>
<add> if (socket.constructor.name === 'ReusedHandle') {
<add> socket = socket.handle;
<add> }
<ide>
<ide> return socket.doWrite(req, bufs);
<ide> } | 1 |
Ruby | Ruby | extend cmd_fail to all non-zero exit codes (#595) | 39453691ba3208dbd2e6ce1fd341d430b31dff55 | <ide><path>Library/Homebrew/test/test_integration_cmds.rb
<ide> def cmd(*args)
<ide> def cmd_fail(*args)
<ide> output = cmd_output(*args)
<ide> status = $?.exitstatus
<del> $stderr.puts "\n#{output}" if status != 1
<del> assert_equal 1, status
<add> $stderr.puts "\n#{output}" if status == 0
<add> refute_equal 0, status
<ide> output
<ide> end
<ide> | 1 |
Ruby | Ruby | view path strict type casting | e65d41a47af0c56cb2d60868e6ad2ba01d324d48 | <ide><path>actionview/lib/action_view/lookup_context.rb
<ide> def any?(name, prefixes = [], partial = false)
<ide> # Whenever setting view paths, makes a copy so that we can manipulate them in
<ide> # instance objects as we wish.
<ide> def build_view_paths(paths)
<del> ActionView::PathSet.new(Array(paths))
<add> if ActionView::PathSet === paths
<add> paths
<add> else
<add> ActionView::PathSet.new(Array(paths))
<add> end
<ide> end
<ide>
<ide> # Compute details hash and key according to user options (e.g. passed from #render).
<ide><path>actionview/lib/action_view/path_set.rb
<ide> def typecast(paths)
<ide> case path
<ide> when Pathname, String
<ide> FileSystemResolver.new path.to_s
<del> else
<add> when Resolver
<ide> path
<add> else
<add> raise TypeError, "#{path.inspect} is not a valid path: must be a String, Pathname, or Resolver"
<ide> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | change a test to be relevant in fiber | c6f10e2cee8c0ef6ceddf032ca318960d43820e7 | <ide><path>src/renderers/dom/__tests__/ReactDOMProduction-test.js
<ide> describe('ReactDOMProduction', () => {
<ide> expect(function() {
<ide> class Component extends React.Component {
<ide> render() {
<del> return ['this is wrong'];
<add> return undefined;
<ide> }
<ide> }
<ide> | 1 |
Text | Text | shorten troubleshooting wording | c91d0a99e211229bfa6630e7b80895e27fbb2f24 | <ide><path>CONTRIBUTING.md
<ide> Contributing to Homebrew
<ide>
<ide> Reporting Bugs
<ide> --------------
<del>Please run:
<add>First, please run `brew update` and `brew doctor`.
<ide>
<del>* `brew update`
<del>* `brew doctor`
<del>
<del>Please read:
<del>
<del>* [Troubleshooting Checklist](https://github.com/Homebrew/homebrew/wiki/troubleshooting)
<add>Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebrew/wiki/troubleshooting).
<ide>
<ide> **If you don't read these it will take us far longer to help you with your problem.**
<ide> | 1 |
Text | Text | add the text "indexed array" in example comment | 6ac087f16b597780dedd9649eedb633359e4d13c | <ide><path>client/src/pages/guide/english/php/array/index.md
<ide> Here is an example:
<ide> ```
<ide> <?php
<ide> // array without keys
<add>// This array is also an example of "indexed array"
<ide> $bikes = array("Suzuki","BMW","Yamaha");
<ide> echo "I like " . $bikes[0] . ", " . $bikes[1] . " and " . $bikes[2] . ".";
<ide> ?> | 1 |
Python | Python | fix creation for floating ips | ba21cf38629424e6c0f1d67adc0874c72fc1557c | <ide><path>libcloud/common/openstack.py
<ide> def parse_error(self):
<ide> context = self.connection.context
<ide> driver = self.connection.driver
<ide> key_pair_name = context.get('key_pair_name', None)
<del>
<ide> if len(values) > 0 and values[0]['code'] == 404 and key_pair_name:
<ide> raise KeyPairDoesNotExistError(name=key_pair_name,
<ide> driver=driver)
<ide><path>libcloud/compute/drivers/openstack.py
<ide> def ex_list_floating_ip_pools(self):
<ide> self.connection.request('/os-floating-ip-pools').object)
<ide>
<ide> def _to_floating_ips(self, obj):
<del> ip_elements = obj['floating_ips']
<add> ip_elements = obj['floatingips']
<ide> return [self._to_floating_ip(ip) for ip in ip_elements]
<ide>
<ide> def _to_floating_ip(self, obj):
<del> return OpenStack_1_1_FloatingIpAddress(id=obj['id'],
<del> ip_address=obj['ip'],
<del> pool=None,
<del> node_id=obj['instance_id'],
<del> driver=self)
<add> return OpenStack_1_1_FloatingIpAddress(id=obj.pop('id'),
<add> floating_ip_address=obj.pop('floating_ip_address'),
<add> floating_network_id=obj.pop('floating_network_id'),
<add> fixed_ip_address=obj.pop('fixed_ip_address', ''),
<add> status=obj.pop('status', False),
<add> port_id=obj.pop('port_id', None),
<add> extra=obj)
<add>
<ide>
<add> @_neutron_endpoint
<ide> def ex_list_floating_ips(self):
<ide> """
<ide> List floating IPs
<ide>
<ide> :rtype: ``list`` of :class:`OpenStack_1_1_FloatingIpAddress`
<ide> """
<ide> return self._to_floating_ips(
<del> self.connection.request('/os-floating-ips').object)
<add> self.connection.request('/v2.0/floatingips').object)
<add>
<add> @_neutron_endpoint
<add> def ex_list_ports(self):
<add> """
<add> List ports
<add> """
<add> resp = self.connection.request('/v2.0/ports', method='GET').object
<add>
<add> return resp['ports']
<ide>
<ide> def ex_get_floating_ip(self, ip):
<ide> """
<ide> def ex_get_floating_ip(self, ip):
<ide> ip_obj, = [x for x in floating_ips if x.ip_address == ip]
<ide> return ip_obj
<ide>
<del> def ex_create_floating_ip(self, ip_pool=None):
<del> """
<del> Create new floating IP. The ip_pool attribute is optional only if your
<del> infrastructure has only one IP pool available.
<del>
<del> :param ip_pool: name of the floating IP pool
<del> :type ip_pool: ``str``
<add> @_neutron_endpoint
<add> def ex_create_floating_ip(self, floating_network_id, port_id=None):
<add> data = {
<add> "floatingip":
<add> {
<add> "port_id": port_id,
<add> "floating_network_id": floating_network_id
<add> }
<add> }
<ide>
<del> :rtype: :class:`OpenStack_1_1_FloatingIpAddress`
<del> """
<del> data = {'pool': ip_pool} if ip_pool is not None else {}
<del> resp = self.connection.request('/os-floating-ips',
<del> method='POST',
<del> data=data)
<add> resp = self.connection.request('/v2.0/floatingips', method='POST',
<add> data=data).object
<ide>
<del> data = resp.object['floating_ip']
<del> id = data['id']
<del> ip_address = data['ip']
<del> return OpenStack_1_1_FloatingIpAddress(id=id,
<del> ip_address=ip_address,
<del> pool=None,
<del> node_id=None,
<del> driver=self)
<add> return self._to_floating_ip(resp['floatingip'])
<ide>
<del> def ex_delete_floating_ip(self, ip):
<add> @_neutron_endpoint
<add> def ex_delete_floating_ip(self, floating_ip_id):
<ide> """
<ide> Delete specified floating IP
<ide>
<ide> def ex_delete_floating_ip(self, ip):
<ide>
<ide> :rtype: ``bool``
<ide> """
<del> resp = self.connection.request('/os-floating-ips/%s' % ip.id,
<del> method='DELETE')
<add> resp = self.connection.request(
<add> '/v2.0/floatingips/%s' % floating_ip_id, method='DELETE')
<ide> return resp.status in (httplib.NO_CONTENT, httplib.ACCEPTED)
<ide>
<ide> def ex_attach_floating_ip_to_node(self, node, ip):
<ide> def ex_detach_floating_ip_from_node(self, node, ip):
<ide> method='POST', data=data)
<ide> return resp.status == httplib.ACCEPTED
<ide>
<add> @_neutron_endpoint
<add> def ex_associate_floating_ip_to_node(self, floating_ip_id, port_id):
<add> data = {
<add> "floatingip":
<add> {
<add> "port_id": port_id
<add> }
<add> }
<add> resp = self.connection.request('/v2.0/floatingips/%s' % floating_ip_id,
<add> method='PUT',
<add> data=data).object
<add>
<add> return self._to_floating_ip(resp['floatingip'])
<add>
<add> @_neutron_endpoint
<add> def ex_disassociate_floating_ip_from_node(self, floating_ip_id):
<add> data = {
<add> "floatingip":
<add> {
<add> "port_id": None
<add> }
<add> }
<add> resp = self.connection.request('/v2.0/floatingips/%s' % floating_ip_id,
<add> method='PUT',
<add> data=data).object
<add>
<add> return self._to_floating_ip(resp['floatingip'])
<add>
<ide> def ex_get_metadata_for_node(self, node):
<ide> """
<ide> Return the metadata associated with the node.
<ide> def _to_floating_ips(self, obj):
<ide> return [self._to_floating_ip(ip) for ip in ip_elements]
<ide>
<ide> def _to_floating_ip(self, obj):
<del> return OpenStack_1_1_FloatingIpAddress(id=obj['id'],
<del> ip_address=obj['ip'],
<del> pool=self,
<del> node_id=obj['instance_id'],
<del> driver=self.connection.driver)
<add> return OpenStack_1_1_FloatingIpAddress(id=obj.pop('id'),
<add> floating_ip_address=obj.pop('floating_ip_address'),
<add> floating_network_id=obj.pop('floating_network_id'),
<add> fixed_ip_address=obj.pop('fixed_ip_address', ''),
<add> status=obj.pop('status', False),
<add> port_id=obj.pop('port_id', None),
<add> extra=obj)
<add>
<ide>
<ide> def get_floating_ip(self, ip):
<ide> """
<ide> def __repr__(self):
<ide> return ('<OpenStack_1_1_FloatingIpPool: name=%s>' % self.name)
<ide>
<ide>
<add>
<ide> class OpenStack_1_1_FloatingIpAddress(object):
<ide> """
<ide> Floating IP info.
<ide> """
<ide>
<del> def __init__(self, id, ip_address, pool, node_id=None, driver=None):
<add> def __init__(self, id, floating_ip_address, floating_network_id, fixed_ip_address="", status=False, port_id=None,
<add> extra={}):
<ide> self.id = str(id)
<del> self.ip_address = ip_address
<del> self.pool = pool
<del> self.node_id = node_id
<del> self.driver = driver
<del>
<del> def delete(self):
<del> """
<del> Delete this floating IP
<del>
<del> :rtype: ``bool``
<del> """
<del> if self.pool is not None:
<del> return self.pool.delete_floating_ip(self)
<del> elif self.driver is not None:
<del> return self.driver.ex_delete_floating_ip(self)
<add> self.floating_ip_address = floating_ip_address
<add> self.floating_network_id = floating_network_id
<add> self.fixed_ip_address = fixed_ip_address
<add> self.status = status
<add> self.port_id = port_id
<add> self.extra = extra
<ide>
<ide> def __repr__(self):
<ide> return ('<OpenStack_1_1_FloatingIpAddress: id=%s, ip_addr=%s,'
<del> ' pool=%s, driver=%s>'
<del> % (self.id, self.ip_address, self.pool, self.driver))
<add> ' attached_to_ip=%s>'
<add> % (self.id, self.floating_ip_address, self.fixed_ip_address)) | 2 |
Go | Go | remove pools_nopool.go & build tag from pools.go | f01d755cd0af7b17596cc084871f7f032995cac3 | <ide><path>pkg/pools/pools.go
<del>// +build go1.3
<del>
<ide> // Package pools provides a collection of pools which provide various
<ide> // data types with buffers. These can be used to lower the number of
<ide> // memory allocations and reuse buffers.
<ide><path>pkg/pools/pools_nopool.go
<del>// +build !go1.3
<del>
<del>package pools
<del>
<del>import (
<del> "bufio"
<del> "io"
<del>
<del> "github.com/docker/docker/pkg/ioutils"
<del>)
<del>
<del>var (
<del> BufioReader32KPool *BufioReaderPool
<del> BufioWriter32KPool *BufioWriterPool
<del>)
<del>
<del>const buffer32K = 32 * 1024
<del>
<del>type BufioReaderPool struct {
<del> size int
<del>}
<del>
<del>func init() {
<del> BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K)
<del> BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K)
<del>}
<del>
<del>func newBufioReaderPoolWithSize(size int) *BufioReaderPool {
<del> return &BufioReaderPool{size: size}
<del>}
<del>
<del>func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader {
<del> return bufio.NewReaderSize(r, bufPool.size)
<del>}
<del>
<del>func (bufPool *BufioReaderPool) Put(b *bufio.Reader) {
<del> b.Reset(nil)
<del>}
<del>
<del>func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser {
<del> return ioutils.NewReadCloserWrapper(r, func() error {
<del> if readCloser, ok := r.(io.ReadCloser); ok {
<del> return readCloser.Close()
<del> }
<del> return nil
<del> })
<del>}
<del>
<del>type BufioWriterPool struct {
<del> size int
<del>}
<del>
<del>func newBufioWriterPoolWithSize(size int) *BufioWriterPool {
<del> return &BufioWriterPool{size: size}
<del>}
<del>
<del>func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer {
<del> return bufio.NewWriterSize(w, bufPool.size)
<del>}
<del>
<del>func (bufPool *BufioWriterPool) Put(b *bufio.Writer) {
<del> b.Reset(nil)
<del>}
<del>
<del>func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser {
<del> return ioutils.NewWriteCloserWrapper(w, func() error {
<del> buf.Flush()
<del> if writeCloser, ok := w.(io.WriteCloser); ok {
<del> return writeCloser.Close()
<del> }
<del> return nil
<del> })
<del>} | 2 |
Javascript | Javascript | add common.mustcall test-dgram-listen-after-bind | eecf100049dd2d3ce6e4864a553cca43561a6a91 | <ide><path>test/parallel/test-dgram-listen-after-bind.js
<ide>
<ide> 'use strict';
<ide> require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide>
<ide> const timer = setTimeout(() => {
<ide> socket.close();
<ide> }, 100);
<ide>
<del>socket.on('listening', () => {
<add>socket.on('listening', common.mustCall(() => {
<ide> clearTimeout(timer);
<ide> fired = true;
<ide> socket.close();
<del>});
<add>}));
<ide>
<del>socket.on('close', () => {
<add>socket.on('close', common.mustCall(() => {
<ide> assert(fired, 'listening should fire after bind');
<del>});
<add>})); | 1 |
Javascript | Javascript | avoid turbo cache miss on root package change | ec7609e28831429745ff5f93b201bcdd25056ede | <ide><path>scripts/normalize-version-bump.js
<ide> const writeJson = async (filePath, data) =>
<ide> await normalizeVersions(path.join(cwd, 'lerna.json'))
<ide> await fs.unlink(path.join(cwd, 'pnpm-lock.yaml'))
<ide> await fs.writeFile(path.join(cwd, 'pnpm-lock.yaml'), '')
<add>
<add> const rootPkgJsonPath = path.join(cwd, 'package.json')
<add> await writeJson(rootPkgJsonPath, {
<add> name: 'nextjs-project',
<add> version: '0.0.0',
<add> private: true,
<add> workspaces: ['packages/*'],
<add> scripts: {},
<add> })
<ide> })()
<ide><path>scripts/run-for-change.js
<ide> const CHANGE_ITEM_GROUPS = {
<ide> 'CODE_OF_CONDUCT.md',
<ide> 'readme.md',
<ide> ],
<del> 'next-swc': ['packages/next-swc'],
<add> 'next-swc': ['packages/next-swc', 'scripts/normalize-version-bump.js'],
<ide> }
<ide>
<ide> async function main() { | 2 |
Javascript | Javascript | avoid regex in istypedarray | c8768d12f2f0b31f9ac971aeac6d2c17c9ff3db5 | <ide><path>src/Angular.js
<ide> function isPromiseLike(obj) {
<ide> }
<ide>
<ide>
<del>var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
<add>var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
<ide> function isTypedArray(value) {
<del> return TYPED_ARRAY_REGEXP.test(toString.call(value));
<add> return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
<ide> }
<ide>
<ide> | 1 |
Python | Python | add batch_set_value for faster tf weight loading | 5dad3786f6a34c15ce11ee862bab7a59ed713d68 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def set_value(x, value):
<ide> tf.assign(x, np.asarray(value)).op.run(session=get_session())
<ide>
<ide>
<add>def batch_set_value(tuples):
<add> '''Sets the values of many tensor variables at once.
<add>
<add> # Arguments
<add> tuples: a list of tuples `(tensor, value)`.
<add> `value` should be a Numpy array.
<add> '''
<add> if tuples:
<add> ops = [tf.assign(x, np.asarray(value)) for x, value in tuples]
<add> get_session().run(ops)
<add>
<ide> # GRAPH MANIPULATION
<ide>
<ide> class Function(object):
<ide><path>keras/backend/theano_backend.py
<ide> def set_value(x, value):
<ide> x.set_value(np.asarray(value, dtype=x.dtype))
<ide>
<ide>
<add>def batch_set_value(tuples):
<add> for x, value in tuples:
<add> x.set_value(np.asarray(value, dtype=x.dtype))
<add>
<add>
<ide> # GRAPH MANIPULATION
<ide>
<ide> class Function(object):
<ide><path>keras/engine/topology.py
<ide> def set_weights(self, weights):
<ide> '" with a weight list of length ' + str(len(weights)) +
<ide> ', but the layer was expecting ' + str(len(params)) +
<ide> ' weights. Provided weights: ' + str(weights))
<add> if not params:
<add> return
<add> weight_value_tuples = []
<ide> for p, w in zip(params, weights):
<ide> if K.get_value(p).shape != w.shape:
<ide> raise Exception('Layer weight shape ' +
<ide> str(K.get_value(p).shape) +
<ide> ' not compatible with '
<ide> 'provided weight shape ' + str(w.shape))
<del> K.set_value(p, w)
<add> weight_value_tuples.append((p, w))
<add> K.batch_set_value(weight_value_tuples)
<ide>
<ide> def get_weights(self):
<ide> '''Returns the current weights of the layer,
<ide> def load_weights(self, filepath):
<ide> ' layers into a model with ' +
<ide> str(len(flattened_layers)) + ' layers.')
<ide>
<add> # we batch weight value assignments in a single backend call
<add> # which provides a speedup in TensorFlow.
<add> weight_value_tuples = []
<ide> for k, name in enumerate(layer_names):
<ide> g = f[name]
<ide> weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
<ide> if len(weight_names):
<del> weights = [g[weight_name] for weight_name in weight_names]
<del> flattened_layers[k].set_weights(weights)
<add> weight_values = [g[weight_name] for weight_name in weight_names]
<add> layer = flattened_layers[k]
<add> symbolic_weights = layer.trainable_weights + layer.non_trainable_weights
<add> if len(weight_values) != len(symbolic_weights):
<add> raise Exception('Layer #' + str(k) +
<add> ' (named "' + layer.name +
<add> '" in the current model) was found to '
<add> 'correspond to layer ' + name +
<add> ' in the save file. '
<add> 'However the new layer ' + layer.name +
<add> ' expects ' + str(len(symbolic_weights)) +
<add> ' weights, but the saved weights have ' +
<add> str(len(weight_values)) +
<add> ' elements.')
<add> weight_value_tuples += zip(symbolic_weights, weight_values)
<add> K.batch_set_value(weight_value_tuples)
<ide> f.close()
<ide>
<ide> def to_json(self, **kwargs): | 3 |
Python | Python | fix denormal linspace test for longdouble | 9df4a528b57d0d95d84132394178e65ba2683159 | <ide><path>numpy/core/tests/test_function_base.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>from numpy import (logspace, linspace, geomspace, dtype, array, finfo,
<del> typecodes, arange, isnan, ndarray, sqrt)
<add>from numpy import (logspace, linspace, geomspace, dtype, array, sctypes,
<add> arange, isnan, ndarray, sqrt, nextafter)
<ide> from numpy.testing import (
<ide> TestCase, run_module_suite, assert_, assert_equal, assert_raises,
<ide> assert_array_equal, assert_allclose, suppress_warnings
<ide> def __mul__(self, other):
<ide> def test_denormal_numbers(self):
<ide> # Regression test for gh-5437. Will probably fail when compiled
<ide> # with ICC, which flushes denormals to zero
<del> for dt in (dtype(f) for f in typecodes['Float']):
<del> stop = finfo(dt).tiny * finfo(dt).resolution
<del> assert_(any(linspace(0, stop, 10, endpoint=False, dtype=dt)))
<add> for ftype in sctypes['float']:
<add> stop = nextafter(ftype(0), ftype(1)) * 5 # A denormal number
<add> assert_(any(linspace(0, stop, 10, endpoint=False, dtype=ftype)))
<ide>
<ide> def test_equivalent_to_arange(self):
<ide> for j in range(1000): | 1 |
Ruby | Ruby | move updater mock into test class namespace | 65673d60c1ee8aa5c4776bef0dd4fa9d95f81474 | <ide><path>Library/Homebrew/test/test_updater.rb
<ide> require 'cmd/update'
<ide> require 'yaml'
<ide>
<del>class UpdaterMock < Updater
<del> def in_repo_expect(cmd, output = '')
<del> @outputs ||= Hash.new { |h,k| h[k] = [] }
<del> @expected ||= []
<del> @expected << cmd
<del> @outputs[cmd] << output
<del> end
<add>class UpdaterTests < Test::Unit::TestCase
<add> class UpdaterMock < ::Updater
<add> def in_repo_expect(cmd, output = '')
<add> @outputs ||= Hash.new { |h,k| h[k] = [] }
<add> @expected ||= []
<add> @expected << cmd
<add> @outputs[cmd] << output
<add> end
<ide>
<del> def `(cmd, *args)
<del> cmd = "#{cmd} #{args*' '}".strip
<del> if @expected.include?(cmd) and !@outputs[cmd].empty?
<del> @called ||= []
<del> @called << cmd
<del> @outputs[cmd].shift
<del> else
<del> raise "#<#{self.class.name} #{object_id}> unexpectedly called backticks: `#{cmd}'"
<add> def `(cmd, *args)
<add> cmd = "#{cmd} #{args*' '}".strip
<add> if @expected.include?(cmd) and !@outputs[cmd].empty?
<add> @called ||= []
<add> @called << cmd
<add> @outputs[cmd].shift
<add> else
<add> raise "#{inspect} unexpectedly called backticks: `#{cmd}`"
<add> end
<ide> end
<del> end
<ide>
<del> alias safe_system ` #`
<add> alias safe_system ` #`
<ide>
<del> def expectations_met?
<del> @expected == @called
<add> def expectations_met?
<add> @expected == @called
<add> end
<ide> end
<del>end
<ide>
<del>class UpdaterTests < Test::Unit::TestCase
<ide> def fixture(name)
<ide> self.class.fixture_data[name]
<ide> end | 1 |
Text | Text | add socket.io guide | 12f7405781fb623e80af40c9e3a3e16965cab46f | <ide><path>README.md
<ide> for authentication with single page applications. If you insist on using
<ide> a client-side framework, it's best if you use a boilerplate of choice for your particular
<ide> client-side framework and just grab the pieces you need from the Hackathon Starter.
<ide>
<del>HOW IT WORKS (mini guide series)
<del>--------------------------------
<add>How it works (mini guide)
<add>-------------------------
<ide> This section is intended for giving you a detailed explanation about
<ide> how a particular functionality works. Maybe you are just curious about
<ide> how it works, or maybe you are lost and confused while reading the code,
<ide> Todo
<ide>
<ide> <hr>
<ide>
<add>### How do I use Socket.io with Hackathon Starter?
<add>[Dan Stroot](https://github.com/dstroot) submitted an excellent [pull request](https://github.com/dstroot/hackathon-starter/commit/0a632def1ce8da446709d92812423d337c977d75) that adds a real-time dashboard with socket.io.
<add>And as much as I'd like to add it to the project, I think it violates one of the main
<add>principles of the Hackathon Starter:
<add>> When I started this project, my primary focus was on simplicity and ease of use.
<add>> I also tried to make it as generic and reusable as possible to cover most use cases of
<add>> hackathon web apps, **without being too specific**.
<add>
<add>When I need to use socket.io, I **really** need it, but most of the time - I don't. But more
<add>importantly, websockets support is still experimental on most hosting providers. As of October 2013,
<add>Heroku supports websockets, but not until you opt-in by running this command:
<add>```
<add>heroku labs:enable websockets -a myapp
<add>```
<add>And what if you are deploying to OpenShift? They do support websockets, but it is currently in a
<add>preview state. So, for OpenShift you would need to change the socket.io connect URI to the following:
<add>```
<add>var socket = io.connect('http://yoursite-namespace.rhcloud.com:8000');
<add>```
<add>Wait, why is it on port 8000? And why is it you don't have to specify the port number when you are
<add>deploying your app to Heroku? Who knows, and if I didn't run across this [blog post](http://velin-georgiev-blog.appspot.com/blog/set-up-nodejs-express-socketio-application-using-websockets-on-openshift-by-red-hat/)
<add>I wouldn't even know I had to use port 8000.
<add>
<add>I am really glad that Heroku and OpenShift at least
<add>have a websockets support, because many other PaaS providers still do not support it.
<add>Due to the aforementioned issues with websockets, I cannot include socket.io as part of the Hackathon Starter. *For now*.
<add>If you need to use socket.io in your app, then continue reading.
<add>
<add>First you need to install socket.io:
<add>```
<add>npm install socket.io --save`
<add>```
<add>
<add>Replace `var app = express();` with the following code:
<add>
<add>```
<add>var app = express();
<add>var http = require('http');
<add>var server = http.createServer(app);
<add>var io = require('socket.io').listen(server);
<add>
<add>```
<add>
<add>I like to have the following code organization in `app.js` (from top to bottom): module dependencies,
<add>import controllers, import configs, connect to database, express configuration, routes,
<add>start the server, socket.io stuff. That way I always know where to look for things.
<add>
<add>Add the following code at the end of `app.js`:
<add>
<add>```
<add>io.configure(function() {
<add> io.set('transports', ['websocket']);
<add>});
<add>
<add>io.sockets.on('connection', function(socket) {
<add> socket.emit('greet', { hello: 'Hey, Mr.Client!' });
<add> socket.on('respond', function(data) {
<add> console.log(data);
<add> });
<add> socket.on('disconnect', function() {
<add> console.log('Socket disconnected');
<add> });
<add>});
<add>```
<add>
<add>We are done with the server-side business.
<add>
<add>You now have a choice - to include your JavaScript code in Jade templates or have all your client-side
<add>JavaScript in a separate file - in `main.js`. I will admit, when I first started out with Node.js and JavaScript in general,
<add>I placed all JavaScript code inside templates because I have access to template variables passed in from Express
<add>right then and there. It's the easiest thing you can do, but also the least efficient and harder to maintain.
<add>
<add>But it's understandable if you take the easier road. Most of the time you don't care about performance during hackathons, you just
<add>want to [*"get shit done"*](http://www.startupvitamins.com/media/products/13/aaron_levie_poster_black.jpg) before the time runs out.
<add>
<add>If you want to stick all your JavaScript inside templates, then in `layout.jade` -
<add>your main template file, add this to `head` block.
<add>
<add>```
<add>script(src='/socket.io/socket.io.js?v=#{cacheBuster}')
<add>script.
<add> var socket = io.connect(window.location.href);
<add> socket.on('greet', function (data) {
<add> console.log(data);
<add> socket.emit('respond', { message: 'Hello to you too, Mr.Server!' });
<add> });
<add>```
<add>
<add>If you want to have JavaScript code separate from templates, move that inline script code into `main.js`,
<add>inside the `$(document).ready()`. Oh, and notice the path of socket.io file, you don't actually
<add>have to have `socket.io.js` file anywhere in your project, it will be generated automatically
<add>at runtime.
<add>
<add>And that's it, we are done!
<add>
<add><hr>
<ide>
<del>TODO LIST
<del>---------
<add>TODO
<add>----
<ide> - Concatenate and minify all assets via Express middleware if possible, otherwise Gulp.js. Because even with caching enabled, there is at least 50-80ms delay for each static file request (On Heroku).
<ide> - Pages that require login, should automatically redirect to last attempted URL on successful sign-in.
<del>- Add more API examples.
<del>- Mocha tests.
<del>- Once things are stabilized, create a CHANGELOG.md and follow a version format so people who already use Hackathon Starter could know what are the new changes.
<ide>
<ide>
<ide> Contributing | 1 |
Python | Python | handle none scores in evaluate printer | 26bf642afd6ddb496846dad9283b195897afe30b | <ide><path>spacy/cli/evaluate.py
<ide> def render_parses(
<ide> def print_prf_per_type(
<ide> msg: Printer, scores: Dict[str, Dict[str, float]], name: str, type: str
<ide> ) -> None:
<del> data = [
<del> (k, f"{v['p']*100:.2f}", f"{v['r']*100:.2f}", f"{v['f']*100:.2f}")
<del> for k, v in scores.items()
<del> ]
<add> data = []
<add> for key, value in scores.items():
<add> row = [key]
<add> for k in ("p", "r", "f"):
<add> v = value[k]
<add> row.append(f"{v * 100:.2f}" if isinstance(v, (int, float)) else v)
<add> data.append(row)
<ide> msg.table(
<ide> data,
<ide> header=("", "P", "R", "F"),
<ide> def print_textcats_auc_per_cat(
<ide> msg: Printer, scores: Dict[str, Dict[str, float]]
<ide> ) -> None:
<ide> msg.table(
<del> [(k, f"{v:.2f}") for k, v in scores.items()],
<add> [
<add> (k, f"{v:.2f}" if isinstance(v, (float, int)) else v)
<add> for k, v in scores.items()
<add> ],
<ide> header=("", "ROC AUC"),
<ide> aligns=("l", "r"),
<ide> title="Textcat ROC AUC (per label)",
<ide><path>spacy/tests/regression/test_issue7019.py
<add>from spacy.cli.evaluate import print_textcats_auc_per_cat, print_prf_per_type
<add>from wasabi import msg
<add>
<add>
<add>def test_issue7019():
<add> scores = {"LABEL_A": 0.39829102, "LABEL_B": 0.938298329382, "LABEL_C": None}
<add> print_textcats_auc_per_cat(msg, scores)
<add> scores = {
<add> "LABEL_A": {"p": 0.3420302, "r": 0.3929020, "f": 0.49823928932},
<add> "LABEL_B": {"p": None, "r": None, "f": None},
<add> }
<add> print_prf_per_type(msg, scores, name="foo", type="bar") | 2 |
Python | Python | update boto3 to latest | dad318e2b2ce7946b46c6c5aa6031489202abad1 | <ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'oss2>=2.14.0',
<ide> ]
<ide> amazon = [
<del> 'boto3>=1.15.0,<1.19.0',
<add> 'boto3>=1.15.0,<2.0.0',
<ide> 'watchtower~=2.0.1',
<ide> 'jsonpath_ng>=1.5.3',
<ide> 'redshift_connector~=2.0.888', | 1 |
Text | Text | add git clone step to readmes | 7a98aeae189680d9a4e37cbb87c302488fc993ee | <ide><path>Examples/Movies/README.md
<ide> The Movies app is a demonstration of basic concepts, such as fetching data, rend
<ide>
<ide> Before running the app, make sure you ran:
<ide>
<add> git clone https://github.com/facebook/react-native.git
<ide> cd react-native
<ide> npm install
<ide>
<ide><path>Examples/UIExplorer/README.md
<ide> The UIExplorer is a sample app that showcases React Native views and modules.
<ide>
<ide> Before running the app, make sure you ran:
<ide>
<add> git clone https://github.com/facebook/react-native.git
<ide> cd react-native
<ide> npm install
<ide> | 2 |
Javascript | Javascript | fix renderer.render check camera bug | 8f1a4323de3b53700e6cd01d1e9aa25011ff8726 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide> // Rendering
<ide>
<ide> this.render = function ( scene, camera, renderTarget, forceClear ) {
<del>
<del> if ( camera !== undefined && camera.isCamera !== true ) {
<add> if ( ! ( camera && camera.isCamera ) ) {
<ide>
<ide> console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
<ide> return; | 1 |
Python | Python | set version to v2.1.0a7.dev12 | 07617b6b7fddbfb5177813c2e6ecbee691b073cb | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a7.dev11"
<add>__version__ = "2.1.0a7.dev12"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Go | Go | add chroot for tar packing operations | 3029e765e241ea2b5249868705dbf9095bc4d529 | <ide><path>daemon/archive.go
<ide> func extractArchive(i interface{}, src io.Reader, dst string, opts *archive.TarO
<ide> return chrootarchive.UntarWithRoot(src, dst, opts, root)
<ide> }
<ide>
<del>func archivePath(i interface{}, src string, opts *archive.TarOptions) (io.ReadCloser, error) {
<add>func archivePath(i interface{}, src string, opts *archive.TarOptions, root string) (io.ReadCloser, error) {
<ide> if ap, ok := i.(archiver); ok {
<ide> return ap.ArchivePath(src, opts)
<ide> }
<del> return archive.TarWithOptions(src, opts)
<add> return chrootarchive.Tar(src, opts, root)
<ide> }
<ide>
<ide> // ContainerCopy performs a deprecated operation of archiving the resource at
<ide> func (daemon *Daemon) containerArchivePath(container *container.Container, path
<ide> sourceDir, sourceBase := driver.Dir(resolvedPath), driver.Base(resolvedPath)
<ide> opts := archive.TarResourceRebaseOpts(sourceBase, driver.Base(absPath))
<ide>
<del> data, err := archivePath(driver, sourceDir, opts)
<add> data, err := archivePath(driver, sourceDir, opts, container.BaseFS.Path())
<ide> if err != nil {
<ide> return nil, nil, err
<ide> }
<ide> func (daemon *Daemon) containerCopy(container *container.Container, resource str
<ide> archive, err := archivePath(driver, basePath, &archive.TarOptions{
<ide> Compression: archive.Uncompressed,
<ide> IncludeFiles: filter,
<del> })
<add> }, container.BaseFS.Path())
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>daemon/export.go
<ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
<ide> Compression: archive.Uncompressed,
<ide> UIDMaps: daemon.idMapping.UIDs(),
<ide> GIDMaps: daemon.idMapping.GIDs(),
<del> })
<add> }, basefs.Path())
<ide> if err != nil {
<ide> rwlayer.Unmount()
<ide> return nil, err
<ide><path>pkg/chrootarchive/archive.go
<ide> func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions
<ide>
<ide> return invokeUnpack(r, dest, options, root)
<ide> }
<add>
<add>// Tar tars the requested path while chrooted to the specified root.
<add>func Tar(srcPath string, options *archive.TarOptions, root string) (io.ReadCloser, error) {
<add> if options == nil {
<add> options = &archive.TarOptions{}
<add> }
<add> return invokePack(srcPath, options, root)
<add>}
<ide><path>pkg/chrootarchive/archive_unix.go
<ide> import (
<ide> "os"
<ide> "path/filepath"
<ide> "runtime"
<add> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/reexec"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // untar is the entry-point for docker-untar on re-exec. This is not used on
<ide> func untar() {
<ide> runtime.LockOSThread()
<ide> flag.Parse()
<ide>
<del> var options *archive.TarOptions
<add> var options archive.TarOptions
<ide>
<ide> //read the options from the pipe "ExtraFiles"
<ide> if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil {
<ide> func untar() {
<ide> fatal(err)
<ide> }
<ide>
<del> if err := archive.Unpack(os.Stdin, dst, options); err != nil {
<add> if err := archive.Unpack(os.Stdin, dst, &options); err != nil {
<ide> fatal(err)
<ide> }
<ide> // fully consume stdin in case it is zero padded
<ide> func untar() {
<ide> }
<ide>
<ide> func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.TarOptions, root string) error {
<add> if root == "" {
<add> return errors.New("must specify a root to chroot to")
<add> }
<ide>
<ide> // We can't pass a potentially large exclude list directly via cmd line
<ide> // because we easily overrun the kernel's max argument/environment size
<ide> func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.T
<ide> }
<ide> return nil
<ide> }
<add>
<add>func tar() {
<add> runtime.LockOSThread()
<add> flag.Parse()
<add>
<add> src := flag.Arg(0)
<add> var root string
<add> if len(flag.Args()) > 1 {
<add> root = flag.Arg(1)
<add> }
<add>
<add> if root == "" {
<add> root = src
<add> }
<add>
<add> if err := realChroot(root); err != nil {
<add> fatal(err)
<add> }
<add>
<add> var options archive.TarOptions
<add> if err := json.NewDecoder(os.Stdin).Decode(&options); err != nil {
<add> fatal(err)
<add> }
<add>
<add> rdr, err := archive.TarWithOptions(src, &options)
<add> if err != nil {
<add> fatal(err)
<add> }
<add> defer rdr.Close()
<add>
<add> if _, err := io.Copy(os.Stdout, rdr); err != nil {
<add> fatal(err)
<add> }
<add>
<add> os.Exit(0)
<add>}
<add>
<add>func invokePack(srcPath string, options *archive.TarOptions, root string) (io.ReadCloser, error) {
<add> if root == "" {
<add> return nil, errors.New("root path must not be empty")
<add> }
<add>
<add> relSrc, err := filepath.Rel(root, srcPath)
<add> if err != nil {
<add> return nil, err
<add> }
<add> if relSrc == "." {
<add> relSrc = "/"
<add> }
<add> if relSrc[0] != '/' {
<add> relSrc = "/" + relSrc
<add> }
<add>
<add> // make sure we didn't trim a trailing slash with the call to `Rel`
<add> if strings.HasSuffix(srcPath, "/") && !strings.HasSuffix(relSrc, "/") {
<add> relSrc += "/"
<add> }
<add>
<add> cmd := reexec.Command("docker-tar", relSrc, root)
<add>
<add> errBuff := bytes.NewBuffer(nil)
<add> cmd.Stderr = errBuff
<add>
<add> tarR, tarW := io.Pipe()
<add> cmd.Stdout = tarW
<add>
<add> stdin, err := cmd.StdinPipe()
<add> if err != nil {
<add> return nil, errors.Wrap(err, "error getting options pipe for tar process")
<add> }
<add>
<add> if err := cmd.Start(); err != nil {
<add> return nil, errors.Wrap(err, "tar error on re-exec cmd")
<add> }
<add>
<add> go func() {
<add> err := cmd.Wait()
<add> err = errors.Wrapf(err, "error processing tar file: %s", errBuff)
<add> tarW.CloseWithError(err)
<add> }()
<add>
<add> if err := json.NewEncoder(stdin).Encode(options); err != nil {
<add> stdin.Close()
<add> return nil, errors.Wrap(err, "tar json encode to pipe failed")
<add> }
<add> stdin.Close()
<add>
<add> return tarR, nil
<add>}
<ide><path>pkg/chrootarchive/archive_unix_test.go
<ide> package chrootarchive
<ide>
<ide> import (
<add> gotar "archive/tar"
<ide> "bytes"
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<add> "path"
<ide> "path/filepath"
<add> "strings"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> func TestUntarWithMaliciousSymlinks(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, string(hostData), "pwn3d")
<ide> }
<add>
<add>// Test for CVE-2018-15664
<add>// Assures that in the case where an "attacker" controlled path is a symlink to
<add>// some path outside of a container's rootfs that we do not unwittingly leak
<add>// host data into the archive.
<add>func TestTarWithMaliciousSymlinks(t *testing.T) {
<add> dir, err := ioutil.TempDir("", t.Name())
<add> assert.NilError(t, err)
<add> // defer os.RemoveAll(dir)
<add> t.Log(dir)
<add>
<add> root := filepath.Join(dir, "root")
<add>
<add> err = os.MkdirAll(root, 0755)
<add> assert.NilError(t, err)
<add>
<add> hostFileData := []byte("I am a host file")
<add>
<add> // Add a file into a directory above root
<add> // Ensure that we can't access this file while tarring.
<add> err = ioutil.WriteFile(filepath.Join(dir, "host-file"), hostFileData, 0644)
<add> assert.NilError(t, err)
<add>
<add> safe := filepath.Join(root, "safe")
<add> err = unix.Symlink(dir, safe)
<add> assert.NilError(t, err)
<add>
<add> data := filepath.Join(dir, "data")
<add> err = os.MkdirAll(data, 0755)
<add> assert.NilError(t, err)
<add>
<add> type testCase struct {
<add> p string
<add> includes []string
<add> }
<add>
<add> cases := []testCase{
<add> {p: safe, includes: []string{"host-file"}},
<add> {p: safe + "/", includes: []string{"host-file"}},
<add> {p: safe, includes: nil},
<add> {p: safe + "/", includes: nil},
<add> {p: root, includes: []string{"safe/host-file"}},
<add> {p: root, includes: []string{"/safe/host-file"}},
<add> {p: root, includes: nil},
<add> }
<add>
<add> maxBytes := len(hostFileData)
<add>
<add> for _, tc := range cases {
<add> t.Run(path.Join(tc.p+"_"+strings.Join(tc.includes, "_")), func(t *testing.T) {
<add> // Here if we use archive.TarWithOptions directly or change the "root" parameter
<add> // to be the same as "safe", data from the host will be leaked into the archive
<add> var opts *archive.TarOptions
<add> if tc.includes != nil {
<add> opts = &archive.TarOptions{
<add> IncludeFiles: tc.includes,
<add> }
<add> }
<add> rdr, err := Tar(tc.p, opts, root)
<add> assert.NilError(t, err)
<add> defer rdr.Close()
<add>
<add> tr := gotar.NewReader(rdr)
<add> assert.Assert(t, !isDataInTar(t, tr, hostFileData, int64(maxBytes)), "host data leaked to archive")
<add> })
<add> }
<add>}
<add>
<add>func isDataInTar(t *testing.T, tr *gotar.Reader, compare []byte, maxBytes int64) bool {
<add> for {
<add> h, err := tr.Next()
<add> if err == io.EOF {
<add> break
<add> }
<add> assert.NilError(t, err)
<add>
<add> if h.Size == 0 {
<add> continue
<add> }
<add> assert.Assert(t, h.Size <= maxBytes, "%s: file size exceeds max expected size %d: %d", h.Name, maxBytes, h.Size)
<add>
<add> data := make([]byte, int(h.Size))
<add> _, err = io.ReadFull(tr, data)
<add> assert.NilError(t, err)
<add> if bytes.Contains(data, compare) {
<add> return true
<add> }
<add> }
<add>
<add> return false
<add>}
<ide><path>pkg/chrootarchive/archive_windows.go
<ide> func invokeUnpack(decompressedArchive io.ReadCloser,
<ide> // do the unpack. We call inline instead within the daemon process.
<ide> return archive.Unpack(decompressedArchive, longpath.AddPrefix(dest), options)
<ide> }
<add>
<add>func invokePack(srcPath string, options *archive.TarOptions, root string) (io.ReadCloser, error) {
<add> // Windows is different to Linux here because Windows does not support
<add> // chroot. Hence there is no point sandboxing a chrooted process to
<add> // do the pack. We call inline instead within the daemon process.
<add> return archive.TarWithOptions(srcPath, options)
<add>}
<ide><path>pkg/chrootarchive/init_unix.go
<ide> import (
<ide> func init() {
<ide> reexec.Register("docker-applyLayer", applyLayer)
<ide> reexec.Register("docker-untar", untar)
<add> reexec.Register("docker-tar", tar)
<ide> }
<ide>
<ide> func fatal(err error) { | 7 |
Javascript | Javascript | add abortcontroller to eslint globals | 2aab894acf83732591de861ee29f3ddbd25546c4 | <ide><path>packages/eslint-config-react-native-community/index.js
<ide> module.exports = {
<ide> __DEV__: true,
<ide> __dirname: false,
<ide> __fbBatchedBridgeConfig: false,
<add> AbortController: false,
<ide> alert: false,
<ide> cancelAnimationFrame: false,
<ide> cancelIdleCallback: false, | 1 |
Ruby | Ruby | generalise the untap step so we can add to update | d388c4386335390d1c57dc1f9857bbf373781f18 | <ide><path>Library/Homebrew/cmd/untap.rb
<ide> def untap
<ide>
<ide> raise "No such tap!" unless tapd.directory?
<ide>
<del> gitignores = (HOMEBREW_LIBRARY/"Formula/.gitignore").read.split rescue []
<add> files = []
<add> tapd.find_formula{ |file| files << Pathname.new("#{user}-#{repo}").join(file) }
<add> untapped = unlink_tap_formula(files)
<add> rm_rf tapd
<add> puts "Untapped #{untapped} formula"
<add> end
<add>
<add> def unlink_tap_formula formulae
<ide> untapped = 0
<add> gitignores = (HOMEBREW_LIBRARY/"Formula/.gitignore").read.split rescue []
<ide>
<del> tapd.find_formula do |pn|
<del> bn = pn.basename.to_s
<add> formulae.each do |formula|
<add> tapd = (HOMEBREW_LIBRARY/"Taps/#{formula}").dirname
<add> bn = formula.basename.to_s
<ide> pn = HOMEBREW_LIBRARY/"Formula/#{bn}"
<del> if pn.symlink? and pn.realpath.to_s =~ %r[^#{tapd.realpath}]
<add>
<add> if pn.symlink? and pn.realpath.to_s =~ %r[^#{tapd}]
<ide> pn.delete
<ide> gitignores.delete(bn)
<ide> untapped += 1
<ide> end
<ide> end
<del> rm_rf tapd
<ide>
<ide> HOMEBREW_REPOSITORY.join("Library/Formula/.gitignore").atomic_write(gitignores * "\n")
<ide>
<del> puts "Untapped #{untapped} formula"
<add> untapped
<ide> end
<ide> end | 1 |
PHP | PHP | add some test for _basename() | 56271d933344f2a6489ab5ef7f946e0c067d97a9 | <ide><path>src/Filesystem/File.php
<ide> public function name()
<ide> $this->info();
<ide> }
<ide> if (isset($this->info['extension'])) {
<del> return $this->_basename($this->name, '.' . $this->info['extension']);
<add> return static::_basename($this->name, '.' . $this->info['extension']);
<ide> }
<ide> if ($this->name) {
<ide> return $this->name;
<ide> public function name()
<ide> * @param string|null $ext The name of the extension
<ide> * @return string the file basename.
<ide> */
<del> protected function _basename($path, $ext = null)
<add> protected static function _basename($path, $ext = null)
<ide> {
<ide> $splInfo = new SplFileInfo($path);
<ide> $name = ltrim($splInfo->getFilename(), DS);
<ide> public function safe($name = null, $ext = null)
<ide> $ext = $this->ext();
<ide> }
<ide>
<del> return preg_replace("/(?:[^\w\.-]+)/", '_', $this->_basename($name, $ext));
<add> return preg_replace("/(?:[^\w\.-]+)/", '_', static::_basename($name, $ext));
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> public function testUtf8Filenames()
<ide> $this->assertTrue($File->readable());
<ide> }
<ide>
<add> /**
<add> * Test _basename method
<add> * @dataProvider baseNameValueProvider
<add> * @return void
<add> */
<add> public function testBasename($path, $suffix)
<add> {
<add> $class = new \ReflectionClass('Cake\Filesystem\File');
<add> $method = $class->getMethod('_basename');
<add> $method->setAccessible(true);
<add> if ($suffix === null) {
<add> $this->assertEquals(basename($path), $method->invokeArgs(null, [$path]));
<add> } else {
<add> $this->assertEquals(basename($path, $suffix), $method->invokeArgs(null, [$path, $suffix]));
<add> }
<add> }
<add>
<add> /**
<add> * Data provider for testBasename().
<add> *
<add> * @return array
<add> */
<add> public function baseNameValueProvider()
<add> {
<add> return [
<add> ['folder/نام.txt', null],
<add> ['folder/نام فارسی.txt', null],
<add> ['نام.txt', null],
<add> ['نام فارسی.txt', null],
<add> ['/نام.txt', null],
<add> ['/نام فارسی.txt', null],
<add> //
<add> ['folder/نام.txt', '.txt'],
<add> ['folder/نام فارسی.txt', '.txt'],
<add> ['نام.txt', '.txt'],
<add> ['نام فارسی.txt', '.txt'],
<add> ['/نام.txt', '.txt'],
<add> ['/نام فارسی.txt', '.txt'],
<add> //
<add> ['/etc/sudoers.d', null],
<add> ['/etc/sudoers.d', '.d'],
<add> ['/etc/passwd', null],
<add> ['/etc/', null],
<add> ['.', null],
<add> ['/', null],
<add> ];
<add> }
<add>
<ide> /**
<ide> * testPermission method
<ide> * | 2 |
Python | Python | change int to enum | 50d866a5541e1fcc4ff1ceeab172cccc31af7e46 | <ide><path>tests/providers/trino/hooks/test_trino.py
<ide> TRINO_DBAPI_CONNECT = 'airflow.providers.trino.hooks.trino.trino.dbapi.connect'
<ide>
<ide>
<del>class TestTrinoHookConn(unittest.TestCase):
<add>class TestTrinoHookConn:
<ide> @patch(BASIC_AUTHENTICATION)
<ide> @patch(TRINO_DBAPI_CONNECT)
<ide> @patch(HOOK_GET_CONNECTION)
<ide> def assert_connection_called_with(mock_connect, auth=None, verify=True):
<ide> schema='hive',
<ide> source='airflow',
<ide> user='login',
<del> isolation_level=0,
<add> isolation_level=IsolationLevel.AUTOCOMMIT,
<ide> auth=None if not auth else auth.return_value,
<ide> verify=verify,
<ide> ) | 1 |
Javascript | Javascript | fix boolean logic error in view helper assert | 625e38267861b3e6e3281808c833ef7f668d543a | <ide><path>packages/ember-handlebars/lib/helpers/view.js
<ide> Ember.Handlebars.ViewHelper = Ember.Object.create({
<ide> var viewOptions = {};
<ide>
<ide> if (fn) {
<del> ember_assert("You cannot provide a template block if you also specified a templateName", !(get(viewOptions, 'templateName')) && !(newView.PrototypeMixin.keys().indexOf('templateName') >= 0));
<add> ember_assert("You cannot provide a template block if you also specified a templateName", !(get(viewOptions, 'templateName')) && (newView.PrototypeMixin.keys().indexOf('templateName') >= 0));
<ide> viewOptions.template = fn;
<ide> }
<ide> | 1 |
Python | Python | mimic the statsd headers | 3768827a8e78531ca9fe10e715e26f26b67ea575 | <ide><path>airflow/settings.py
<ide>
<ide> class DummyStatsLogger(object):
<ide> @classmethod
<del> def incr(cls):
<add> def incr(cls, stat, count=1, rate=1):
<ide> pass
<ide> @classmethod
<del> def decr(cls):
<add> def decr(cls, stat, count=1, rate=1):
<ide> pass
<ide> @classmethod
<del> def gauge(cls):
<add> def gauge(cls, stat, value, rate=1, delta=False):
<ide> pass
<ide>
<ide> Stats = DummyStatsLogger | 1 |
Javascript | Javascript | flow type improvements to accept co-variant types | b7d873b1a07c863a96d8a9a494f699fdc81ede9c | <ide><path>Libraries/Lists/ListView/ListViewDataSource.js
<ide> class ListViewDataSource {
<ide> * this function as the `dataBlob`.
<ide> */
<ide> cloneWithRows(
<del> dataBlob: Array<any> | {[key: string]: any},
<del> rowIdentities: ?Array<string>
<add> dataBlob: $ReadOnlyArray<any> | {+[key: string]: any},
<add> rowIdentities: ?$ReadOnlyArray<string>
<ide> ): ListViewDataSource {
<del> var rowIds = rowIdentities ? [rowIdentities] : null;
<add> var rowIds = rowIdentities ? [[...rowIdentities]] : null;
<ide> if (!this._sectionHeaderHasChanged) {
<ide> this._sectionHeaderHasChanged = () => false;
<ide> } | 1 |
PHP | PHP | remove unused namespace | 359747b019fede505c0f19e9b9bcfc161c10e090 | <ide><path>tests/Cache/CacheRepositoryTest.php
<ide> <?php
<ide>
<ide> use Mockery as m;
<del>use Illuminate\Cache\ArrayStore;
<ide>
<ide> class CacheRepositoryTest extends PHPUnit_Framework_TestCase {
<ide> | 1 |
Ruby | Ruby | fix rubocop warnings | ba852444131d021b1190cb670b038b78818229fb | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<del>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz"
<del>PYTHON_VIRTUALENV_SHA256 = "fab40f32d9ad298fba04a260f3073505a16d52539a84843cf8c8369d4fd17167"
<add>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz".freeze
<add>PYTHON_VIRTUALENV_SHA256 = "fab40f32d9ad298fba04a260f3073505a16d52539a84843cf8c8369d4fd17167".freeze | 1 |
Ruby | Ruby | remove dead code | 3d6552f8e3a4f3d85c6856f62feb71b999b5afb7 | <ide><path>Library/Homebrew/cmd/--config.rb
<ide> def dump_verbose_config
<ide> end
<ide>
<ide> def dump_c1
<del> stuff = []
<ide> print "#{HOMEBREW_PREFIX}-#{HOMEBREW_VERSION} "
<ide> print MACOS_FULL_VERSION
<ide> print "-#{kernel}" if MacOS.version < :lion | 1 |
Javascript | Javascript | fix modal showing when challenge already completed | f1b29a6fd1b99d0767660281179a4ed797b9c05a | <ide><path>client/commonFramework.js
<ide> editor.setOption('extraKeys', {
<ide> }
<ide> },
<ide> 'Ctrl-Enter': function() {
<add> isInitRun = false;
<ide> bonfireExecute(true);
<ide> return false;
<ide> }
<ide> var testSuccess = function() {
<ide> if (goodTests === tests.length) {
<ide> return showCompletion();
<ide> }
<del>
<del> // test unsuccessful, make sure initRun is set to false
<del> isInitRun = false;
<ide> };
<ide>
<ide> function showCompletion() {
<ide> function bonfireExecute(shouldTest) {
<ide> }
<ide>
<ide> $('#submitButton').on('click', function() {
<add> isInitRun = false;
<ide> bonfireExecute(true);
<ide> });
<ide> | 1 |
PHP | PHP | get router in function | bd9cd7703fe5d745af764ba1c5ac25bd70ed99e2 | <ide><path>src/Illuminate/Broadcasting/BroadcastManager.php
<ide> public function routes()
<ide>
<ide> $router = $this->app['router'];
<ide>
<del> $router->group(['middleware' => ['web']], function () {
<add> $router->group(['middleware' => ['web']], function ($router) {
<ide> $router->post('/broadcasting/auth', BroadcastController::class.'@authenticate');
<ide> $router->post('/broadcasting/socket', BroadcastController::class.'@rememberSocket');
<ide> }); | 1 |
Text | Text | fix typos in step 66 of new js rbg project | 5b229e4f526063728b4867a4c2f9d22bd106490c | <ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8c1154d3ae11aee80353f.md
<ide> You should access the first element of the `button functions` property of the `l
<ide> assert.match(update.toString(), /location\[('|")button functions\1\]\[0\]/);
<ide> ```
<ide>
<del>You should set the `button1.onclick` property to be the second element of the `button functions` property of the `location` argument.
<add>You should set the `button1.onclick` property to be the first element of the `button functions` property of the `location` argument.
<ide>
<ide> ```js
<ide> assert.match(update.toString(), /button1\.onclick\s*=\s*location\[('|")button functions\1\]\[0\]/);
<ide> You should access the second element of the `button functions` property of the `
<ide> assert.match(update.toString(), /location\[('|")button functions\1\]\[1\]/);
<ide> ```
<ide>
<del>You should set the `button2.onclick` property to be the third element of the `button functions` property of the `location` argument.
<add>You should set the `button2.onclick` property to be the second element of the `button functions` property of the `location` argument.
<ide>
<ide> ```js
<ide> assert.match(update.toString(), /button2\.onclick\s*=\s*location\[('|")button functions\1\]\[1\]/); | 1 |
Javascript | Javascript | fix minimum values for writeint*() functions | 5d0b5a00aac6589091dce4345612d3fccb3c430c | <ide><path>lib/buffer.js
<ide> Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
<ide> assert.ok(offset < buffer.length,
<ide> 'Trying to write beyond buffer length');
<ide>
<del> verifsint(value, 0x7f, -0xf0);
<add> verifsint(value, 0x7f, -0x80);
<ide> }
<ide>
<ide> if (value >= 0) {
<ide> function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
<ide> assert.ok(offset + 1 < buffer.length,
<ide> 'Trying to write beyond buffer length');
<ide>
<del> verifsint(value, 0x7fff, -0xf000);
<add> verifsint(value, 0x7fff, -0x8000);
<ide> }
<ide>
<ide> if (value >= 0) {
<ide> function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
<ide> assert.ok(offset + 3 < buffer.length,
<ide> 'Trying to write beyond buffer length');
<ide>
<del> verifsint(value, 0x7fffffff, -0xf0000000);
<add> verifsint(value, 0x7fffffff, -0x80000000);
<ide> }
<ide>
<ide> if (value >= 0) {
<ide><path>test/simple/test-writeint.js
<ide> function test8() {
<ide> ASSERT.throws(function() {
<ide> buffer.writeInt8(0xabc, 0);
<ide> });
<add>
<add> /* Make sure we handle min/max correctly */
<add> buffer.writeInt8(0x7f, 0);
<add> buffer.writeInt8(-0x80, 1);
<add>
<add> ASSERT.equal(0x7f, buffer[0]);
<add> ASSERT.equal(0x80, buffer[1]);
<add> ASSERT.throws(function() {
<add> buffer.writeInt8(0x7f + 1, 0);
<add> });
<add> ASSERT.throws(function() {
<add> buffer.writeInt8(-0x80 - 1, 0);
<add> });
<ide> }
<ide>
<ide>
<ide> function test16() {
<ide> ASSERT.equal(0x71, buffer[2]);
<ide> ASSERT.equal(0x71, buffer[3]);
<ide> ASSERT.equal(0xf9, buffer[4]);
<add>
<add> /* Make sure we handle min/max correctly */
<add> buffer.writeInt16BE(0x7fff, 0);
<add> buffer.writeInt16BE(-0x8000, 2);
<add> ASSERT.equal(0x7f, buffer[0]);
<add> ASSERT.equal(0xff, buffer[1]);
<add> ASSERT.equal(0x80, buffer[2]);
<add> ASSERT.equal(0x00, buffer[3]);
<add> ASSERT.throws(function() {
<add> buffer.writeInt16BE(0x7fff + 1, 0);
<add> });
<add> ASSERT.throws(function() {
<add> buffer.writeInt16BE(-0x8000 - 1, 0);
<add> });
<add>
<add> buffer.writeInt16LE(0x7fff, 0);
<add> buffer.writeInt16LE(-0x8000, 2);
<add> ASSERT.equal(0xff, buffer[0]);
<add> ASSERT.equal(0x7f, buffer[1]);
<add> ASSERT.equal(0x00, buffer[2]);
<add> ASSERT.equal(0x80, buffer[3]);
<add> ASSERT.throws(function() {
<add> buffer.writeInt16LE(0x7fff + 1, 0);
<add> });
<add> ASSERT.throws(function() {
<add> buffer.writeInt16LE(-0x8000 - 1, 0);
<add> });
<ide> }
<ide>
<ide>
<ide> function test32() {
<ide> ASSERT.equal(0xfe, buffer[5]);
<ide> ASSERT.equal(0xff, buffer[6]);
<ide> ASSERT.equal(0xcf, buffer[7]);
<add>
<add> /* Make sure we handle min/max correctly */
<add> buffer.writeInt32BE(0x7fffffff, 0);
<add> buffer.writeInt32BE(-0x80000000, 4);
<add> ASSERT.equal(0x7f, buffer[0]);
<add> ASSERT.equal(0xff, buffer[1]);
<add> ASSERT.equal(0xff, buffer[2]);
<add> ASSERT.equal(0xff, buffer[3]);
<add> ASSERT.equal(0x80, buffer[4]);
<add> ASSERT.equal(0x00, buffer[5]);
<add> ASSERT.equal(0x00, buffer[6]);
<add> ASSERT.equal(0x00, buffer[7]);
<add> ASSERT.throws(function() {
<add> buffer.writeInt32BE(0x7fffffff + 1, 0);
<add> });
<add> ASSERT.throws(function() {
<add> buffer.writeInt32BE(-0x80000000 - 1, 0);
<add> });
<add>
<add> buffer.writeInt32LE(0x7fffffff, 0);
<add> buffer.writeInt32LE(-0x80000000, 4);
<add> ASSERT.equal(0xff, buffer[0]);
<add> ASSERT.equal(0xff, buffer[1]);
<add> ASSERT.equal(0xff, buffer[2]);
<add> ASSERT.equal(0x7f, buffer[3]);
<add> ASSERT.equal(0x00, buffer[4]);
<add> ASSERT.equal(0x00, buffer[5]);
<add> ASSERT.equal(0x00, buffer[6]);
<add> ASSERT.equal(0x80, buffer[7]);
<add> ASSERT.throws(function() {
<add> buffer.writeInt32LE(0x7fffffff + 1, 0);
<add> });
<add> ASSERT.throws(function() {
<add> buffer.writeInt32LE(-0x80000000 - 1, 0);
<add> });
<ide> }
<ide>
<ide> | 2 |
PHP | PHP | add updateorcreate() function | 74c1b8027b5128026905bb9e49b7e77667b7ba34 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function firstOrNew(array $attributes)
<ide> return new static($attributes);
<ide> }
<ide>
<add> /**
<add> * Create or update a record matching the attributes, and fill it with values.
<add> *
<add> * @param array $attributes
<add> * @param array $values
<add> * @return \Illuminate\Database\Eloquent\Model
<add> */
<add> public static function updateOrCreate(array $attributes, array $values = [])
<add> {
<add> $instance = static::firstOrNew($attributes);
<add> $instance->fill($values)->save();
<add>
<add> return $instance;
<add> }
<add>
<ide> /**
<ide> * Get the first model for the given attributes.
<ide> * | 1 |
PHP | PHP | fix 12pm not validating with string data | 2716bcb81b3bc94368e30aafa6a7723bf8bb5620 | <ide><path>src/Validation/Validation.php
<ide> protected static function _getDateString($value)
<ide>
<ide> if (isset($value['hour'])) {
<ide> if (isset($value['meridian'])) {
<del> if ($value['hour'] === 12) {
<add> if ((int)$value['hour'] === 12) {
<ide> $value['hour'] = 0;
<ide> }
<ide> $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> <?php
<ide> /**
<del> * ValidationTest file
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> public function testDateArray()
<ide> */
<ide> public function testDateTimeArray()
<ide> {
<add> $date = [
<add> 'year' => 2014,
<add> 'month' => '02',
<add> 'day' => '14',
<add> 'hour' => '12',
<add> 'minute' => '14',
<add> 'second' => '15',
<add> 'meridian' => 'pm'
<add> ];
<add> $this->assertTrue(Validation::datetime($date));
<add>
<ide> $date = ['year' => 2014, 'month' => 2, 'day' => 14, 'hour' => 13, 'minute' => 14, 'second' => 15];
<ide> $this->assertTrue(Validation::datetime($date));
<ide> | 2 |
PHP | PHP | add setter and getter for autorender flag | 0b6e5ad7b5cdfec917c42f0dfabd73a85f76e01f | <ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListenerInterface, EventDispatcherInterface
<ide> *
<ide> * @var bool
<ide> */
<del> public $autoRender = true;
<add> protected $autoRender = true;
<ide>
<ide> /**
<ide> * Instance of ComponentRegistry used to create Components
<ide> public function __get($name)
<ide> $deprecated = [
<ide> 'name' => 'getName',
<ide> 'plugin' => 'getPlugin',
<add> 'autoRender' => 'isAutoRenderEnabled',
<ide> ];
<ide> if (isset($deprecated[$name])) {
<ide> $method = $deprecated[$name];
<ide> public function __set($name, $value)
<ide> $deprecated = [
<ide> 'name' => 'setName',
<ide> 'plugin' => 'setPlugin',
<add> 'autoRender' => 'enableAutoRender',
<ide> ];
<ide> if (isset($deprecated[$name])) {
<ide> $method = $deprecated[$name];
<ide> public function setPlugin($plugin)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Returns true if an action should be rendered automatically.
<add> *
<add> * @return bool
<add> */
<add> public function isAutoRenderEnabled()
<add> {
<add> return $this->autoRender;
<add> }
<add>
<add> /**
<add> * Enable or disbale automatic action rendering.
<add> *
<add> * @param bool $autoRender Flag.
<add> * @return $this
<add> */
<add> public function enableAutoRender($autoRender = true)
<add> {
<add> $this->autoRender = $autoRender;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Gets the request instance.
<ide> *
<ide><path>src/Http/ActionDispatcher.php
<ide> protected function _invoke(Controller $controller)
<ide> throw new LogicException('Controller actions can only return Cake\Http\Response or null.');
<ide> }
<ide>
<del> if (!$response && $controller->autoRender) {
<add> if (!$response && $controller->isAutoRenderEnabled()) {
<ide> $controller->render();
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testResponse()
<ide> $this->assertSame($response, $controller->getResponse());
<ide> }
<ide>
<add> /**
<add> * Test autoRender getter and setter.
<add> *
<add> * @return void
<add> */
<add> public function testAutoRender()
<add> {
<add> $controller = new PostsController();
<add> $this->assertTrue($controller->isAutoRenderEnabled());
<add>
<add> $this->assertSame($controller, $controller->enableAutoRender(false));
<add> $this->assertFalse($controller->isAutoRenderEnabled());
<add>
<add> $this->assertSame($controller, $controller->enableAutoRender());
<add> $this->assertTrue($controller->isAutoRenderEnabled());
<add> }
<add>
<ide> /**
<ide> * Tests deprecated view propertiyes work
<ide> * | 3 |
Text | Text | update translation selection-sort | dcb03cbbf0b52bb2f2d1e0c88270f00ae8068bd0 | <ide><path>guide/portuguese/algorithms/sorting-algorithms/selection-sort/index.md
<ide> ---
<ide> title: Selection Sort
<del>localeTitle: Seleção de seleção
<add>localeTitle: Ordenação por Seleção
<ide> ---
<del>## Seleção de seleção
<add>## Ordenação por Seleção
<ide>
<del>A seleção de classificação é um dos algoritmos de classificação mais simples. Funciona da seguinte maneira,
<add>A Ordenação por Seleção é um dos algoritmos de classificação mais simples. Funciona da seguinte maneira,
<ide>
<ide> 1. Encontre o menor elemento. Troque com o primeiro elemento.
<ide> 2. Encontre o segundo menor elemento. Troque com o segundo elemento.
<ide> 3. Encontre o terceiro menor elemento. Troque com o terceiro elemento.
<ide> 4. Repita encontrando o próximo elemento menor e trocando-o para a posição correta correspondente até que o array esteja classificado.
<ide>
<del>Como você pode imaginar, esse algoritmo é chamado de Seleção de Seleção porque seleciona repetidamente o próximo elemento menor e o troca para o seu lugar.
<add>Como você pode imaginar, esse algoritmo é chamado de Ordenação por Seleção porque seleciona repetidamente o próximo elemento menor e o troca para o seu lugar.
<ide>
<ide> Mas, como você escreveria o código para encontrar o índice do segundo menor valor em uma matriz?
<ide>
<ide> for(int i = 0; i < n; i++)
<ide> }
<ide> ```
<ide>
<del>### Implementação em Javascript
<add>O seguinte programa C ++ contém uma implementação iterativa e recursiva do algoritmo Ordenação por Seleção. Ambas as implementações são invocadas na função `main()`.
<add>
<add>```cpp
<add>#include <iostream>
<add>#include <string>
<add>using namespace std;
<add>
<add>template<typename T, size_t n>
<add>void print_array(T const(&arr)[n]) {
<add> for (size_t i = 0; i < n; i++)
<add> std::cout << arr[i] << ' ';
<add> cout << "\n";
<add>}
<add>
<add>int minIndex(int a[], int i, int j) {
<add> if (i == j)
<add> return i;
<add> int k = minIndex(a, i + 1, j);
<add> return (a[i] < a[k]) ? i : k;
<add>}
<add>
<add>void recurSelectionSort(int a[], int n, int index = 0) {
<add> if (index == n)
<add> return;
<add> int k = minIndex(a, index, n - 1);
<add> if (k != index)
<add> swap(a[k], a[index]);
<add> recurSelectionSort(a, n, index + 1);
<add>}
<add>
<add>void iterSelectionSort(int a[], int n) {
<add> for (int i = 0; i < n; i++)
<add> {
<add> int min_index = i;
<add> int min_element = a[i];
<add> for (int j = i + 1; j < n; j++)
<add> {
<add> if (a[j] < min_element)
<add> {
<add> min_element = a[j];
<add> min_index = j;
<add> }
<add> }
<add> swap(a[i], a[min_index]);
<add> }
<add>}
<add>
<add>int main() {
<add> int recurArr[6] = { 100,35, 500, 9, 67, 20 };
<add> int iterArr[5] = { 25, 0, 500, 56, 98 };
<add>
<add> cout << "Recursive Selection Sort" << "\n";
<add> print_array(recurArr); // 100 35 500 9 67 20
<add> recurSelectionSort(recurArr, 6);
<add> print_array(recurArr); // 9 20 35 67 100 500
<add>
<add> cout << "Iterative Selection Sort" << "\n";
<add> print_array(iterArr); // 25 0 500 56 98
<add> iterSelectionSort(iterArr, 5);
<add> print_array(iterArr); // 0 25 56 98 500
<add>}
<add>```
<ide>
<del>\`\` \`Javascript seleção de função _sort (A) { var len =_ comprimento do _array_ (A); para (var i = 0; i <len - 1; i = i + 1) { var j _min = i; para (var j = i + 1; j <len; j = j + 1) { if (A \[j\] <A \[j_ min\]) { j _min = j; } outro {} } if (j_ min! == i) { trocar (A, i, j\_min); } outro {} } }
<add>### Implementação em JavaScript
<add>```js
<add>function selection_sort(A) {
<add> var len = A.length;
<add> for (var i = 0; i < len - 1; i = i + 1) {
<add> var j_min = i;
<add> for (var j = i + 1; j < len; j = j + 1) {
<add> if (A[j] < A[j_min]) {
<add> j_min = j;
<add> } else {}
<add> }
<add> if (j_min !== i) {
<add> swap(A, i, j_min);
<add> } else {}
<add> }
<add>}
<add>
<add>function swap(A, x, y) {
<add> var temp = A[x];
<add> A[x] = A[y];
<add> A[y] = temp;
<add>}
<add>```
<ide>
<del>troca de funções (A, x, y) { var temp = A \[x\]; A \[x\] = A \[y\]; A \[y\] = temp; }
<add>### Implementação em Python
<add>```python
<add>def seletion_sort(arr):
<add> if not arr:
<add> return arr
<add> for i in range(len(arr)):
<add> min_i = i
<add> for j in range(i + 1, len(arr)):
<add> if arr[j] < arr[min_i]:
<add> min_i = j
<add> arr[i], arr[min_i] = arr[min_i], arr[i]
<ide> ```
<del>### Implementation in Python
<add>
<add>### Implementação em Java
<add>```java
<add>public void selectionsort(int array[])
<add>{
<add> int n = array.length; //method to find length of array
<add> for (int i = 0; i < n-1; i++)
<add> {
<add> int index = i;
<add> int min = array[i]; // taking the min element as ith element of array
<add> for (int j = i+1; j < n; j++)
<add> {
<add> if (array[j] < array[index])
<add> {
<add> index = j;
<add> min = array[j];
<add> }
<add> }
<add> int t = array[index]; //Interchange the places of the elements
<add> array[index] = array[i];
<add> array[i] = t;
<add> }
<add>}
<ide> ```
<ide>
<del>python _sort de_ seleção de def _(arr): se não for: return arr para eu na faixa (len (arr)): min_ i = i para j no intervalo (i + 1, len (arr)): se arr \[j\] <arr \[min _i\]: min_ i = j arr \[i\], arr \[min _i\] = arr \[min_ i\], arr \[i\] \`\` \`
<add>### Implementação em MATLAB
<add>```MATLAB
<add>function [sorted] = selectionSort(unsorted)
<add> len = length(unsorted);
<add> for i = 1:1:len
<add> minInd = i;
<add> for j = i+1:1:len
<add> if unsorted(j) < unsorted(minInd)
<add> minInd = j;
<add> end
<add> end
<add> unsorted([i minInd]) = unsorted([minInd i]);
<add> end
<add> sorted = unsorted;
<add>end
<add>
<add>```
<ide>
<ide> ### Propriedades
<ide>
<del>* Complexidade do espaço: **O (n)**
<del>* Complexidade do Tempo: **O (n 2 )**
<del>* Ordenando no Lugar: **Sim**
<del>* Estável: **não**
<add>* Complexidade do espaço: <b>O(n)</b>
<add>* Complexidade do Tempo: <b>O(n<sup>2</sup>)</b>
<add>* Ordenando no Lugar: <b>Sim</b>
<add>* Estável: <b>Não</b>
<ide>
<ide> ### Visualização
<ide>
<ide> python _sort de_ seleção de def _(arr): se não for: return arr para eu na fai
<ide> ### Referências
<ide>
<ide> * [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)
<del>* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms#sorting-algorithms)
<ide>\ No newline at end of file
<add>* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms#sorting-algorithms)
<add>* [MyCodeSchool](https://www.youtube.com/watch?v=GUDLRan2DWM) | 1 |
Python | Python | remove the `__reduce__` tests | f3fd03f37044930eb04c0625ad54ef58306a5576 | <ide><path>numpy/typing/tests/test_generic_alias.py
<ide> class TestGenericAlias:
<ide> ("__origin__", lambda n: n.__origin__),
<ide> ("__args__", lambda n: n.__args__),
<ide> ("__parameters__", lambda n: n.__parameters__),
<del> ("__reduce__", lambda n: n.__reduce__()[1][:3]),
<del> ("__reduce_ex__", lambda n: n.__reduce_ex__(1)[1][:3]),
<ide> ("__mro_entries__", lambda n: n.__mro_entries__([object])),
<ide> ("__hash__", lambda n: hash(n)),
<ide> ("__repr__", lambda n: repr(n)), | 1 |
PHP | PHP | add additional test for get() with uuid | 0719af87ee426cf214dfc581e288def120bf5cbb | <ide><path>tests/TestCase/ORM/TableUuidTest.php
<ide> public function testSaveUpdate($tableName)
<ide> $this->assertEquals($entity->toArray(), $row->toArray());
<ide> }
<ide>
<add> /**
<add> * Test delete with string pk.
<add> *
<add> * @dataProvider uuidTableProvider
<add> * @return void
<add> */
<add> public function testGetById($tableName)
<add> {
<add> $table = TableRegistry::get($tableName);
<add> $entity = $table->find('all')->firstOrFail();
<add>
<add> $result = $table->get($entity->id);
<add> $this->assertSame($result->id, $entity->id);
<add> }
<add>
<ide> /**
<ide> * Test delete with string pk.
<ide> * | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.