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
use more template literals
dd1592020b31d810caa276f11738343551d59b82
<ide><path>tools/license2rtf.js <ide> function RtfGenerator() { <ide> if (li) <ide> level++; <ide> <del> var rtf = '\\pard'; <del> rtf += '\\sa150\\sl300\\slmult1'; <add> var rtf = '\\pard\\sa150\\sl300\\slmult1'; <ide> if (level > 0) <del> rtf += '\\li' + (level * 240); <add> rtf += `\\li${level * 240}`; <ide> if (li) { <del> rtf += '\\tx' + (level) * 240; <del> rtf += '\\fi-240'; <add> rtf += `\\tx${level * 240}\\fi-240`; <ide> } <ide> if (lic) <ide> rtf += '\\ri240'; <ide> if (!lic) <ide> rtf += '\\b'; <ide> if (li) <del> rtf += ' ' + li + '\\tab'; <del> rtf += ' '; <del> rtf += lines.map(rtfEscape).join('\\line '); <add> rtf += ` ${li}\\tab`; <add> rtf += ` ${lines.map(rtfEscape).join('\\line ')}`; <ide> if (!lic) <ide> rtf += '\\b0'; <ide> rtf += '\\par\n'; <ide> function RtfGenerator() { <ide> function toHex(number, length) { <ide> var hex = (~~number).toString(16); <ide> while (hex.length < length) <del> hex = '0' + hex; <add> hex = `0${hex}`; <ide> return hex; <ide> } <ide> <ide> function rtfEscape(string) { <ide> return string <ide> .replace(/[\\{}]/g, function(m) { <del> return '\\' + m; <add> return `\\${m}`; <ide> }) <ide> .replace(/\t/g, function() { <ide> return '\\tab '; <ide> }) <ide> // eslint-disable-next-line no-control-regex <ide> .replace(/[\x00-\x1f\x7f-\xff]/g, function(m) { <del> return '\\\'' + toHex(m.charCodeAt(0), 2); <add> return `\\'${toHex(m.charCodeAt(0), 2)}`; <ide> }) <ide> .replace(/\ufeff/g, '') <ide> .replace(/[\u0100-\uffff]/g, function(m) { <del> return '\\u' + toHex(m.charCodeAt(0), 4) + '?'; <add> return `\\u${toHex(m.charCodeAt(0), 4)}?`; <ide> }); <ide> } <ide>
1
Python
Python
improve train cli with base model
90c52128dc5f8131affa7710742e9081cdcaf476
<ide><path>spacy/cli/train.py <ide> raw_text=("Path to jsonl file with unlabelled text documents.", "option", "rt", Path), <ide> base_model=("Name of model to update (optional)", "option", "b", str), <ide> pipeline=("Comma-separated names of pipeline components", "option", "p", str), <add> replace_components=("Replace components from base model", "flag", "R", bool), <ide> vectors=("Model to load vectors from", "option", "v", str), <ide> n_iter=("Number of iterations", "option", "n", int), <ide> n_early_stopping=("Maximum number of training epochs without dev accuracy improvement", "option", "ne", int), <ide> def train( <ide> raw_text=None, <ide> base_model=None, <ide> pipeline="tagger,parser,ner", <add> replace_components=False, <ide> vectors=None, <ide> n_iter=30, <ide> n_early_stopping=None, <ide> def train( <ide> # the model and make sure the pipeline matches the pipeline setting. If <ide> # training starts from a blank model, intitalize the language class. <ide> pipeline = [p.strip() for p in pipeline.split(",")] <add> disabled_pipes = None <add> pipes_added = False <ide> msg.text("Training pipeline: {}".format(pipeline)) <ide> if base_model: <ide> msg.text("Starting with base model '{}'".format(base_model)) <ide> def train( <ide> "`lang` argument ('{}') ".format(nlp.lang, lang), <ide> exits=1, <ide> ) <del> nlp.disable_pipes([p for p in nlp.pipe_names if p not in pipeline]) <ide> for pipe in pipeline: <add> pipe_cfg = {} <add> if pipe == "parser": <add> pipe_cfg = {"learn_tokens": learn_tokens} <add> elif pipe == "textcat": <add> pipe_cfg = { <add> "exclusive_classes": not textcat_multilabel, <add> "architecture": textcat_arch, <add> "positive_label": textcat_positive_label, <add> } <ide> if pipe not in nlp.pipe_names: <del> if pipe == "parser": <del> pipe_cfg = {"learn_tokens": learn_tokens} <del> elif pipe == "textcat": <del> pipe_cfg = { <del> "exclusive_classes": not textcat_multilabel, <del> "architecture": textcat_arch, <del> "positive_label": textcat_positive_label, <del> } <del> else: <del> pipe_cfg = {} <add> msg.text("Adding component to base model '{}'".format(pipe)) <ide> nlp.add_pipe(nlp.create_pipe(pipe, config=pipe_cfg)) <add> pipes_added = True <add> elif replace_components: <add> msg.text("Replacing component from base model '{}'".format(pipe)) <add> nlp.replace_pipe(pipe, nlp.create_pipe(pipe, config=pipe_cfg)) <add> pipes_added = True <ide> else: <ide> if pipe == "textcat": <ide> textcat_cfg = nlp.get_pipe("textcat").cfg <ide> def train( <ide> "architecture": textcat_cfg["architecture"], <ide> "positive_label": textcat_cfg["positive_label"], <ide> } <del> pipe_cfg = { <del> "exclusive_classes": not textcat_multilabel, <del> "architecture": textcat_arch, <del> "positive_label": textcat_positive_label, <del> } <ide> if base_cfg != pipe_cfg: <ide> msg.fail( <ide> "The base textcat model configuration does" <ide> def train( <ide> ), <ide> exits=1, <ide> ) <add> msg.text("Extending component from base model '{}'".format(pipe)) <add> disabled_pipes = nlp.disable_pipes([p for p in nlp.pipe_names if p not in pipeline]) <ide> else: <ide> msg.text("Starting with blank model '{}'".format(lang)) <ide> lang_cls = util.get_lang_class(lang) <ide> def train( <ide> corpus = GoldCorpus(train_path, dev_path, limit=n_examples) <ide> n_train_words = corpus.count_train() <ide> <del> if base_model: <add> if base_model and not pipes_added: <ide> # Start with an existing model, use default optimizer <ide> optimizer = create_default_optimizer(Model.ops) <ide> else: <ide> def train( <ide> <ide> # Verify textcat config <ide> if "textcat" in pipeline: <del> textcat_labels = nlp.get_pipe("textcat").cfg["labels"] <add> textcat_labels = nlp.get_pipe("textcat").cfg.get("labels", []) <ide> if textcat_positive_label and textcat_positive_label not in textcat_labels: <ide> msg.fail( <ide> "The textcat_positive_label (tpl) '{}' does not match any " <ide> def train( <ide> "cpu": cpu_wps, <ide> "gpu": gpu_wps, <ide> } <del> meta["accuracy"] = scorer.scores <add> meta.setdefault("accuracy", {}) <add> for component in nlp.pipe_names: <add> for metric in _get_metrics(component): <add> meta["accuracy"][metric] = scorer.scores[metric] <ide> else: <ide> meta.setdefault("beam_accuracy", {}) <ide> meta.setdefault("beam_speed", {}) <del> meta["beam_accuracy"][beam_width] = scorer.scores <add> for component in nlp.pipe_names: <add> for metric in _get_metrics(component): <add> meta["beam_accuracy"][metric] = scorer.scores[metric] <ide> meta["beam_speed"][beam_width] = { <ide> "nwords": nwords, <ide> "cpu": cpu_wps, <ide> def train( <ide> ) <ide> break <ide> finally: <add> best_pipes = nlp.pipe_names <add> if disabled_pipes: <add> disabled_pipes.restore() <ide> with nlp.use_params(optimizer.averages): <ide> final_model_path = output_path / "model-final" <ide> nlp.to_disk(final_model_path) <add> final_meta = srsly.read_json(output_path / "model-final" / "meta.json") <ide> msg.good("Saved model to output directory", final_model_path) <ide> with msg.loading("Creating best model..."): <del> best_model_path = _collate_best_model(meta, output_path, nlp.pipe_names) <add> best_model_path = _collate_best_model(final_meta, output_path, best_pipes) <ide> msg.good("Created best model", best_model_path) <ide> <ide> <ide> def _load_pretrained_tok2vec(nlp, loc): <ide> <ide> def _collate_best_model(meta, output_path, components): <ide> bests = {} <add> meta.setdefault("accuracy", {}) <ide> for component in components: <ide> bests[component] = _find_best(output_path, component) <ide> best_dest = output_path / "model-best" <ide> def _find_best(experiment_dir, component): <ide> <ide> def _get_metrics(component): <ide> if component == "parser": <del> return ("las", "uas", "token_acc") <add> return ("las", "uas", "las_per_type", "token_acc") <ide> elif component == "tagger": <ide> return ("tags_acc",) <ide> elif component == "ner": <del> return ("ents_f", "ents_p", "ents_r") <add> return ("ents_f", "ents_p", "ents_r", "ents_per_type") <add> elif component == "textcat": <add> return ("textcat_score",) <ide> return ("token_acc",) <ide> <ide>
1
Javascript
Javascript
add sourcemaps
c03600ba3f93426075b575f5120b2c7a2a691f8b
<ide><path>rollup.config.js <ide> export default { <ide> dest: 'build/three.modules.js' <ide> } <ide> ], <del> outro: outro <add> outro: outro, <add> sourceMap: true <ide> };
1
Ruby
Ruby
ensure mktemp cleans up after itself
d89b3272f441ebdc71d0ffb0448dd1c364f1ca52
<ide><path>Library/Homebrew/extend/fileutils.rb <ide> def mktemp <ide> # /tmp volume to the other volume. So we let the user override the tmp <ide> # prefix if they need to. <ide> tmp_prefix = ENV['HOMEBREW_TEMP'] || '/tmp' <del> tmp=Pathname.new `/usr/bin/mktemp -d #{tmp_prefix}/homebrew-#{name}-#{version}-XXXX`.strip <del> raise "Couldn't create build sandbox" if not tmp.directory? or $? != 0 <del> begin <del> wd=Dir.pwd <del> chdir tmp <del> yield <del> ensure <del> chdir wd <del> tmp.rmtree <del> end <add> tmp = Pathname.new(`/usr/bin/mktemp -d #{tmp_prefix}/homebrew-#{name}-#{version}-XXXX`.chomp) <add> raise "Failed to create sandbox: #{tmp}" unless tmp.directory? <add> cd(tmp){ yield } <add> ensure <add> ignore_interrupts{ tmp.rmtree } if tmp <ide> end <ide> <ide> # A version of mkdir that also changes to that folder in a block.
1
Javascript
Javascript
add "deprecated" to the testswarm module list
1144e754a6a131bd4affec26fd85299e71bdab06
<ide><path>Gruntfile.js <ide> module.exports = function( grunt ) { <ide> "css", <ide> "data", <ide> "deferred", <add> "deprecated", <ide> "dimensions", <ide> "effects", <ide> "event",
1
Python
Python
add test to show it doesn't work as it used to
d979b922360fb64f35b4bf4d75e5c9ff69694911
<ide><path>libcloud/test/test_response_classes.py <ide> import requests <ide> import requests_mock <ide> <del>from libcloud.common.base import XmlResponse, JsonResponse <add>from libcloud.common.base import XmlResponse, JsonResponse, RawResponse, Connection <ide> from libcloud.common.types import MalformedResponseError <ide> from libcloud.httplib_ssl import LibcloudConnection <ide> <ide> def test_JsonResponse_class_zero_length_body_strip(self): <ide> parsed = response.parse_body() <ide> self.assertEqual(parsed, '') <ide> <add> def test_RawResponse_class_read_method(self): <add> TEST_DATA = '1234abcd' <add> <add> conn = Connection(host='mock.com', port=80, secure=False) <add> conn.connect() <add> adapter = requests_mock.Adapter() <add> conn.connection.session.mount('mock', adapter) <add> adapter.register_uri('GET', 'http://test.com/raw_data', text=TEST_DATA) <add> <add> response = conn.request('/raw_data', raw=True) <add> data = response.response.read() <add> self.assertEqual(data, TEST_DATA) <ide> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main())
1
Go
Go
use status code from sockrequest (fix )
531433e7650c5d33ff6580d7de28a093a504ac6c
<ide><path>integration-cli/docker_api_containers_test.go <ide> import ( <ide> "bytes" <ide> "encoding/json" <ide> "io" <add> "net/http" <ide> "os/exec" <ide> "strings" <ide> "testing" <ide> func TestContainerApiStartVolumeBinds(t *testing.T) { <ide> "Volumes": map[string]struct{}{"/tmp": {}}, <ide> } <ide> <del> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") { <add> if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated { <ide> t.Fatal(err) <ide> } <ide> <ide> bindPath := randomUnixTmpDirPath("test") <ide> config = map[string]interface{}{ <ide> "Binds": []string{bindPath + ":/tmp"}, <ide> } <del> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestContainerApiStartDupVolumeBinds(t *testing.T) { <ide> "Volumes": map[string]struct{}{"/tmp": {}}, <ide> } <ide> <del> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") { <add> if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestContainerApiStartVolumesFrom(t *testing.T) { <ide> "Volumes": map[string]struct{}{volPath: {}}, <ide> } <ide> <del> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") { <add> if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated { <ide> t.Fatal(err) <ide> } <ide> <ide> config = map[string]interface{}{ <ide> "VolumesFrom": []string{volName}, <ide> } <del> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestVolumesFromHasPriority(t *testing.T) { <ide> "Volumes": map[string]struct{}{volPath: {}}, <ide> } <ide> <del> if _, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") { <add> if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestVolumesFromHasPriority(t *testing.T) { <ide> "VolumesFrom": []string{volName}, <ide> "Binds": []string{bindPath + ":/tmp"}, <ide> } <del> if _, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestPostContainerBindNormalVolume(t *testing.T) { <ide> } <ide> <ide> bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}} <del> _, _, err = sockRequest("POST", "/containers/two/start", bindSpec) <del> if err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/two/start", bindSpec); err != nil && status != http.StatusNoContent { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestContainerApiPause(t *testing.T) { <ide> } <ide> ContainerID := strings.TrimSpace(out) <ide> <del> if _, _, err = sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && status != http.StatusNoContent { <ide> t.Fatalf("POST a container pause: sockRequest failed: %v", err) <ide> } <ide> <ide> func TestContainerApiPause(t *testing.T) { <ide> t.Fatalf("there should be one paused container and not %d", len(pausedContainers)) <ide> } <ide> <del> if _, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") { <add> if status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && status != http.StatusNoContent { <ide> t.Fatalf("POST a container pause: sockRequest failed: %v", err) <ide> } <ide> <ide><path>integration-cli/docker_cli_rm_test.go <ide> package main <ide> <ide> import ( <add> "net/http" <ide> "os" <ide> "os/exec" <ide> "strings" <ide> func TestRmRunningContainerCheckError409(t *testing.T) { <ide> createRunningContainer(t, "foo") <ide> <ide> endpoint := "/containers/foo" <del> _, _, err := sockRequest("DELETE", endpoint, nil) <add> status, _, err := sockRequest("DELETE", endpoint, nil) <ide> <ide> if err == nil { <ide> t.Fatalf("Expected error, can't rm a running container") <del> } <del> if !strings.Contains(err.Error(), "409 Conflict") { <add> } else if status != http.StatusConflict { <ide> t.Fatalf("Expected error to contain '409 Conflict' but found %s", err) <ide> } <ide>
2
Javascript
Javascript
add script for running v8 benchmarks
bd094103d791fdd53eccd15bbfd1875655ea4a01
<ide><path>benchmark/v8_bench.js <add>// compare with "google-chrome deps/v8/benchmarks/run.html" <add>var fs = require('fs'); <add>var path = require('path'); <add>var vm = require('vm'); <add> <add>var dir = path.join(__dirname, '..', 'deps', 'v8', 'benchmarks'); <add> <add>global.print = console.log; <add> <add>global.load = function (x) { <add> var source = fs.readFileSync(path.join(dir, x), 'utf8'); <add> vm.runInThisContext(source, x); <add>} <add> <add>load('run.js');
1
Ruby
Ruby
handle github api authentication failures
6fd0125ad9e2fc4eab2639f57136d8b15cffd744
<ide><path>Library/Homebrew/utils.rb <ide> module GitHub extend self <ide> Error = Class.new(StandardError) <ide> RateLimitExceededError = Class.new(Error) <ide> HTTPNotFoundError = Class.new(Error) <add> AuthenticationFailedError = Class.new(Error) <ide> <ide> def open url, headers={}, &block <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> def handle_api_error(e) <ide> end <ide> <ide> case e.io.status.first <add> when "401", "403" <add> raise AuthenticationFailedError, e.message, e.backtrace <ide> when "404" <ide> raise HTTPNotFoundError, e.message, e.backtrace <ide> else
1
Text
Text
remove deprecated copy from readme
97a2dc96f23b25bc7980d2a4514b7065ff4edb9e
<ide><path>README.md <ide> With Standard Containers we can put an end to that embarrassment, by <ide> making INDUSTRIAL-GRADE DELIVERY of software a reality. <ide> <ide> <del> <del> <del>Standard Container Specification <del>-------------------------------- <del> <del>(TODO) <del> <del>### Image format <del> <del> <del>### Standard operations <del> <del>* Copy <del>* Run <del>* Stop <del>* Wait <del>* Commit <del>* Attach standard streams <del>* List filesystem changes <del>* ... <del> <del>### Execution environment <del> <del>#### Root filesystem <del> <del>#### Environment variables <del> <del>#### Process arguments <del> <del>#### Networking <del> <del>#### Process namespacing <del> <del>#### Resource limits <del> <del>#### Process monitoring <del> <del>#### Logging <del> <del>#### Signals <del> <del>#### Pseudo-terminal allocation <del> <del>#### Security <del> <ide> ### Legal <ide> <ide> Transfers of Docker shall be in accordance with applicable export
1
Ruby
Ruby
fix usage documentation in videoanalyzer
f70defa1ba8a344ea1f2198086aeda4253bf9842
<ide><path>activestorage/lib/active_storage/analyzer/video_analyzer.rb <ide> module ActiveStorage <ide> # <ide> # Example: <ide> # <del> # ActiveStorage::VideoAnalyzer.new(blob).metadata <add> # ActiveStorage::Analyzer::VideoAnalyzer.new(blob).metadata <ide> # # => { width: 640.0, height: 480.0, duration: 5.0, angle: 0, display_aspect_ratio: [4, 3] } <ide> # <ide> # When a video's angle is 90 or 270 degrees, its width and height are automatically swapped for convenience.
1
Python
Python
fix asset compilation via setup.py
c3763f3be5245af8f2c13d89db648e67bad8c680
<ide><path>setup.py <ide> def finalize_options(self) -> None: <ide> <ide> def run(self) -> None: <ide> """Run a command to compile and build assets.""" <del> subprocess.check_call('./airflow/www/compile_assets.sh') <add> www_dir = AIRFLOW_SOURCES_ROOT / "airflow" / "www" <add> subprocess.check_call(['yarn', 'install', '--frozen-lockfile'], cwd=str(www_dir)) <add> subprocess.check_call(['yarn', 'run', 'build'], cwd=str(www_dir)) <ide> <ide> <ide> class ListExtras(Command):
1
PHP
PHP
fix niceformat stattic access for real
c5ff3041be666d1c997d3c7c7d1b3e8a58c8c9a1
<ide><path>Cake/Test/TestCase/Utility/TimeTest.php <ide> public function testNice() { <ide> $this->assertEquals(date('D', $time), $this->Time->nice($time, null, '%a')); <ide> $this->assertEquals(date('M d, Y', $time), $this->Time->nice($time, null, '%b %d, %Y')); <ide> <del> $this->Time->niceFormat = '%Y-%d-%m'; <add> Time::$niceFormat = '%Y-%d-%m'; <ide> $this->assertEquals(date('Y-d-m', $time), $this->Time->nice($time)); <ide> $this->assertEquals('%Y-%d-%m', Time::$niceFormat); <ide>
1
Java
Java
introduce test for gh-27390
5cc09849cedfc21a5922930d17bce7a61fccd238
<ide><path>spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.SoftAssertions.assertSoftly; <ide> <ide> /** <ide> * Unit tests for {@link BeanUtils}. <ide> void instantiateClassWithOptionalNullableType() throws NoSuchMethodException { <ide> } <ide> <ide> @Test // gh-22531 <del> void instantiateClassWithOptionalPrimitiveType() throws NoSuchMethodException { <del> Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class); <del> BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo"); <del> assertThat(bean.getCounter()).isEqualTo(0); <del> assertThat(bean.isFlag()).isEqualTo(false); <del> assertThat(bean.getValue()).isEqualTo("foo"); <add> void instantiateClassWithFewerArgsThanParameters() throws NoSuchMethodException { <add> Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor(); <add> <add> assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() -> <add> BeanUtils.instantiateClass(constructor, null, null, "foo")); <ide> } <ide> <ide> @Test // gh-22531 <ide> void instantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException { <del> Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class); <add> Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor(); <add> <ide> assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() -> <del> BeanUtils.instantiateClass(ctor, null, null, "foo", null)); <add> BeanUtils.instantiateClass(constructor, null, null, null, null, null, null, null, "foo", null)); <add> } <add> <add> @Test // gh-22531, gh-27390 <add> void instantiateClassWithOptionalPrimitiveTypes() throws NoSuchMethodException { <add> Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor(); <add> <add> BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(constructor, null, null, null, null, null, null, null, "foo"); <add> <add> assertSoftly(softly -> { <add> softly.assertThat(bean.isFlag()).isEqualTo(false); <add> softly.assertThat(bean.getByteCount()).isEqualTo((byte) 0); <add> softly.assertThat(bean.getShortCount()).isEqualTo((short) 0); <add> softly.assertThat(bean.getIntCount()).isEqualTo(0); <add> softly.assertThat(bean.getLongCount()).isEqualTo(0L); <add> softly.assertThat(bean.getFloatCount()).isEqualTo(0F); <add> softly.assertThat(bean.getDoubleCount()).isEqualTo(0D); <add> softly.assertThat(bean.getText()).isEqualTo("foo"); <add> }); <add> } <add> <add> private Constructor<BeanWithPrimitiveTypes> getBeanWithPrimitiveTypesConstructor() throws NoSuchMethodException { <add> return BeanWithPrimitiveTypes.class.getConstructor(boolean.class, byte.class, short.class, int.class, <add> long.class, float.class, double.class, String.class); <ide> } <ide> <ide> @Test <ide> public String getValue() { <ide> <ide> private static class BeanWithPrimitiveTypes { <ide> <del> private int counter; <del> <ide> private boolean flag; <add> private byte byteCount; <add> private short shortCount; <add> private int intCount; <add> private long longCount; <add> private float floatCount; <add> private double doubleCount; <add> private String text; <ide> <del> private String value; <ide> <ide> @SuppressWarnings("unused") <del> public BeanWithPrimitiveTypes(int counter, boolean flag, String value) { <del> this.counter = counter; <add> public BeanWithPrimitiveTypes(boolean flag, byte byteCount, short shortCount, int intCount, long longCount, <add> float floatCount, double doubleCount, String text) { <ide> this.flag = flag; <del> this.value = value; <del> } <del> <del> public int getCounter() { <del> return counter; <add> this.byteCount = byteCount; <add> this.shortCount = shortCount; <add> this.intCount = intCount; <add> this.longCount = longCount; <add> this.floatCount = floatCount; <add> this.doubleCount = doubleCount; <add> this.text = text; <ide> } <ide> <ide> public boolean isFlag() { <ide> return flag; <ide> } <ide> <del> public String getValue() { <del> return value; <add> public byte getByteCount() { <add> return byteCount; <add> } <add> <add> public short getShortCount() { <add> return shortCount; <add> } <add> <add> public int getIntCount() { <add> return intCount; <add> } <add> <add> public long getLongCount() { <add> return longCount; <add> } <add> <add> public float getFloatCount() { <add> return floatCount; <add> } <add> <add> public double getDoubleCount() { <add> return doubleCount; <add> } <add> <add> public String getText() { <add> return text; <ide> } <add> <ide> } <ide> <ide> private static class PrivateBeanWithPrivateConstructor {
1
PHP
PHP
remove unused method
1e4a5f92f31c5deaf2d981a055adb35c004b8fb1
<ide><path>src/I18n/PackageLocator.php <ide> public function set(string $name, string $locale, $spec): void <ide> $this->converted[$name][$locale] = $spec instanceof Package; <ide> } <ide> <del> /** <del> * Sets a Package object. <del> * <del> * @param string $name The package name. <del> * @param string $locale The locale for the package. <del> * @param \Cake\I18n\Package $package A Package instance. <del> * @return void <del> */ <del> public function setPackage(string $name, string $locale, Package $package): void <del> { <del> $this->registry[$name][$locale] = $package; <del> $this->converted[$name][$locale] = true; <del> } <del> <ide> /** <ide> * Gets a Package object. <ide> *
1
Ruby
Ruby
check byte size instead of length
92b8cda4c9ba87c82d737fd4303f4bbc535395f3
<ide><path>activesupport/lib/active_support/security_utils.rb <ide> def fixed_length_secure_compare(a, b) <ide> # the secret length. This should be considered when using secure_compare <ide> # to compare weak, short secrets to user input. <ide> def secure_compare(a, b) <del> a.length == b.length && fixed_length_secure_compare(a, b) <add> a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) <ide> end <ide> module_function :secure_compare <ide> end <ide><path>activesupport/test/security_utils_test.rb <ide> def test_secure_compare_should_perform_string_comparison <ide> assert_not ActiveSupport::SecurityUtils.secure_compare("a", "b") <ide> end <ide> <add> def test_secure_compare_return_false_on_bytesize_mismatch <add> assert_not ActiveSupport::SecurityUtils.secure_compare("a", "\u{ff41}") <add> end <add> <ide> def test_fixed_length_secure_compare_should_perform_string_comparison <ide> assert ActiveSupport::SecurityUtils.fixed_length_secure_compare("a", "a") <ide> assert_not ActiveSupport::SecurityUtils.fixed_length_secure_compare("a", "b")
2
Text
Text
add backticks to highlight comment.json file name
24c41b6849e2652ad2e4d35a3fc1dd5bf0ac2664
<ide><path>docs/docs/tutorial.md <ide> var CommentBox = React.createClass({ <ide> `getInitialState()` executes exactly once during the lifecycle of the component and sets up the initial state of the component. <ide> <ide> #### Updating state <del>When the component is first created, we want to GET some JSON from the server and update the state to reflect the latest data. In a real application this would be a dynamic endpoint, but for this example we will keep things simple by creating a static JSON file public/comments.json containing the array of comments: <add>When the component is first created, we want to GET some JSON from the server and update the state to reflect the latest data. In a real application this would be a dynamic endpoint, but for this example we will keep things simple by creating a static JSON file `public/comments.json` containing the array of comments: <ide> <ide> ```javascript <ide> // tutorial13.json
1
Python
Python
add missing license
c231005fcbb67d275fdf20fea93d0103b18a1d62
<ide><path>libcloud/dns/drivers/nsone.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <ide> import sys <ide> try: <ide> import simplejson as json
1
PHP
PHP
fix a method naming error
778350e5d6a59c4670251ca6b6e0419f801368ba
<ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> protected function runUp($file, $batch, $pretend) <ide> return $this->pretendToRun($migration, 'up'); <ide> } <ide> <del> $this->migrate($migration, 'up'); <add> $this->runMigration($migration, 'up'); <ide> <ide> // Once we have run a migrations class, we will log that it was run in this <ide> // repository so that we don't try to run it next time we do a migration
1
Javascript
Javascript
fix symlink resolving for examples in the repo
c97c1e551654ff9dd5de50b9eec9d21a791ffe06
<ide><path>local-cli/core/default.config.js <ide> <ide> const path = require('path'); <ide> const flatten = require('lodash').flatten; <del> <ide> const blacklist = require('../../packager/blacklist'); <del> <ide> const android = require('./android'); <ide> const findAssets = require('./findAssets'); <ide> const ios = require('./ios'); <ide> const windows = require('./windows'); <ide> const wrapCommands = require('./wrapCommands'); <ide> const findPlugins = require('./findPlugins'); <del> <ide> const findSymlinksPaths = require('../util/findSymlinksPaths'); <del>const NODE_MODULES = path.resolve(__dirname, '..', '..', '..'); <ide> <ide> import type {ConfigT} from './index'; <ide> <add>function getProjectPath() { <add> if (__dirname.match(/node_modules[\/\\]react-native[\/\\]local-cli[\/\\]core$/)) { <add> // Packager is running from node_modules. <add> // This is the default case for all projects created using 'react-native init'. <add> return path.resolve(__dirname, '../../../..'); <add> } else if (__dirname.match(/Pods[\/\\]React[\/\\]packager$/)) { <add> // React Native was installed using CocoaPods. <add> return path.resolve(__dirname, '../../../..'); <add> } <add> return path.resolve(__dirname, '../..'); <add>} <add> <ide> const getRNPMConfig = (folder) => <ide> // $FlowFixMe non-literal require <ide> require(path.join(folder, './package.json')).rnpm || {}; <ide> const attachPackage = (command, pkg) => Array.isArray(command) <ide> ? command.map(cmd => attachPackage(cmd, pkg)) <ide> : { ...command, pkg }; <ide> <del>const addSymlinkToRoots = (roots) => <del> roots.concat(findSymlinksPaths(NODE_MODULES, roots)); <add>const resolveSymlink = (roots) => <add> roots.concat( <add> findSymlinksPaths( <add> path.join(getProjectPath(), 'node_modules'), <add> roots <add> ) <add> ); <ide> <ide> /** <ide> * Default configuration for the CLI. <ide> const config: ConfigT = { <ide> getProjectRoots() { <ide> const root = process.env.REACT_NATIVE_APP_ROOT; <ide> if (root) { <del> return addSymlinkToRoots([path.resolve(root)]); <add> return resolveSymlink([path.resolve(root)]); <ide> } <ide> <del> var roots; <del> if (__dirname.match(/node_modules[\/\\]react-native[\/\\]local-cli[\/\\]core$/)) { <del> // Packager is running from node_modules. <del> // This is the default case for all projects created using 'react-native init'. <del> roots = [path.resolve(__dirname, '../../../..')]; <del> } else if (__dirname.match(/Pods[\/\\]React[\/\\]packager$/)) { <del> // React Native was installed using CocoaPods. <del> roots = [path.resolve(__dirname, '../../../..')]; <del> } else { <del> roots = [path.resolve(__dirname, '../..')]; <del> } <del> return addSymlinkToRoots(roots); <add> return resolveSymlink([getProjectPath()]); <ide> }, <ide> }; <ide>
1
Javascript
Javascript
add azimuthal equidistant projection mode
1e017e60b67740b8d7602951abb0d096ed37a593
<ide><path>d3.geo.js <ide> var d3_radians = Math.PI / 180; <ide> // TODO clip input coordinates on opposite hemisphere <ide> d3.geo.azimuthal = function() { <del> var mode = "orthographic", // or stereographic <add> var mode = "orthographic", // or stereographic, gnomonic or equidistant <ide> origin, <ide> scale = 200, <ide> translate = [480, 250], <ide> d3.geo.azimuthal = function() { <ide> sx1 = Math.sin(x1), <ide> cy1 = Math.cos(y1), <ide> sy1 = Math.sin(y1), <del> k = mode === "stereographic" ? 1 / (sy0 * sy1 + cy0 * cy1 * cx1 + 1) <del> : mode === "gnomonic" ? 1 / (sy0 * sy1 + cy0 * cy1 * cx1) <add> cc = mode !== "orthographic" ? sy0 * sy1 + cy0 * cy1 * cx1 : null, <add> c, <add> k = mode === "stereographic" ? 1 / (1 + cc) <add> : mode === "gnomonic" ? 1 / cc <add> : mode === "equidistant" ? (c = Math.acos(cc), c / Math.sin(c)) <ide> : 1, <ide> x = k * cy1 * sx1, <ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1); <ide> d3.geo.azimuthal = function() { <ide> p = Math.sqrt(x * x + y * y), <ide> c = mode === "stereographic" ? 2 * Math.atan(p) <ide> : mode === "gnomonic" ? Math.atan(p) <add> : mode === "equidistant" ? p <ide> : Math.asin(p), <ide> sc = Math.sin(c), <ide> cc = Math.cos(c); <ide><path>d3.geo.min.js <del>(function(){function o(a){return a.target}function n(a){return a.source}function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={};var a=Math.PI/180;d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b==="stereographic"?1/(i*n+h*m*k+1):b==="gnomonic"?1/(i*n+h*m*k):1,p=o*m*l,q=o*(i*m*k-h*n);return[d*p+e[0],d*q+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.invert=function(c){var g=(c[0]-e[0])/d,j=(c[1]-e[1])/d,k=Math.sqrt(g*g+j*j),l=b==="stereographic"?2*Math.atan(k):b==="gnomonic"?Math.atan(k):Math.asin(k),m=Math.sin(l),n=Math.cos(l);return[(f+Math.atan2(g*m,k*h*n+j*i*m))/a,Math.asin(n*i-j*m*h/k)/a]},j.mode=function(a){if(!arguments.length)return b;b=a+"";return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.invert=function(b){var c=(b[0]-e[0])/d,j=(b[1]-e[1])/d,k=i+j,l=Math.atan2(c,k),m=Math.sqrt(c*c+k*k);return[(f+l/g)/a,Math.asin((h-m*m*g*g)/(2*g))/a]},j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())},d3.geo.mercator=function(){function d(d){var e=d[0]/360,f=-(Math.log(Math.tan(Math.PI/4+d[1]*a/2))/a)/360;return[b*e+c[0],b*Math.max(-0.5,Math.min(.5,f))+c[1]]}var b=500,c=[480,250];d.invert=function(d){var e=(d[0]-c[0])/b,f=(d[1]-c[1])/b;return[360*e,2*Math.atan(Math.exp(-360*f*a))/a-90]},d.scale=function(a){if(!arguments.length)return b;b=+a;return d},d.translate=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return d};return d},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m};d3.geo.greatCircle=function(){function f(e,f){var g=b.call(this,e,f),h=c.call(this,e,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.cos(i),n=Math.sin(i),o=Math.cos(j),p=Math.sin(j),q=Math.cos(k),r=Math.sin(k),s=Math.cos(l),t=Math.sin(l),e=Math.acos(p*t+o*s*Math.cos(k-i)),u=Math.sin(e),v=e/(d-1),w=-v,x=[],f=-1;while(++f<d){w+=v;var y=Math.sin(e-w)/u,z=Math.sin(w)/u,A=y*o*m+z*s*q,B=y*o*n+z*s*r,C=y*p+z*t;x[f]=[Math.atan2(B,A)/a,Math.atan2(C,Math.sqrt(A*A+B*B))/a]}return x}var b=n,c=o,d=100,e=6371;f.source=function(a){if(!arguments.length)return b;b=a;return f},f.target=function(a){if(!arguments.length)return c;c=a;return f},f.n=function(a){if(!arguments.length)return d;d=+a;return f},f.radius=function(a){if(!arguments.length)return e;e=+a;return f},f.distance=function(d,f){var g=b.call(this,d,f),h=c.call(this,d,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.sin((l-j)/2),n=Math.sin((k-i)/2),o=m*m+Math.cos(j)*Math.cos(l)*n*n;return e*2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))};return f}})() <ide>\ No newline at end of file <add>(function(){function o(a){return a.target}function n(a){return a.source}function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={};var a=Math.PI/180;d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b!=="orthographic"?i*n+h*m*k:null,p,q=b==="stereographic"?1/(1+o):b==="gnomonic"?1/o:b==="equidistant"?(p=Math.acos(o),p/Math.sin(p)):1,r=q*m*l,s=q*(i*m*k-h*n);return[d*r+e[0],d*s+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.invert=function(c){var g=(c[0]-e[0])/d,j=(c[1]-e[1])/d,k=Math.sqrt(g*g+j*j),l=b==="stereographic"?2*Math.atan(k):b==="gnomonic"?Math.atan(k):b==="equidistant"?k:Math.asin(k),m=Math.sin(l),n=Math.cos(l);return[(f+Math.atan2(g*m,k*h*n+j*i*m))/a,Math.asin(n*i-j*m*h/k)/a]},j.mode=function(a){if(!arguments.length)return b;b=a+"";return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.invert=function(b){var c=(b[0]-e[0])/d,j=(b[1]-e[1])/d,k=i+j,l=Math.atan2(c,k),m=Math.sqrt(c*c+k*k);return[(f+l/g)/a,Math.asin((h-m*m*g*g)/(2*g))/a]},j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())},d3.geo.mercator=function(){function d(d){var e=d[0]/360,f=-(Math.log(Math.tan(Math.PI/4+d[1]*a/2))/a)/360;return[b*e+c[0],b*Math.max(-0.5,Math.min(.5,f))+c[1]]}var b=500,c=[480,250];d.invert=function(d){var e=(d[0]-c[0])/b,f=(d[1]-c[1])/b;return[360*e,2*Math.atan(Math.exp(-360*f*a))/a-90]},d.scale=function(a){if(!arguments.length)return b;b=+a;return d},d.translate=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return d};return d},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m};d3.geo.greatCircle=function(){function f(e,f){var g=b.call(this,e,f),h=c.call(this,e,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.cos(i),n=Math.sin(i),o=Math.cos(j),p=Math.sin(j),q=Math.cos(k),r=Math.sin(k),s=Math.cos(l),t=Math.sin(l),e=Math.acos(p*t+o*s*Math.cos(k-i)),u=Math.sin(e),v=e/(d-1),w=-v,x=[],f=-1;while(++f<d){w+=v;var y=Math.sin(e-w)/u,z=Math.sin(w)/u,A=y*o*m+z*s*q,B=y*o*n+z*s*r,C=y*p+z*t;x[f]=[Math.atan2(B,A)/a,Math.atan2(C,Math.sqrt(A*A+B*B))/a]}return x}var b=n,c=o,d=100,e=6371;f.source=function(a){if(!arguments.length)return b;b=a;return f},f.target=function(a){if(!arguments.length)return c;c=a;return f},f.n=function(a){if(!arguments.length)return d;d=+a;return f},f.radius=function(a){if(!arguments.length)return e;e=+a;return f},f.distance=function(d,f){var g=b.call(this,d,f),h=c.call(this,d,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.sin((l-j)/2),n=Math.sin((k-i)/2),o=m*m+Math.cos(j)*Math.cos(l)*n*n;return e*2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))};return f}})() <ide>\ No newline at end of file <ide><path>src/geo/azimuthal.js <ide> // TODO clip input coordinates on opposite hemisphere <ide> d3.geo.azimuthal = function() { <del> var mode = "orthographic", // or stereographic <add> var mode = "orthographic", // or stereographic, gnomonic or equidistant <ide> origin, <ide> scale = 200, <ide> translate = [480, 250], <ide> d3.geo.azimuthal = function() { <ide> sx1 = Math.sin(x1), <ide> cy1 = Math.cos(y1), <ide> sy1 = Math.sin(y1), <del> k = mode === "stereographic" ? 1 / (sy0 * sy1 + cy0 * cy1 * cx1 + 1) <del> : mode === "gnomonic" ? 1 / (sy0 * sy1 + cy0 * cy1 * cx1) <add> cc = mode !== "orthographic" ? sy0 * sy1 + cy0 * cy1 * cx1 : null, <add> c, <add> k = mode === "stereographic" ? 1 / (1 + cc) <add> : mode === "gnomonic" ? 1 / cc <add> : mode === "equidistant" ? (c = Math.acos(cc), c / Math.sin(c)) <ide> : 1, <ide> x = k * cy1 * sx1, <ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1); <ide> d3.geo.azimuthal = function() { <ide> p = Math.sqrt(x * x + y * y), <ide> c = mode === "stereographic" ? 2 * Math.atan(p) <ide> : mode === "gnomonic" ? Math.atan(p) <add> : mode === "equidistant" ? p <ide> : Math.asin(p), <ide> sc = Math.sin(c), <ide> cc = Math.cos(c); <ide><path>test/geo/azimuthal-test.js <ide> suite.addBatch({ <ide> assert.inDelta(lonlat[1], 85, 1e-6); <ide> } <ide> }, <add> "azimuthal.equidistant": { <add> topic: function() { <add> return d3.geo.azimuthal().mode("equidistant").translate([0, 0]).scale(100); <add> }, <add> "Arctic": function(azimuthal) { <add> var coords = azimuthal([0, 85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], -148.352986, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> }, <add> "Antarctic": function(azimuthal) { <add> var coords = azimuthal([0, -85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 148.352986, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], -85, 1e-6); <add> }, <add> "Hawaii": function(azimuthal) { <add> var coords = azimuthal([-180, 0]); <add> assert.inDelta(coords[0], -314.159265, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], -180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Phillipines": function(azimuthal) { <add> var coords = azimuthal([180, 0]); <add> assert.inDelta(coords[0], 314.159265, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Inversion works for non-zero translation": function() { <add> var azimuthal = d3.geo.azimuthal().mode("stereographic").translate([123, 99]).scale(100), <add> coords = azimuthal([0, 85]), <add> lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> } <add> } <ide> }); <ide> <ide> suite.export(module);
4
Text
Text
update readfilesync in fs.md
2614d247fb3cb6ceb65350a49a927d68696f2e62
<ide><path>doc/api/fs.md <ide> fs.appendFile('message.txt', 'data to append', 'utf8', callback); <ide> <ide> Any specified file descriptor has to have been opened for appending. <ide> <del>_Note: If a file descriptor is specified as the `file`, it will not be closed <del>automatically._ <add>*Note*: If a file descriptor is specified as the `file`, it will not be closed <add>automatically. <ide> <ide> ## fs.appendFileSync(file, data[, options]) <ide> <!-- YAML <ide> On Linux, positional writes don't work when the file is opened in append mode. <ide> The kernel ignores the position argument and always appends the data to <ide> the end of the file. <ide> <del>_Note: The behavior of `fs.open()` is platform specific for some flags. As such, <add>*Note*: The behavior of `fs.open()` is platform-specific for some flags. As such, <ide> opening a directory on macOS and Linux with the `'a+'` flag - see example <ide> below - will return an error. In contrast, on Windows and FreeBSD, a file <del>descriptor will be returned._ <add>descriptor will be returned. <ide> <ide> ```js <ide> // macOS and Linux <ide> If `options` is a string, then it specifies the encoding. Example: <ide> ```js <ide> fs.readFile('/etc/passwd', 'utf8', callback); <ide> ``` <add>*Note*: When the path is a directory, the behavior of <add>`fs.readFile()` and [`fs.readFileSync()`][] is platform-specific. On macOS, <add>Linux, and Windows, an error will be returned. On FreeBSD, a representation <add>of the directory's contents will be returned. <add> <add>```js <add>// macOS, Linux and Windows <add>fs.readFile('<directory>', (err, data) => { <add> // => [Error: EISDIR: illegal operation on a directory, read <directory>] <add>}); <add> <add>// FreeBSD <add>fs.readFile('<directory>', (err, data) => { <add> // => null, <data> <add>}); <add>``` <ide> <ide> Any specified file descriptor has to support reading. <ide> <del>_Note: If a file descriptor is specified as the `path`, it will not be closed <del>automatically._ <add>*Note*: If a file descriptor is specified as the `path`, it will not be closed <add>automatically. <ide> <ide> ## fs.readFileSync(path[, options]) <ide> <!-- YAML <ide> Synchronous version of [`fs.readFile`][]. Returns the contents of the `file`. <ide> If the `encoding` option is specified then this function returns a <ide> string. Otherwise it returns a buffer. <ide> <add>*Note*: Similar to [`fs.readFile()`][], when the path is a directory, the <add>behavior of `fs.readFileSync()` is platform-specific. <add> <add>```js <add>// macOS, Linux and Windows <add>fs.readFileSync('<directory>'); <add>// => [Error: EISDIR: illegal operation on a directory, read <directory>] <add> <add>// FreeBSD <add>fs.readFileSync('<directory>'); // => null, <data> <add>``` <add> <ide> ## fs.readlink(path[, options], callback) <ide> <!-- YAML <ide> added: v0.1.31 <ide> effectively stopping watching of `filename`. <ide> Calling `fs.unwatchFile()` with a filename that is not being watched is a <ide> no-op, not an error. <ide> <del>_Note: [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. <add>*Note*: [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. <ide> `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` <del>when possible._ <add>when possible. <ide> <ide> ## fs.utimes(path, atime, mtime, callback) <ide> <!-- YAML <ide> These stat objects are instances of `fs.Stat`. <ide> To be notified when the file was modified, not just accessed, it is necessary <ide> to compare `curr.mtime` and `prev.mtime`. <ide> <del>_Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will <add>*Note*: when an `fs.watchFile` operation results in an `ENOENT` error, it will <ide> invoke the listener once, with all the fields zeroed (or, for dates, the Unix <ide> Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead <ide> of zero. If the file is created later on, the listener will be called again, <del> with the latest stat objects. This is a change in functionality since v0.10._ <add> with the latest stat objects. This is a change in functionality since v0.10. <ide> <del>_Note: [`fs.watch()`][] is more efficient than `fs.watchFile` and <add>*Note*: [`fs.watch()`][] is more efficient than `fs.watchFile` and <ide> `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and <del>`fs.unwatchFile` when possible._ <add>`fs.unwatchFile` when possible. <ide> <ide> ## fs.write(fd, buffer[, offset[, length[, position]]], callback) <ide> <!-- YAML <ide> Note that it is unsafe to use `fs.writeFile` multiple times on the same file <ide> without waiting for the callback. For this scenario, <ide> `fs.createWriteStream` is strongly recommended. <ide> <del>_Note: If a file descriptor is specified as the `file`, it will not be closed <del>automatically._ <add>*Note*: If a file descriptor is specified as the `file`, it will not be closed <add>automatically. <ide> <ide> ## fs.writeFileSync(file, data[, options]) <ide> <!-- YAML
1
Python
Python
fix typo in test
f9ff27790978d0f36cc55f2c601229b31a154aaa
<ide><path>libcloud/test/compute/test_openstack.py <ide> def test_ex_create_router(self): <ide> self.assertEqual(router.name, 'router1') <ide> <ide> def test_ex_delete_router(self): <del> router = self.driver.ex_list_routers()[0] <add> router = self.driver.ex_list_routers()[1] <ide> self.assertTrue(self.driver.ex_delete_router(router=router)) <ide> <ide> class OpenStack_1_1_FactoryMethodTests(OpenStack_1_1_Tests):
1
PHP
PHP
use array_key_exists instead of isset()
a30f861f2c53b888f41fe9242138f0e1e3147466
<ide><path>lib/Cake/Test/Case/Utility/HashTest.php <ide> public function testContains() { <ide> ); <ide> $this->assertTrue(Hash::contains($b, $a)); <ide> $this->assertFalse(Hash::contains($a, $b)); <add> <add> $a = array(0 => 'test', 'string' => null); <add> $this->assertTrue(Hash::contains($a, array('string' => null))); <add> <add> $a = array(0 => 'test', 'string' => null); <add> $this->assertTrue(Hash::contains($a, array('test'))); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Utility/Hash.php <ide> public static function contains(array $data, array $needle) { <ide> $val = $needle[$key]; <ide> unset($needle[$key]); <ide> <del> if (isset($data[$key]) && is_array($val)) { <add> if (array_key_exists($key, $data) && is_array($val)) { <ide> $next = $data[$key]; <ide> unset($data[$key]); <ide> <ide> if (!empty($val)) { <ide> $stack[] = array($val, $next); <ide> } <del> } elseif (!isset($data[$key]) || $data[$key] != $val) { <add> } elseif (!array_key_exists($key, $data) || $data[$key] != $val) { <ide> return false; <ide> } <ide>
2
Python
Python
add changelog to pypi sidebar
a5f140bce9800221e8f68b9f5493e4ba4e4bc3b4
<ide><path>setup.py <ide> def run_tests(self): <ide> ] <ide> }, <ide> project_urls={ <del> "Documentation": "http://docs.celeryproject.org/en/latest/index.html", <add> "Documentation": "https://docs.celeryproject.org/en/latest/index.html", <add> "Changelog": "https://docs.celeryproject.org/en/stable/changelog.html", <ide> "Code": "https://github.com/celery/celery", <ide> "Tracker": "https://github.com/celery/celery/issues", <ide> "Funding": "https://opencollective.com/celery"
1
Go
Go
use beam.router to simplify the 'stdio' command
9206b18818db988621f60cbf869eb20acd1a49e9
<ide><path>pkg/beam/examples/beamsh/beamsh.go <ide> func GetHandler(name string) Handler { <ide> defer stderr.Close() <ide> var tasks sync.WaitGroup <ide> defer tasks.Wait() <del> for { <del> payload, attachment, err := in.Receive() <del> if err != nil { <del> return <del> } <del> cmd := data.Message(payload).Get("cmd") <del> if attachment != nil && len(cmd) > 0 && cmd[0] == "log" { <del> w, err := beam.SendPipe(out, payload) <del> if err != nil { <del> attachment.Close() <del> fmt.Fprintf(stderr, "sendpipe: %v\n", err) <del> return <del> } <del> tasks.Add(1) <del> go func(payload []byte, attachment *os.File, sink *os.File) { <del> defer tasks.Done() <del> defer attachment.Close() <del> defer sink.Close() <del> cmd := data.Message(payload).Get("cmd") <del> if cmd == nil || len(cmd) == 0 { <del> return <del> } <del> if cmd[0] != "log" { <del> return <del> } <del> var output io.Writer <del> if len(cmd) == 1 || cmd[1] == "stdout" { <del> output = os.Stdout <del> } else if cmd[1] == "stderr" { <del> output = os.Stderr <del> } <del> io.Copy(io.MultiWriter(output, sink), attachment) <del> }(payload, attachment, w) <del> } else { <del> if err := out.Send(payload, attachment); err != nil { <del> return <del> } <del> } <add> <add> r := beam.NewRouter(out) <add> r.NewRoute().HasAttachment().KeyStartsWith("cmd", "log").Handler(func(payload []byte, attachment *os.File) error { <add> tasks.Add(1) <add> go func() { <add> defer tasks.Done() <add> defer attachment.Close() <add> io.Copy(os.Stdout, attachment) <add> attachment.Close() <add> }() <add> return nil <add> }).Tee(out) <add> <add> if _, err := beam.Copy(r, in); err != nil { <add> Fatal(err) <add> fmt.Fprintf(stderr, "%v\n", err) <add> return <ide> } <ide> } <ide> } else if name == "echo" {
1
Ruby
Ruby
fix extension for compress
b30ab67ca68155586620f55d1ee562fbf4cffacf
<ide><path>Library/Homebrew/unpack_strategy/compress.rb <ide> class Compress < Tar <ide> using Magic <ide> <ide> def self.extensions <del> [".compress"] <add> [".Z"] <ide> end <ide> <ide> def self.can_extract?(path)
1
Ruby
Ruby
replace tabs with spaces
c83dd0d04b857161b47a43b54ba56c7296ac50c0
<ide><path>Library/Homebrew/test/os/linux/dependency_collector_spec.rb <ide> <ide> context "when xz, zip, and bzip2 are not available" do <ide> it "creates a resource dependency from a '.xz' URL" do <del> resource.url("http://example.com/foo.xz") <del> allow_any_instance_of(Object).to receive(:which).with("xz") <del> expect(subject.add(resource)).to eq(Dependency.new("xz", [:build])) <add> resource.url("http://example.com/foo.xz") <add> allow_any_instance_of(Object).to receive(:which).with("xz") <add> expect(subject.add(resource)).to eq(Dependency.new("xz", [:build])) <ide> end <ide> <ide> it "creates a resource dependency from a '.zip' URL" do <del> resource.url("http://example.com/foo.zip") <del> allow_any_instance_of(Object).to receive(:which).with("zip") <del> expect(subject.add(resource)).to eq(Dependency.new("zip", [:build])) <add> resource.url("http://example.com/foo.zip") <add> allow_any_instance_of(Object).to receive(:which).with("zip") <add> expect(subject.add(resource)).to eq(Dependency.new("zip", [:build])) <ide> end <ide> <ide> it "creates a resource dependency from a '.bz2' URL" do <del> resource.url("http://example.com/foo.tar.bz2") <del> allow_any_instance_of(Object).to receive(:which).with("bzip2") <del> expect(subject.add(resource)).to eq(Dependency.new("bzip2", [:build])) <add> resource.url("http://example.com/foo.tar.bz2") <add> allow_any_instance_of(Object).to receive(:which).with("bzip2") <add> expect(subject.add(resource)).to eq(Dependency.new("bzip2", [:build])) <ide> end <ide> end <ide> <ide> context "when xz, zip, and bzip2 are available" do <ide> it "does not create a resource dependency from a '.xz' URL" do <del> resource.url("http://example.com/foo.xz") <del> allow_any_instance_of(Object).to receive(:which).with("xz").and_return(Pathname.new("foo")) <del> expect(subject.add(resource)).to be nil <add> resource.url("http://example.com/foo.xz") <add> allow_any_instance_of(Object).to receive(:which).with("xz").and_return(Pathname.new("foo")) <add> expect(subject.add(resource)).to be nil <ide> end <ide> <ide> it "does not create a resource dependency from a '.zip' URL" do <del> resource.url("http://example.com/foo.zip") <del> allow_any_instance_of(Object).to receive(:which).with("zip").and_return(Pathname.new("foo")) <del> expect(subject.add(resource)).to be nil <add> resource.url("http://example.com/foo.zip") <add> allow_any_instance_of(Object).to receive(:which).with("zip").and_return(Pathname.new("foo")) <add> expect(subject.add(resource)).to be nil <ide> end <ide> <ide> it "does not create a resource dependency from a '.bz2' URL" do <del> resource.url("http://example.com/foo.tar.bz2") <del> allow_any_instance_of(Object).to receive(:which).with("bzip2").and_return(Pathname.new("foo")) <del> expect(subject.add(resource)).to be nil <add> resource.url("http://example.com/foo.tar.bz2") <add> allow_any_instance_of(Object).to receive(:which).with("bzip2").and_return(Pathname.new("foo")) <add> expect(subject.add(resource)).to be nil <ide> end <ide> end <ide> end
1
Ruby
Ruby
add doctor check for cpu arch on linux
57109a175a5ca268025e6d39d39867ea05c910bc
<ide><path>Library/Homebrew/extend/os/linux/diagnostic.rb <ide> <ide> require "tempfile" <ide> require "utils/shell" <add>require "hardware" <ide> require "os/linux/diagnostic" <ide> require "os/linux/glibc" <ide> require "os/linux/kernel" <ide> def supported_configuration_checks <ide> %w[ <ide> check_glibc_minimum_version <ide> check_kernel_minimum_version <add> check_supported_architecture <ide> ].freeze <ide> end <ide> <ide> def check_umask_not_zero <ide> EOS <ide> end <ide> <add> def check_supported_architecture <add> return if Hardware::CPU.arch == :x86_64 <add> <add> <<~EOS <add> Your CPU architecture (#{Hardware::CPU.arch}) is not supported. We only support <add> x86_64 CPU architectures. You will be unable to use binary packages (bottles). <add> #{please_create_pull_requests} <add> EOS <add> end <add> <ide> def check_glibc_minimum_version <ide> return unless OS::Linux::Glibc.below_minimum_version? <ide> <ide><path>Library/Homebrew/test/os/linux/diagnostic_spec.rb <ide> require "diagnostic" <ide> <ide> describe Homebrew::Diagnostic::Checks do <add> specify "#check_supported_architecture" do <add> allow(Hardware::CPU).to receive(:type).and_return(:arm64) <add> <add> expect(subject.check_supported_architecture) <add> .to match(/Your CPU architecture .+ is not supported/) <add> end <add> <ide> specify "#check_glibc_minimum_version" do <ide> allow(OS::Linux::Glibc).to receive(:below_minimum_version?).and_return(true) <ide>
2
PHP
PHP
add isnotempty() to the stringable class
07a377af4c8eae4a72eeb8a29f16912e81300cf3
<ide><path>src/Illuminate/Support/Stringable.php <ide> public function isEmpty() <ide> return empty($this->value); <ide> } <ide> <add> /** <add> * Determine if the given string is not empty. <add> * <add> * @return bool <add> */ <add> public function isNotEmpty() <add> { <add> return ! $this->isEmpty(); <add> } <add> <ide> /** <ide> * Convert a string to kebab case. <ide> *
1
Javascript
Javascript
fix color parsing
923de05ba85f1811abfe77cec6093b78a0622e9f
<ide><path>src/color.js <ide> module.exports = class Color { <ide> if (Array.isArray(value)) { <ide> return null; <ide> } <del> value = value.toRGBAString(); <add> value = Object.values(value); <ide> break; <ide> default: <ide> return null;
1
Python
Python
fix failing test case and lint issue
a2b04ff591578ec04e2c34bf05ac5262bca0176e
<ide><path>libcloud/compute/drivers/auroracompute.py <ide> 'AuroraComputeNodeDriver' <ide> ] <ide> <add> <ide> class AuroraComputeNodeDriver(CloudStackNodeDriver): <ide> type = Provider.AURORACOMPUTE <ide> name = 'PCextreme AuroraCompute' <ide><path>libcloud/test/compute/test_auroracompute.py <ide> <ide> import sys <ide> <del>from libcloud.compute.drivers.exoscale import AuroraComputeNodeDriver <add>from libcloud.compute.drivers.auroracompute import AuroraComputeNodeDriver <ide> from libcloud.test.compute.test_cloudstack import CloudStackCommonTestCase <ide> from libcloud.test import unittest <ide> <add> <ide> class AuroraComputeNodeDriverTestCase(CloudStackCommonTestCase, unittest.TestCase): <ide> driver_klass = AuroraComputeNodeDriver <ide>
2
Javascript
Javascript
add check if face are not undefinded
8a774733d986c4b9636ccef8fc1363fb0426a933
<ide><path>examples/jsm/modifiers/SimplifyModifier.js <ide> function collapse( vertices, faces, u, v ) { // u and v are pointers to vertices <ide> // delete triangles on edge uv: <ide> for ( let i = u.faces.length - 1; i >= 0; i -- ) { <ide> <del> if ( u.faces[ i ].hasVertex( v ) ) { <add> if ( u.faces[ i ] && u.faces[ i ].hasVertex( v ) ) { <ide> <ide> removeFace( u.faces[ i ], faces ); <ide>
1
Javascript
Javascript
fix examples using __next_data__
f8f308d6dd6c23476383b2e8d6f80484c194cf6f
<ide><path>examples/with-aphrodite/pages/_document.js <del>import Document, { Head, Main, NextScript } from 'next/document' <add>import Document, { Html, Head, Main, NextScript } from 'next/document' <ide> import { StyleSheetServer } from 'aphrodite' <ide> <del>export default class MyDocument extends Document { <add>class MyDocument extends Document { <ide> static async getInitialProps({ renderPage }) { <ide> const { html, css } = StyleSheetServer.renderStatic(() => renderPage()) <ide> const ids = css.renderedClassNames <ide> return { ...html, css, ids } <ide> } <ide> <del> constructor(props) { <del> super(props) <del> /* Take the renderedClassNames from aphrodite (as generated <del> in getInitialProps) and assign them to __NEXT_DATA__ so that they <del> are accessible to the client for rehydration. */ <del> const { __NEXT_DATA__, ids } = props <del> if (ids) { <del> __NEXT_DATA__.ids = this.props.ids <del> } <del> } <del> <ide> render() { <ide> /* Make sure to use data-aphrodite attribute in the style tag here <ide> so that aphrodite knows which style tag it's in control of when <ide> the client goes to render styles. If you don't you'll get a second <ide> <style> tag */ <add> const { css, ids } = this.props <ide> return ( <del> <html> <add> <Html> <ide> <Head> <ide> <style <ide> data-aphrodite <del> dangerouslySetInnerHTML={{ __html: this.props.css.content }} <add> dangerouslySetInnerHTML={{ __html: css.content }} <ide> /> <ide> </Head> <ide> <body> <ide> <Main /> <ide> <NextScript /> <add> {ids && ( <add> <script <add> dangerouslySetInnerHTML={{ <add> __html: ` <add> window.__REHYDRATE_IDS = ${JSON.stringify(ids)} <add> `, <add> }} <add> /> <add> )} <ide> </body> <del> </html> <add> </Html> <ide> ) <ide> } <ide> } <add> <add>export default MyDocument <ide><path>examples/with-aphrodite/pages/index.js <ide> import { StyleSheet, css } from 'aphrodite' <ide> <add>// Rehydrate to ensure that the client doesn't duplicate styles <add>// It has to execute before any code that defines styles <add>// '__REHYDRATE_IDS' is set in '_document.js' <ide> if (typeof window !== 'undefined') { <del> /* StyleSheet.rehydrate takes an array of rendered classnames, <del> and ensures that the client side render doesn't generate <del> duplicate style definitions in the <style data-aphrodite> tag */ <del> StyleSheet.rehydrate(window.__NEXT_DATA__.ids) <add> StyleSheet.rehydrate(window.__REHYDRATE_IDS) <ide> } <ide> <ide> export default function Home() { <ide><path>examples/with-glamor/pages/_document.js <del>import Document, { Head, Main, NextScript } from 'next/document' <add>import Document, { Html, Head, Main, NextScript } from 'next/document' <ide> import { renderStatic } from 'glamor/server' <ide> <del>export default class MyDocument extends Document { <add>class MyDocument extends Document { <ide> static async getInitialProps({ renderPage }) { <ide> const page = renderPage() <del> const styles = renderStatic(() => page.html || page.errorHtml) <del> return { ...page, ...styles } <del> } <del> <del> constructor(props) { <del> super(props) <del> const { __NEXT_DATA__, ids } = props <del> if (ids) { <del> __NEXT_DATA__.ids = this.props.ids <del> } <add> const { css, ids } = renderStatic(() => page.html || page.errorHtml) <add> return { ...page, css, ids } <ide> } <ide> <ide> render() { <add> const { ids, css } = this.props <ide> return ( <del> <html> <add> <Html> <ide> <Head> <del> <style dangerouslySetInnerHTML={{ __html: this.props.css }} /> <add> <style dangerouslySetInnerHTML={{ __html: css }} /> <ide> </Head> <ide> <body> <ide> <Main /> <ide> <NextScript /> <add> {ids && ( <add> <script <add> dangerouslySetInnerHTML={{ <add> __html: ` <add> window.__REHYDRATE_IDS = ${JSON.stringify(ids)} <add> `, <add> }} <add> /> <add> )} <ide> </body> <del> </html> <add> </Html> <ide> ) <ide> } <ide> } <add> <add>export default MyDocument <ide><path>examples/with-glamor/pages/index.js <del>import { rehydrate } from 'glamor' <add>import { rehydrate, css } from 'glamor' <ide> <del>// Adds server generated styles to glamor cache. <del>// Has to run before any `style()` calls <del>// '__NEXT_DATA__.ids' is set in '_document.js' <add>// Rehydrate to ensure that the client doesn't duplicate styles <add>// It has to execute before any code that defines styles <add>// '__REHYDRATE_IDS' is set in '_document.js' <ide> if (typeof window !== 'undefined') { <del> rehydrate(window.__NEXT_DATA__.ids) <add> rehydrate(window.__REHYDRATE_IDS) <ide> } <ide> <add>const rule = css({ <add> color: 'red', <add> fontSize: 50, <add>}) <add> <ide> export default function Home() { <del> return <h1 css={{ color: 'red', fontSize: 50 }}>My page</h1> <add> return <h1 {...rule}>My page</h1> <ide> } <ide><path>examples/with-react-intl/pages/_app.js <ide> export default class MyApp extends App { <ide> // Get the `locale` and `messages` from the request object on the server. <ide> // In the browser, use the same values that the server serialized. <ide> const { req } = ctx <del> const { locale, messages } = req || window.__NEXT_DATA__.props <add> const { locale, messages } = req <ide> <ide> return { pageProps, locale, messages } <ide> } <ide><path>examples/with-react-with-styles/pages/_document.js <del>import Document, { Head, Main, NextScript } from 'next/document' <add>import Document, { Html, Head, Main, NextScript } from 'next/document' <ide> import { StyleSheetServer } from 'aphrodite' <ide> <del>export default class MyDocument extends Document { <add>class MyDocument extends Document { <ide> static async getInitialProps({ renderPage }) { <ide> const { html, css } = StyleSheetServer.renderStatic(() => renderPage()) <ide> const ids = css.renderedClassNames <ide> return { ...html, css, ids } <ide> } <ide> <del> constructor(props) { <del> super(props) <del> /* Take the renderedClassNames from aphrodite (as generated <del> in getInitialProps) and assign them to __NEXT_DATA__ so that they <del> are accessible to the client for rehydration. */ <del> const { __NEXT_DATA__, ids } = props <del> if (ids) { <del> __NEXT_DATA__.ids = this.props.ids <del> } <del> } <del> <ide> render() { <ide> /* Make sure to use data-aphrodite attribute in the style tag here <del> so that aphrodite knows which style tag it's in control of when <del> the client goes to render styles. If you don't you'll get a second <del> <style> tag */ <add> so that aphrodite knows which style tag it's in control of when <add> the client goes to render styles. If you don't you'll get a second <add> <style> tag */ <add> const { css, ids } = this.props <ide> return ( <del> <html> <add> <Html> <ide> <Head> <ide> <style <ide> data-aphrodite <del> dangerouslySetInnerHTML={{ __html: this.props.css.content }} <add> dangerouslySetInnerHTML={{ __html: css.content }} <ide> /> <ide> </Head> <ide> <body> <ide> <Main /> <ide> <NextScript /> <add> {ids && ( <add> <script <add> dangerouslySetInnerHTML={{ <add> __html: ` <add> window.__REHYDRATE_IDS = ${JSON.stringify(ids)} <add> `, <add> }} <add> /> <add> )} <ide> </body> <del> </html> <add> </Html> <ide> ) <ide> } <ide> } <add> <add>export default MyDocument
6
Java
Java
clarify intent of unit test
8926255abff6c75b843fb250d7da842f1719cc83
<ide><path>rxjava-core/src/test/java/rx/operators/OperationTimeoutTest.java <ide> public Observable<Integer> call() { <ide> } <ide> <ide> @Test <del> public void testTimeoutSelectorTimeoutFirst() { <del> PublishSubject<Integer> source = PublishSubject.create(); <add> public void testTimeoutSelectorTimeoutFirst() throws InterruptedException { <add> Observable<Integer> source = Observable.<Integer>never(); <ide> final PublishSubject<Integer> timeout = PublishSubject.create(); <ide> <ide> Func1<Integer, Observable<Integer>> timeoutFunc = new Func1<Integer, Observable<Integer>>() { <ide> public Observable<Integer> call() { <ide> Observer<Object> o = mock(Observer.class); <ide> InOrder inOrder = inOrder(o); <ide> <del> source.toObservable().timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(new TestObserver<Object>(o)); <del> <add> source.timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(new TestObserver<Object>(o)); <add> <ide> timeout.onNext(1); <del> <add> <ide> inOrder.verify(o).onNext(100); <ide> inOrder.verify(o).onCompleted(); <ide> verify(o, never()).onError(any(Throwable.class)); <ide> public Observable<Integer> call() { <ide> <ide> @Test <ide> public void testTimeoutSelectorFirstThrows() { <del> PublishSubject<Integer> source = PublishSubject.create(); <add> Observable<Integer> source = Observable.<Integer>never(); <ide> final PublishSubject<Integer> timeout = PublishSubject.create(); <ide> <ide> Func1<Integer, Observable<Integer>> timeoutFunc = new Func1<Integer, Observable<Integer>>() { <ide> public Observable<Integer> call() { <ide> @SuppressWarnings("unchecked") <ide> Observer<Object> o = mock(Observer.class); <ide> <del> source.toObservable().timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(new TestObserver<Object>(o)); <add> source.timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(new TestObserver<Object>(o)); <ide> <ide> verify(o).onError(any(OperationReduceTest.CustomException.class)); <ide> verify(o, never()).onNext(any());
1
Java
Java
rename backpressurestrategy.none to missing
07d24c2ecc61eea94b6d646e02ddd9799b42de7c
<ide><path>src/main/java/io/reactivex/BackpressureStrategy.java <ide> public enum BackpressureStrategy { <ide> * Downstream has to deal with any overflow. <ide> * <p>Useful when one applies one of the custom-parameter onBackpressureXXX operators. <ide> */ <del> NONE, <add> MISSING, <ide> /** <ide> * Signals a MissingBackpressureException in case the downstream can't keep up. <ide> */ <ide><path>src/main/java/io/reactivex/Observable.java <ide> public final Flowable<T> toFlowable(BackpressureStrategy strategy) { <ide> return o.onBackpressureDrop(); <ide> case LATEST: <ide> return o.onBackpressureLatest(); <del> case NONE: <add> case MISSING: <ide> return o; <ide> case ERROR: <ide> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<T>(o)); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCreate.java <ide> public void subscribeActual(Subscriber<? super T> t) { <ide> BaseEmitter<T> emitter; <ide> <ide> switch (backpressure) { <del> case NONE: { <del> emitter = new NoneEmitter<T>(t); <add> case MISSING: { <add> emitter = new MissingEmitter<T>(t); <ide> break; <ide> } <ide> case ERROR: { <ide> public final FlowableEmitter<T> serialize() { <ide> } <ide> } <ide> <del> static final class NoneEmitter<T> extends BaseEmitter<T> { <add> static final class MissingEmitter<T> extends BaseEmitter<T> { <ide> <ide> <ide> private static final long serialVersionUID = 3776720187248809713L; <ide> <del> NoneEmitter(Subscriber<? super T> actual) { <add> MissingEmitter(Subscriber<? super T> actual) { <ide> super(actual); <ide> } <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableCreateTest.java <ide> public void subscribe(FlowableEmitter<Integer> e) throws Exception { <ide> } <ide> <ide> @Test <del> public void createNullValueNone() { <add> public void createNullValueMissing() { <ide> final Throwable[] error = { null }; <ide> <ide> Flowable.create(new FlowableOnSubscribe<Integer>() { <ide> public void subscribe(FlowableEmitter<Integer> e) throws Exception { <ide> error[0] = ex; <ide> } <ide> } <del> }, BackpressureStrategy.NONE) <add> }, BackpressureStrategy.MISSING) <ide> .test() <ide> .assertFailure(NullPointerException.class); <ide> <ide> public void subscribe(FlowableEmitter<Integer> e) throws Exception { <ide> } <ide> <ide> @Test <del> public void createNullValueNoneSerialized() { <add> public void createNullValueMissingSerialized() { <ide> final Throwable[] error = { null }; <ide> <ide> Flowable.create(new FlowableOnSubscribe<Integer>() { <ide> public void subscribe(FlowableEmitter<Integer> e) throws Exception { <ide> error[0] = ex; <ide> } <ide> } <del> }, BackpressureStrategy.NONE) <add> }, BackpressureStrategy.MISSING) <ide> .test() <ide> .assertFailure(NullPointerException.class); <ide> <ide> public void subscribe(FlowableEmitter<Integer> e) throws Exception { <ide> <ide> @Test(expected = NullPointerException.class) <ide> public void nullArgument() { <del> Flowable.create(null, BackpressureStrategy.NONE); <add> Flowable.create(null, BackpressureStrategy.MISSING); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromObservableTest.java <ide> public class FlowableFromObservableTest { <ide> @Test <ide> public void dispose() { <del> TestHelper.checkDisposed(Observable.just(1).toFlowable(BackpressureStrategy.NONE)); <add> TestHelper.checkDisposed(Observable.just(1).toFlowable(BackpressureStrategy.MISSING)); <ide> } <ide> <ide> @Test <ide> public void error() { <ide> Observable.error(new TestException()) <del> .toFlowable(BackpressureStrategy.NONE) <add> .toFlowable(BackpressureStrategy.MISSING) <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSourceTest.java <ide> public void normalLatest() { <ide> } <ide> <ide> @Test <del> public void normalNone() { <del> Flowable.create(source, BackpressureStrategy.NONE).subscribe(ts); <add> public void normalMissing() { <add> Flowable.create(source, BackpressureStrategy.MISSING).subscribe(ts); <ide> <ide> source.onNext(1); <ide> source.onNext(2); <ide> public void normalNone() { <ide> } <ide> <ide> @Test <del> public void normalNoneRequested() { <del> Flowable.create(source, BackpressureStrategy.NONE).subscribe(ts); <add> public void normalMissingRequested() { <add> Flowable.create(source, BackpressureStrategy.MISSING).subscribe(ts); <ide> ts.request(2); <ide> <ide> source.onNext(1); <ide> public void errorLatest() { <ide> } <ide> <ide> @Test <del> public void errorNone() { <del> Flowable.create(source, BackpressureStrategy.NONE).subscribe(ts); <add> public void errorMissing() { <add> Flowable.create(source, BackpressureStrategy.MISSING).subscribe(ts); <ide> <ide> source.onNext(1); <ide> source.onNext(2); <ide> public void unsubscribedDrop() { <ide> } <ide> <ide> @Test <del> public void unsubscribedNone() { <del> Flowable.create(source, BackpressureStrategy.NONE).subscribe(ts); <add> public void unsubscribedMissing() { <add> Flowable.create(source, BackpressureStrategy.MISSING).subscribe(ts); <ide> ts.cancel(); <ide> <ide> source.onNext(1); <ide> public void unsubscribedNoCancelDrop() { <ide> } <ide> <ide> @Test <del> public void unsubscribedNoCancelNone() { <del> Flowable.create(sourceNoCancel, BackpressureStrategy.NONE).subscribe(ts); <add> public void unsubscribedNoCancelMissing() { <add> Flowable.create(sourceNoCancel, BackpressureStrategy.MISSING).subscribe(ts); <ide> ts.cancel(); <ide> <ide> sourceNoCancel.onNext(1); <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java <ide> public void subscribe(FlowableEmitter<Object> s) throws Exception { <ide> s.onNext(i); <ide> } <ide> } <del> }, BackpressureStrategy.NONE) <add> }, BackpressureStrategy.MISSING) <ide> .publish(8) <ide> .autoConnect() <ide> .test(0L) <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableToXTest.java <ide> public void toFlowableError2() { <ide> @Test <ide> public void toFlowableMissing() { <ide> TestSubscriber<Integer> ts = Observable.range(1, 5) <del> .toFlowable(BackpressureStrategy.NONE) <add> .toFlowable(BackpressureStrategy.MISSING) <ide> .test(0); <ide> <ide> ts.request(2);
8
Ruby
Ruby
fix typo in migration test. closes [h-lame]
6f0b0125d0f9044074fcb6f9b1528937a2bb4d2e
<ide><path>activerecord/test/cases/migration_test.rb <ide> def test_rename_column_with_an_index <ide> table.column :hat_name, :string, :limit => 100 <ide> table.column :hat_size, :integer <ide> end <del> Person.connection.add_index :people, :first_name <add> Person.connection.add_index :hats, :hat_name <ide> assert_nothing_raised do <ide> Person.connection.rename_column "hats", "hat_name", "name" <ide> end
1
Javascript
Javascript
change throws to errors
66e3441e0eccc2bea2d608fd02f1c4795f1c02f6
<ide><path>src/canvas.js <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var fontObj = this.objs.get(fontRefName).fontObj; <ide> <ide> if (!fontObj) { <del> throw 'Can\'t find font for ' + fontRefName; <add> error('Can\'t find font for ' + fontRefName); <ide> } <ide> <ide> var name = fontObj.loadedName || 'sans-serif'; <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> } else if (IR[0] == 'RadialAxial' || IR[0] == 'Dummy') { <ide> var pattern = Pattern.shadingFromIR(this.ctx, IR); <ide> } else { <del> throw 'Unkown IR type'; <add> error('Unkown IR type ' + IR[0]); <ide> } <ide> return pattern; <ide> }, <ide><path>src/core.js <ide> var Page = (function PageClosure() { <ide> if (callback) <ide> callback(e); <ide> else <del> throw e; <add> error(e); <ide> } <ide> }.bind(this), <ide> function pageDisplayReadPromiseError(reason) { <ide> if (callback) <ide> callback(reason); <ide> else <del> throw reason; <add> error(reason); <ide> } <ide> ); <ide> } <ide> var PDFDoc = (function PDFDocClosure() { <ide> if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { <ide> var workerSrc = PDFJS.workerSrc; <ide> if (typeof workerSrc === 'undefined') { <del> throw 'No PDFJS.workerSrc specified'; <add> error('No PDFJS.workerSrc specified'); <ide> } <ide> <ide> try { <ide> var PDFDoc = (function PDFDocClosure() { <ide> }); <ide> break; <ide> default: <del> throw 'Got unkown object type ' + type; <add> error('Got unkown object type ' + type); <ide> } <ide> }, this); <ide> <ide> var PDFDoc = (function PDFDocClosure() { <ide> if (page.displayReadyPromise) <ide> page.displayReadyPromise.reject(data.error); <ide> else <del> throw data.error; <add> error(data.error); <ide> }, this); <ide> <ide> messageHandler.on('jpeg_decode', function(data, promise) { <ide><path>src/jpx.js <ide> var JpxImage = (function JpxImageClosure() { <ide> } <ide> r = 0; <ide> } <del> throw 'Out of packets'; <add> error('Out of packets'); <ide> }; <ide> } <ide> function ResolutionLayerComponentPositionIterator(context) { <ide> var JpxImage = (function JpxImageClosure() { <ide> } <ide> l = 0; <ide> } <del> throw 'Out of packets'; <add> error('Out of packets'); <ide> }; <ide> } <ide> function buildPackets(context) { <ide> var JpxImage = (function JpxImageClosure() { <ide> new ResolutionLayerComponentPositionIterator(context); <ide> break; <ide> default: <del> throw 'Unsupported progression order'; <add> error('Unsupported progression order ' + progressionOrder); <ide> } <ide> } <ide> function parseTilePackets(context, data, offset, dataLength) { <ide> var JpxImage = (function JpxImageClosure() { <ide> if (lbox == 0) <ide> lbox = length - position + headerSize; <ide> if (lbox < headerSize) <del> throw 'Invalid box field size'; <add> error('Invalid box field size'); <ide> var dataLength = lbox - headerSize; <ide> var jumpDataLength = true; <ide> switch (tbox) { <ide> var JpxImage = (function JpxImageClosure() { <ide> scalarExpounded = true; <ide> break; <ide> default: <del> throw 'Invalid SQcd value'; <add> error('Invalid SQcd value ' + sqcd); <ide> } <ide> qcd.noQuantization = spqcdSize == 8; <ide> qcd.scalarExpounded = scalarExpounded; <ide> var JpxImage = (function JpxImageClosure() { <ide> scalarExpounded = true; <ide> break; <ide> default: <del> throw 'Invalid SQcd value'; <add> error('Invalid SQcd value ' + sqcd); <ide> } <ide> qcc.noQuantization = spqcdSize == 8; <ide> qcc.scalarExpounded = scalarExpounded; <ide> var JpxImage = (function JpxImageClosure() { <ide> cod.terminationOnEachCodingPass || <ide> cod.verticalyStripe || cod.predictableTermination || <ide> cod.segmentationSymbolUsed) <del> throw 'Unsupported COD options: ' + uneval(cod); <add> error('Unsupported COD options: ' + uneval(cod)); <ide> <ide> if (context.mainHeader) <ide> context.COD = cod; <ide> var JpxImage = (function JpxImageClosure() { <ide> // skipping content <ide> break; <ide> default: <del> throw 'Unknown codestream code: ' + code.toString(16); <add> error('Unknown codestream code: ' + code.toString(16)); <ide> } <ide> position += length; <ide> } <ide><path>src/obj.js <ide> var XRef = (function XRefClosure() { <ide> var stream, parser; <ide> if (e.uncompressed) { <ide> if (e.gen != gen) <del> throw ('inconsistent generation in XRef'); <add> error('inconsistent generation in XRef'); <ide> stream = this.stream.makeSubStream(e.offset); <ide> parser = new Parser(new Lexer(stream), true, this); <ide> var obj1 = parser.getObj(); <ide> var PDFObjects = (function PDFObjectsClosure() { <ide> // If there isn't an object yet or the object isn't resolved, then the <ide> // data isn't ready yet! <ide> if (!obj || !obj.isResolved) { <del> throw 'Requesting object that isn\'t resolved yet ' + objId; <add> error('Requesting object that isn\'t resolved yet ' + objId); <ide> return null; <ide> } else { <ide> return obj.data; <ide><path>src/stream.js <ide> var JpegStream = (function JpegStreamClosure() { <ide> JpegStream.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) { <ide> if (this.bufferLength) <ide> return; <del> var jpegImage = new JpegImage(); <del> if (this.colorTransform != -1) <del> jpegImage.colorTransform = this.colorTransform; <del> jpegImage.parse(this.bytes); <del> var width = jpegImage.width; <del> var height = jpegImage.height; <del> var data = jpegImage.getData(width, height); <del> this.buffer = data; <del> this.bufferLength = data.length; <add> try { <add> var jpegImage = new JpegImage(); <add> if (this.colorTransform != -1) <add> jpegImage.colorTransform = this.colorTransform; <add> jpegImage.parse(this.bytes); <add> var width = jpegImage.width; <add> var height = jpegImage.height; <add> var data = jpegImage.getData(width, height); <add> this.buffer = data; <add> this.bufferLength = data.length; <add> } catch (e) { <add> error(e); <add> } <ide> }; <ide> JpegStream.prototype.getIR = function jpegStreamGetIR() { <ide> return bytesToString(this.bytes); <ide><path>src/util.js <ide> var Promise = (function PromiseClosure() { <ide> return; <ide> } <ide> if (this._data !== EMPTY_PROMISE) { <del> throw 'Promise ' + this.name + <del> ': Cannot set the data of a promise twice'; <add> error('Promise ' + this.name + <add> ': Cannot set the data of a promise twice'); <ide> } <ide> this._data = value; <ide> this.hasData = true; <ide> var Promise = (function PromiseClosure() { <ide> <ide> get data() { <ide> if (this._data === EMPTY_PROMISE) { <del> throw 'Promise ' + this.name + ': Cannot get data that isn\'t set'; <add> error('Promise ' + this.name + ': Cannot get data that isn\'t set'); <ide> } <ide> return this._data; <ide> }, <ide> var Promise = (function PromiseClosure() { <ide> <ide> resolve: function promiseResolve(data) { <ide> if (this.isResolved) { <del> throw 'A Promise can be resolved only once ' + this.name; <add> error('A Promise can be resolved only once ' + this.name); <ide> } <ide> if (this.isRejected) { <del> throw 'The Promise was already rejected ' + this.name; <add> error('The Promise was already rejected ' + this.name); <ide> } <ide> <ide> this.isResolved = true; <ide> var Promise = (function PromiseClosure() { <ide> <ide> reject: function proimseReject(reason) { <ide> if (this.isRejected) { <del> throw 'A Promise can be rejected only once ' + this.name; <add> error('A Promise can be rejected only once ' + this.name); <ide> } <ide> if (this.isResolved) { <del> throw 'The Promise was already resolved ' + this.name; <add> error('The Promise was already resolved ' + this.name); <ide> } <ide> <ide> this.isRejected = true; <ide> var Promise = (function PromiseClosure() { <ide> <ide> then: function promiseThen(callback, errback) { <ide> if (!callback) { <del> throw 'Requiring callback' + this.name; <add> error('Requiring callback' + this.name); <ide> } <ide> <ide> // If the promise is already resolved, call the callback directly. <ide><path>src/worker.js <ide> function MessageHandler(name, comObj) { <ide> delete callbacks[callbackId]; <ide> callback(data.data); <ide> } else { <del> throw 'Cannot resolve callback ' + callbackId; <add> error('Cannot resolve callback ' + callbackId); <ide> } <ide> } else if (data.action in ah) { <ide> var action = ah[data.action]; <ide> function MessageHandler(name, comObj) { <ide> action[0].call(action[1], data.data); <ide> } <ide> } else { <del> throw 'Unkown action from worker: ' + data.action; <add> error('Unkown action from worker: ' + data.action); <ide> } <ide> }; <ide> } <ide> MessageHandler.prototype = { <ide> on: function messageHandlerOn(actionName, handler, scope) { <ide> var ah = this.actionHandler; <ide> if (ah[actionName]) { <del> throw 'There is already an actionName called "' + actionName + '"'; <add> error('There is already an actionName called "' + actionName + '"'); <ide> } <ide> ah[actionName] = [handler, scope]; <ide> }, <ide> var workerConsole = { <ide> timeEnd: function timeEnd(name) { <ide> var time = consoleTimer[name]; <ide> if (time == null) { <del> throw 'Unkown timer name ' + name; <add> error('Unkown timer name ' + name); <ide> } <ide> this.log('Timer:', name, Date.now() - time); <ide> }
7
Javascript
Javascript
add types to template
e02a0c9ecdde1f06460253b551c5ffc90f6d59f4
<ide><path>lib/Chunk.js <ide> class Chunk { <ide> return this._modules.has(module); <ide> } <ide> <add> /** <add> * @returns {Module[]} an array of all modules in this chunk <add> */ <ide> getModules() { <ide> return this._modules.getFromCache(getArray); <ide> } <ide><path>lib/HotUpdateChunk.js <ide> const Chunk = require("./Chunk"); <ide> class HotUpdateChunk extends Chunk { <ide> constructor() { <ide> super(); <add> /** @type {(string|number)[]} */ <ide> this.removedModules = undefined; <ide> } <ide> } <ide><path>lib/Template.js <ide> class Template { <ide> var maxId = bounds[1]; <ide> if (minId !== 0) source.add("Array(" + minId + ").concat("); <ide> source.add("[\n"); <add> /** @type {Map<string|number, {id: string|number, source: Source|string}>} */ <ide> const modules = new Map(); <ide> for (const module of allModules) { <ide> modules.set(module.id, module);
3
Javascript
Javascript
apply lint fixes
a49769c3c0b2436ffa620513e1dd481050c2a87b
<ide><path>client/src/client-only-routes/ShowCertification.js <ide> class ShowCertification extends Component { <ide> <div className='row signatures'> <ide> <Image <ide> alt="Quincy Larson's Signature" <del> src='https://cdn.freecodecamp.org/platform/english/images/quincy-larson-signature.svg' <add> src={ <add> 'https://cdn.freecodecamp.org' + <add> '/platform/english/images/quincy-larson-signature.svg' <add> } <ide> /> <ide> <p> <ide> <strong>Quincy Larson</strong>
1
Python
Python
replace tf.to_float, tf.to_int with tf.cast
7b91ccb1f83aa0ea5a77f86c7273b0dc284c9e0e
<ide><path>official/nlp/transformer/utils/metrics.py <ide> def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): <ide> # Calculate smoothing cross entropy <ide> with tf.name_scope("smoothing_cross_entropy", values=[logits, labels]): <ide> confidence = 1.0 - smoothing <del> low_confidence = (1.0 - confidence) / tf.to_float(vocab_size - 1) <add> low_confidence = (1.0 - confidence) / tf.cast(vocab_size - 1, tf.float32) <ide> soft_targets = tf.one_hot( <ide> tf.cast(labels, tf.int32), <ide> depth=vocab_size, <ide> def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): <ide> # Calculate the best (lowest) possible value of cross entropy, and <ide> # subtract from the cross entropy loss. <ide> normalizing_constant = -( <del> confidence * tf.log(confidence) + tf.to_float(vocab_size - 1) * <del> low_confidence * tf.log(low_confidence + 1e-20)) <add> confidence * tf.log(confidence) + tf.cast(vocab_size - 1, tf.float32) <add> * low_confidence * tf.log(low_confidence + 1e-20)) <ide> xentropy -= normalizing_constant <ide> <del> weights = tf.to_float(tf.not_equal(labels, 0)) <add> weights = tf.cast(tf.not_equal(labels, 0), tf.float32) <ide> return xentropy * weights, weights <ide> <ide> <ide> def padded_accuracy(logits, labels): <ide> """Percentage of times that predictions matches labels on non-0s.""" <ide> with tf.variable_scope("padded_accuracy", values=[logits, labels]): <ide> logits, labels = _pad_tensors_to_same_length(logits, labels) <del> weights = tf.to_float(tf.not_equal(labels, 0)) <del> outputs = tf.to_int32(tf.argmax(logits, axis=-1)) <del> padded_labels = tf.to_int32(labels) <del> return tf.to_float(tf.equal(outputs, padded_labels)), weights <add> weights = tf.cast(tf.not_equal(labels, 0), tf.float32) <add> outputs = tf.cast(tf.argmax(logits, axis=-1), tf.int32) <add> padded_labels = tf.cast(labels, tf.int32) <add> return tf.cast(tf.equal(outputs, padded_labels), tf.float32), weights <ide> <ide> <ide> def padded_accuracy_topk(logits, labels, k): <ide> """Percentage of times that top-k predictions matches labels on non-0s.""" <ide> with tf.variable_scope("padded_accuracy_topk", values=[logits, labels]): <ide> logits, labels = _pad_tensors_to_same_length(logits, labels) <del> weights = tf.to_float(tf.not_equal(labels, 0)) <add> weights = tf.cast(tf.not_equal(labels, 0), tf.float32) <ide> effective_k = tf.minimum(k, tf.shape(logits)[-1]) <ide> _, outputs = tf.nn.top_k(logits, k=effective_k) <del> outputs = tf.to_int32(outputs) <del> padded_labels = tf.to_int32(labels) <add> outputs = tf.cast(outputs, tf.int32) <add> padded_labels = tf.cast(labels, tf.int32) <ide> padded_labels = tf.expand_dims(padded_labels, axis=-1) <ide> padded_labels += tf.zeros_like(outputs) # Pad to same shape. <del> same = tf.to_float(tf.equal(outputs, padded_labels)) <add> same = tf.cast(tf.equal(outputs, padded_labels), tf.float32) <ide> same_topk = tf.reduce_sum(same, axis=-1) <ide> return same_topk, weights <ide> <ide> def padded_sequence_accuracy(logits, labels): <ide> """Percentage of times that predictions matches labels everywhere (non-0).""" <ide> with tf.variable_scope("padded_sequence_accuracy", values=[logits, labels]): <ide> logits, labels = _pad_tensors_to_same_length(logits, labels) <del> weights = tf.to_float(tf.not_equal(labels, 0)) <del> outputs = tf.to_int32(tf.argmax(logits, axis=-1)) <del> padded_labels = tf.to_int32(labels) <del> not_correct = tf.to_float(tf.not_equal(outputs, padded_labels)) * weights <add> weights = tf.cast(tf.not_equal(labels, 0), tf.float32) <add> outputs = tf.cast(tf.argmax(logits, axis=-1), tf.int32) <add> padded_labels = tf.cast(labels, tf.int32) <add> not_correct = (tf.cast(tf.not_equal(outputs, padded_labels), tf.float32) * <add> weights) <ide> axis = list(range(1, len(outputs.get_shape()))) <ide> correct_seq = 1.0 - tf.minimum(1.0, tf.reduce_sum(not_correct, axis=axis)) <ide> return correct_seq, tf.constant(1.0) <ide> def bleu_score(logits, labels): <ide> Returns: <ide> bleu: int, approx bleu score <ide> """ <del> predictions = tf.to_int32(tf.argmax(logits, axis=-1)) <add> predictions = tf.cast(tf.argmax(logits, axis=-1), tf.int32) <ide> # TODO: Look into removing use of py_func <ide> bleu = tf.py_func(compute_bleu, (labels, predictions), tf.float32) <ide> return bleu, tf.constant(1.0) <ide> def rouge_2_fscore(logits, labels): <ide> Returns: <ide> rouge2_fscore: approx rouge-2 f1 score. <ide> """ <del> predictions = tf.to_int32(tf.argmax(logits, axis=-1)) <add> predictions = tf.cast(tf.argmax(logits, axis=-1), tf.int32) <ide> # TODO: Look into removing use of py_func <ide> rouge_2_f_score = tf.py_func(rouge_n, (predictions, labels), tf.float32) <ide> return rouge_2_f_score, tf.constant(1.0) <ide> def rouge_l_fscore(predictions, labels): <ide> Returns: <ide> rouge_l_fscore: approx rouge-l f1 score. <ide> """ <del> outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) <add> outputs = tf.cast(tf.argmax(predictions, axis=-1), tf.int32) <ide> rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels), <ide> tf.float32) <ide> return rouge_l_f_score, tf.constant(1.0)
1
PHP
PHP
fix unsetproperty() not clearing property cache
84eba53f35d22d2ac6678edbd2a2161a0a349a9b
<ide><path>src/Datasource/EntityTrait.php <ide> public function unsetProperty($property) <ide> foreach ($property as $p) { <ide> unset($this->_properties[$p]); <ide> unset($this->_dirty[$p]); <add> unset($this->_mutated[$p]); <ide> } <ide> <ide> return $this; <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testGetCustomGettersAfterSet() <ide> $this->assertEquals('Dr. Mark', $entity->get('name')); <ide> } <ide> <add> /** <add> * Tests that the get cache is cleared by unsetProperty. <add> * <add> * @return void <add> */ <add> public function testGetCacheClearedByUnset() <add> { <add> $entity = $this->getMock('\Cake\ORM\Entity', ['_getName']); <add> $entity->expects($this->any())->method('_getName') <add> ->will($this->returnCallback(function ($name) { <add> return 'Dr. ' . $name; <add> })); <add> $entity->set('name', 'Jones'); <add> $this->assertEquals('Dr. Jones', $entity->get('name')); <add> <add> $entity->unsetProperty('name'); <add> $this->assertEquals('Dr. ', $entity->get('name')); <add> } <add> <add> <ide> /** <ide> * Test magic property setting with no custom setter <ide> *
2
Java
Java
apply property hints to factorybean if necessary
c9faff74917ae78b16cc76c1f56447004208fe9a
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java <ide> import org.springframework.beans.ExtendedBeanInfoFactory; <ide> import org.springframework.beans.MutablePropertyValues; <ide> import org.springframework.beans.PropertyValue; <add>import org.springframework.beans.factory.FactoryBean; <ide> import org.springframework.beans.factory.config.BeanDefinition; <ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder; <ide> private void addConstructorArgumentValues(CodeBlock.Builder builder, <ide> } <ide> <ide> private void addPropertyValues(CodeBlock.Builder builder, <del> BeanDefinition beanDefinition) { <add> RootBeanDefinition beanDefinition) { <ide> <ide> MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); <ide> if (!propertyValues.isEmpty()) { <ide> private void addPropertyValues(CodeBlock.Builder builder, <ide> builder.addStatement("$L.getPropertyValues().addPropertyValue($S, $L)", <ide> BEAN_DEFINITION_VARIABLE, propertyValue.getName(), code); <ide> } <del> Class<?> beanType = ClassUtils <del> .getUserClass(beanDefinition.getResolvableType().toClass()); <del> BeanInfo beanInfo = (beanType != Object.class) ? getBeanInfo(beanType) : null; <add> Class<?> infrastructureType = getInfrastructureType(beanDefinition); <add> BeanInfo beanInfo = (infrastructureType != Object.class) ? getBeanInfo(infrastructureType) : null; <ide> if (beanInfo != null) { <ide> Map<String, Method> writeMethods = getWriteMethods(beanInfo); <ide> for (PropertyValue propertyValue : propertyValues) { <ide> private void addPropertyValues(CodeBlock.Builder builder, <ide> } <ide> } <ide> <add> private Class<?> getInfrastructureType(RootBeanDefinition beanDefinition) { <add> if (beanDefinition.hasBeanClass()) { <add> Class<?> beanClass = beanDefinition.getBeanClass(); <add> if (FactoryBean.class.isAssignableFrom(beanClass)) { <add> return beanClass; <add> } <add> } <add> return ClassUtils.getUserClass(beanDefinition.getResolvableType().toClass()); <add> } <add> <ide> @Nullable <ide> private BeanInfo getBeanInfo(Class<?> beanType) { <ide> try { <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java <ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; <ide> import org.springframework.aot.test.generator.compile.Compiled; <ide> import org.springframework.aot.test.generator.compile.TestCompiler; <add>import org.springframework.beans.factory.FactoryBean; <ide> import org.springframework.beans.factory.config.BeanDefinition; <ide> import org.springframework.beans.factory.config.BeanReference; <ide> import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder; <ide> import org.springframework.javapoet.CodeBlock; <ide> import org.springframework.javapoet.MethodSpec; <ide> import org.springframework.javapoet.ParameterizedTypeName; <add>import org.springframework.lang.Nullable; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> <ide> void propertyValuesWhenContainsManagedMap() { <ide> }); <ide> } <ide> <add> @Test <add> void propertyValuesWhenValuesOnFactoryBeanClass() { <add> this.beanDefinition.setTargetType(String.class); <add> this.beanDefinition.setBeanClass(PropertyValuesFactoryBean.class); <add> this.beanDefinition.getPropertyValues().add("prefix", "Hello"); <add> this.beanDefinition.getPropertyValues().add("name", "World"); <add> compile((actual, compiled) -> { <add> assertThat(actual.getPropertyValues().get("prefix")).isEqualTo("Hello"); <add> assertThat(actual.getPropertyValues().get("name")).isEqualTo("World"); <add> }); <add> String[] methodNames = { "setPrefix", "setName" }; <add> assertHasMethodInvokeHints(PropertyValuesFactoryBean.class, methodNames); <add> } <add> <ide> @Test <ide> void attributesWhenAllFiltered() { <ide> this.beanDefinition.setAttribute("a", "A"); <ide> public void setSpring(String spring) { <ide> <ide> } <ide> <add> static class PropertyValuesFactoryBean implements FactoryBean<String> { <add> <add> private Class<?> prefix; <add> <add> private String name; <add> <add> public Class<?> getPrefix() { <add> return this.prefix; <add> } <add> <add> public void setPrefix(Class<?> prefix) { <add> this.prefix = prefix; <add> } <add> <add> public String getName() { <add> return this.name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> <add> @Nullable <add> @Override <add> public String getObject() throws Exception { <add> return getPrefix() + " " + getName(); <add> } <add> <add> @Nullable <add> @Override <add> public Class<?> getObjectType() { <add> return String.class; <add> } <add> <add> } <add> <ide> }
2
Text
Text
fix example usage
bddc20a66b2ef660983663b1b389d0e607111804
<ide><path>guide/english/bash/bash-ls/index.md <ide> title: Bash ls <ide> ### Usage <ide> <ide> ```bash <del>cat [options] [file_names] <add>ls [options] [folder_path] <ide> ``` <ide> You can list the items in any directory without even entering the directory. Consider you are in a directory with folders- Test1,Test2. You're in the parent directory you can list all files in Test1 as follows- <ide> `ls Test1`
1
Javascript
Javascript
drop pronouns from err_worker_path message
c788964a75c7ccec63bce9d464e9c96eb6e17080
<ide><path>lib/internal/errors.js <ide> E('ERR_WORKER_PATH', (filename) => <ide> 'The worker script or module filename must be an absolute path or a ' + <ide> 'relative path starting with \'./\' or \'../\'.' + <ide> (filename.startsWith('file://') ? <del> ' If you want to pass a file:// URL, you must wrap it around `new URL`.' : <del> '' <add> ' Wrap file:// URLs with `new URL`.' : '' <ide> ) + <ide> ` Received "${filename}"`, <ide> TypeError); <ide><path>test/parallel/test-worker-unsupported-path.js <ide> const { Worker } = require('worker_threads'); <ide> { <ide> assert.throws( <ide> () => { new Worker('file:///file_url'); }, <del> /If you want to pass a file:\/\/ URL, you must wrap it around `new URL`/ <add> /Wrap file:\/\/ URLs with `new URL`/ <ide> ); <ide> assert.throws( <ide> () => { new Worker('relative_no_dot'); }, <ide> // eslint-disable-next-line node-core/no-unescaped-regexp-dot <del> /^((?!If you want to pass a file:\/\/ URL, you must wrap it around `new URL`).)*$/s <add> /^((?!Wrap file:\/\/ URLs with `new URL`).)*$/s <ide> ); <ide> } <ide>
2
Javascript
Javascript
remove usage of `targetobject` computed property
7d1a8d5800db55664e16c5955ec14f9930181406
<ide><path>packages/ember-glimmer/lib/syntax/curly-component.js <ide> class CurlyComponentManager { <ide> <ide> props.renderer = parentView.renderer; <ide> props[HAS_BLOCK] = hasBlock; <add> // parentView.controller represents any parent components <add> // dynamicScope.controller represents the outlet controller <add> props._targetObject = parentView.controller || dynamicScope.controller; <ide> <ide> let component = klass.create(props); <ide> <ide> dynamicScope.view = component; <ide> parentView.appendChild(component); <ide> <del> if (parentView.controller) { <del> dynamicScope.controller = parentView.controller; <del> } <del> <del> component._controller = dynamicScope.controller; <del> <del> <ide> component.trigger('didInitAttrs', { attrs }); <ide> component.trigger('didReceiveAttrs', { newAttrs: attrs }); <ide> component.trigger('willInsertElement'); <ide><path>packages/ember-runtime/lib/mixins/target_action_support.js <ide> export default Mixin.create({ <ide> action: null, <ide> actionContext: null, <ide> <del> targetObject: computed('target', function() { <del> if (this._targetObject) { <del> return this._targetObject; <del> } <del> <del> let target = get(this, 'target'); <del> <del> if (typeof target === 'string') { <del> let value = get(this, target); <del> if (value === undefined) { <del> value = get(context.lookup, target); <del> } <del> <del> return value; <del> } else { <del> return target; <del> } <del> }), <del> <ide> actionContextObject: computed('actionContext', function() { <ide> let actionContext = get(this, 'actionContext'); <ide> <ide> export default Mixin.create({ <ide> */ <ide> triggerAction(opts = {}) { <ide> let action = opts.action || get(this, 'action'); <del> let target = opts.target || get(this, 'targetObject'); <add> let target = opts.target; <add> <add> if (!target) { <add> target = getTarget(this); <add> } <add> <ide> let actionContext = opts.actionContext; <ide> <ide> function args(options, actionName) { <ide> export default Mixin.create({ <ide> } <ide> } <ide> }); <add> <add>function getTarget(instance) { <add> // TODO: Deprecate specifying `targetObject` <add> let target = get(instance, 'targetObject'); <add> <add> // if a `targetObject` CP was provided, use it <add> if (target) { return target; } <add> <add> // if _targetObject use it <add> if (instance._targetObject) { return instance._targetObject; } <add> <add> target = get(instance, 'target'); <add> if (target) { <add> if (typeof target === 'string') { <add> let value = get(instance, target); <add> if (value === undefined) { <add> value = get(context.lookup, target); <add> } <add> <add> return value; <add> } else { <add> return target; <add> } <add> } <add> <add> if (instance._controller) { return instance._controller; } <add> <add> // fallback to `parentView.controller` <add> let parentViewController = get(instance, 'parentView.controller'); <add> if (parentViewController) { return parentViewController; } <add> <add> return null; <add>} <ide><path>packages/ember-views/lib/mixins/action_support.js <ide> import { Mixin } from 'ember-metal/mixin'; <del>import { computed } from 'ember-metal/computed'; <ide> import { get } from 'ember-metal/property_get'; <ide> import isNone from 'ember-metal/is_none'; <ide> import { assert } from 'ember-metal/debug'; <ide> export default Mixin.create({ <ide> } <ide> }, <ide> <del> /** <del> If the component is currently inserted into the DOM of a parent view, this <del> property will point to the controller of the parent view. <del> <del> @property targetObject <del> @type Ember.Controller <del> @default null <del> @private <del> */ <del> targetObject: computed('controller', function(key) { <del> if (this._targetObject) { return this._targetObject; } <del> if (this._controller) { return this._controller; } <del> let parentView = get(this, 'parentView'); <del> return parentView ? get(parentView, 'controller') : null; <del> }), <del> <ide> send(actionName, ...args) { <ide> let target; <ide> let action = this.actions && this.actions[actionName];
3
Go
Go
variablize file names
ba1f76cbfa2c137abfbc607725460e376e6f44d3
<ide><path>graph/graph.go <ide> type Graph struct { <ide> retained *retainedLayers <ide> } <ide> <add>// file names for ./graph/<ID>/ <add>const ( <add> jsonFileName = "json" <add> layersizeFileName = "layersize" <add> digestFileName = "checksum" <add> tardataFileName = "tar-data.json.gz" <add>) <add> <ide> var ( <ide> // ErrDigestNotSet is used when request the digest for a layer <ide> // but the layer has no digest value or content to compute the <ide> func (graph *Graph) loadImage(id string) (*image.Image, error) { <ide> return nil, err <ide> } <ide> <del> if buf, err := ioutil.ReadFile(filepath.Join(root, "layersize")); err != nil { <add> if buf, err := ioutil.ReadFile(filepath.Join(root, layersizeFileName)); err != nil { <ide> if !os.IsNotExist(err) { <ide> return nil, err <ide> } <ide> func (graph *Graph) loadImage(id string) (*image.Image, error) { <ide> <ide> // saveSize stores the `size` in the provided graph `img` directory `root`. <ide> func (graph *Graph) saveSize(root string, size int) error { <del> if err := ioutil.WriteFile(filepath.Join(root, "layersize"), []byte(strconv.Itoa(size)), 0600); err != nil { <del> return fmt.Errorf("Error storing image size in %s/layersize: %s", root, err) <add> if err := ioutil.WriteFile(filepath.Join(root, layersizeFileName), []byte(strconv.Itoa(size)), 0600); err != nil { <add> return fmt.Errorf("Error storing image size in %s/%s: %s", root, layersizeFileName, err) <ide> } <ide> return nil <ide> } <ide> <ide> // SetDigest sets the digest for the image layer to the provided value. <ide> func (graph *Graph) SetDigest(id string, dgst digest.Digest) error { <ide> root := graph.imageRoot(id) <del> if err := ioutil.WriteFile(filepath.Join(root, "checksum"), []byte(dgst.String()), 0600); err != nil { <del> return fmt.Errorf("Error storing digest in %s/checksum: %s", root, err) <add> if err := ioutil.WriteFile(filepath.Join(root, digestFileName), []byte(dgst.String()), 0600); err != nil { <add> return fmt.Errorf("Error storing digest in %s/%s: %s", root, digestFileName, err) <ide> } <ide> return nil <ide> } <ide> <ide> // GetDigest gets the digest for the provide image layer id. <ide> func (graph *Graph) GetDigest(id string) (digest.Digest, error) { <ide> root := graph.imageRoot(id) <del> cs, err := ioutil.ReadFile(filepath.Join(root, "checksum")) <add> cs, err := ioutil.ReadFile(filepath.Join(root, digestFileName)) <ide> if err != nil { <ide> if os.IsNotExist(err) { <ide> return "", ErrDigestNotSet <ide> func (graph *Graph) RawJSON(id string) ([]byte, error) { <ide> } <ide> <ide> func jsonPath(root string) string { <del> return filepath.Join(root, "json") <add> return filepath.Join(root, jsonFileName) <ide> } <ide><path>graph/graph_unix.go <ide> func (graph *Graph) storeImage(img *image.Image, layerData archive.ArchiveReader <ide> // Store the layer. If layerData is not nil, unpack it into the new layer <ide> if layerData != nil { <ide> // this is saving the tar-split metadata <del> mf, err := os.OpenFile(filepath.Join(root, "tar-data.json.gz"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) <add> mf, err := os.OpenFile(filepath.Join(root, tardataFileName), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) <ide> if err != nil { <ide> return err <ide> } <ide> func (graph *Graph) storeImage(img *image.Image, layerData archive.ArchiveReader <ide> <ide> // TarLayer returns a tar archive of the image's filesystem layer. <ide> func (graph *Graph) TarLayer(img *image.Image) (arch archive.Archive, err error) { <add> // TODO(vbatts) let's reassemble! <ide> return graph.driver.Diff(img.ID, img.Parent) <ide> } <ide><path>graph/graph_windows.go <ide> func (graph *Graph) storeImage(img *image.Image, layerData archive.ArchiveReader <ide> // Store the layer. If layerData is not nil, unpack it into the new layer <ide> if layerData != nil { <ide> // this is saving the tar-split metadata <del> mf, err := os.OpenFile(filepath.Join(root, "tar-data.json.gz"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) <add> mf, err := os.OpenFile(filepath.Join(root, tardataFileName), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) <ide> if err != nil { <ide> return err <ide> } <ide> func (graph *Graph) TarLayer(img *image.Image) (arch archive.Archive, err error) <ide> // We keep this functionality here so that we can still work with the VFS <ide> // driver during development. VFS is not supported (and just will not work) <ide> // for Windows containers. <add> // TODO(vbatts) let's reassemble! <ide> return graph.driver.Diff(img.ID, img.Parent) <ide> } <ide> }
3
Python
Python
add default connection in airflow initdb
5c1251f3a9ab40af6f9ff833ed5a9bb8c12ca7fc
<ide><path>airflow/utils.py <ide> def initdb(): <ide> models.Connection( <ide> conn_id='vertica_default', conn_type='vertica', <ide> host='localhost', port=5433)) <add> merge_conn( <add> models.Connection( <add> conn_id='webhdfs_default', conn_type='hdfs', <add> host='localhost', port=50070)) <ide> <ide> # Known event types <ide> KET = models.KnownEventType
1
Text
Text
convert link to homebrew from http to https
e0022f23144fd1dc6db86a5d8c18af47bc14f0f3
<ide><path>README.md <ide> To build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. E <ide> <ide> For Windows, you have to download and install [git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/en/download/). <ide> <del>OS X users should install [Homebrew](http://brew.sh/). Once Homebrew is installed, run `brew install git` to install git, <add>OS X users should install [Homebrew](https://brew.sh/). Once Homebrew is installed, run `brew install git` to install git, <ide> and `brew install node` to install Node.js. <ide> <ide> Linux/BSD users should use their appropriate package managers to install git and Node.js, or build from source
1
Python
Python
use correct version in chart docs
9c792eabb9ed48a7b468e9a76b3662f20ad846cb
<ide><path>docs/conf.py <ide> PACKAGE_VERSION = 'devel' <ide> elif PACKAGE_NAME == 'helm-chart': <ide> PACKAGE_DIR = os.path.join(ROOT_DIR, 'chart') <del> PACKAGE_VERSION = 'devel' # TODO do we care? probably <add> CHART_YAML_FILE = os.path.join(PACKAGE_DIR, 'Chart.yaml') <add> <add> with open(CHART_YAML_FILE) as chart_file: <add> chart_yaml_contents = yaml.load(chart_file, SafeLoader) <add> <add> PACKAGE_VERSION = chart_yaml_contents['version'] <ide> else: <ide> PACKAGE_DIR = None <ide> PACKAGE_VERSION = 'devel'
1
Ruby
Ruby
reinstate previous order of hashes
704ec8abf0ba613bbf594254f3da0fc04ba200a2
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def run_checks(formulae_and_casks_to_check, args) <ide> <ide> is_newer_than_upstream = (formula&.stable? || cask) && (current > latest) <ide> <del> info = { <del> version: { <del> current: current.to_s, <del> latest: latest.to_s, <del> outdated: is_outdated, <del> newer_than_upstream: is_newer_than_upstream, <del> }, <del> meta: { <del> livecheckable: formula_or_cask.livecheckable?, <del> }, <del> } <add> info = {} <ide> info[:formula] = formula_name(formula, args: args) if formula <ide> info[:cask] = cask_name(cask, args: args) if cask <add> info[:version] = { <add> current: current.to_s, <add> latest: latest.to_s, <add> outdated: is_outdated, <add> newer_than_upstream: is_newer_than_upstream, <add> } <add> info[:meta] = { <add> livecheckable: formula_or_cask.livecheckable?, <add> } <ide> info[:meta][:head_only] = true if formula&.head_only? <ide> info[:meta].merge!(version_info[:meta]) if version_info.present? && version_info.key?(:meta) <ide> <ide> def formula_name(formula, args:) <ide> def status_hash(formula_or_cask, status_str, messages = nil, args:) <ide> formula = formula_or_cask if formula_or_cask.is_a?(Formula) <ide> <del> status_hash = { <del> status: status_str, <del> } <del> status_hash[:messages] = messages if messages.is_a?(Array) <del> <add> status_hash = {} <ide> if formula <ide> status_hash[:formula] = formula_name(formula, args: args) <ide> else <ide> status_hash[:cask] = cask_name(formula_or_cask, args: args) <ide> end <add> status_hash[:status] = status_str <add> status_hash[:messages] = messages if messages.is_a?(Array) <ide> <ide> if args.verbose? <ide> status_hash[:meta] = {
1
Ruby
Ruby
fix rubocop warnings
71fd2bb4b0b30b03fbb7b19c53d008b1780006bb
<ide><path>Library/Homebrew/dev-cmd/man.rb <ide> def regenerate_man_pages <ide> end <ide> <ide> def path_glob_commands(glob) <del> Pathname.glob(glob). <del> sort_by { |source_file| sort_key_for_path(source_file) }. <del> map { |source_file| <del> source_file.read.lines. <del> grep(/^#:/). <del> map { |line| line.slice(2..-1) }. <del> join <del> }. <del> reject { |s| s.strip.empty? || s.include?("@hide_from_man_page") } <add> Pathname.glob(glob) <add> .sort_by { |source_file| sort_key_for_path(source_file) } <add> .map do |source_file| <add> source_file.read.lines <add> .grep(/^#:/) <add> .map { |line| line.slice(2..-1) } <add> .join <add> end <add> .reject { |s| s.strip.empty? || s.include?("@hide_from_man_page") } <ide> end <ide> <ide> def build_man_page <ide> def build_man_page <ide> <ide> variables[:commands] = path_glob_commands("#{HOMEBREW_LIBRARY_PATH}/cmd/*.{rb,sh}") <ide> variables[:developer_commands] = path_glob_commands("#{HOMEBREW_LIBRARY_PATH}/dev-cmd/*.{rb,sh}") <del> variables[:maintainers] = (HOMEBREW_REPOSITORY/"README.md"). <del> read[/Homebrew's current maintainers are (.*)\./, 1]. <del> scan(/\[([^\]]*)\]/).flatten <add> variables[:maintainers] = (HOMEBREW_REPOSITORY/"README.md") <add> .read[/Homebrew's current maintainers are (.*)\./, 1] <add> .scan(/\[([^\]]*)\]/).flatten <ide> <del> ERB.new(template, nil, ">").result(variables.instance_eval{ binding }) <add> ERB.new(template, nil, ">").result(variables.instance_eval { binding }) <ide> end <ide> <ide> def sort_key_for_path(path)
1
Python
Python
remove special-casing of empty arrays in unique_1d
2b417df83202df9ea67f1eec76985a3da20cb86c
<ide><path>numpy/lib/arraysetops.py <ide> def _unique1d(ar, return_index=False, return_inverse=False, <ide> <ide> optional_indices = return_index or return_inverse <ide> <del> if ar.size == 0: <del> ret = (ar,) <del> if return_index: <del> ret += (np.empty(0, np.intp),) <del> if return_inverse: <del> ret += (np.empty(0, np.intp),) <del> if return_counts: <del> ret += (np.empty(0, np.intp),) <del> return ret <del> <ide> if optional_indices: <ide> perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') <ide> aux = ar[perm] <ide> else: <ide> ar.sort() <ide> aux = ar <del> flag = np.concatenate(([True], aux[1:] != aux[:-1])) <add> mask = np.empty(aux.shape, dtype=np.bool_) <add> mask[:1] = True <add> mask[1:] = aux[1:] != aux[:-1] <ide> <del> ret = (aux[flag],) <add> ret = (aux[mask],) <ide> if return_index: <del> ret += (perm[flag],) <add> ret += (perm[mask],) <ide> if return_inverse: <del> iflag = np.cumsum(flag) - 1 <add> imask = np.cumsum(mask) - 1 <ide> inv_idx = np.empty(ar.shape, dtype=np.intp) <del> inv_idx[perm] = iflag <add> inv_idx[perm] = imask <ide> ret += (inv_idx,) <ide> if return_counts: <del> idx = np.concatenate(np.nonzero(flag) + ([ar.size],)) <add> idx = np.concatenate(np.nonzero(mask) + ([ar.size],)) <ide> ret += (np.diff(idx),) <ide> return ret <ide>
1
Go
Go
handle dns querries of type mx
6a4c8d0ac95714186bdca67cd277b9b655ee6b7f
<ide><path>libnetwork/resolver.go <ide> func createRespMsg(query *dns.Msg) *dns.Msg { <ide> return resp <ide> } <ide> <add>func (r *resolver) handleMXQuery(name string, query *dns.Msg) (*dns.Msg, error) { <add> addrv4, _ := r.backend.ResolveName(name, types.IPv4) <add> addrv6, _ := r.backend.ResolveName(name, types.IPv6) <add> <add> if addrv4 == nil && addrv6 == nil { <add> return nil, nil <add> } <add> <add> // We were able to resolve the name. Respond with an empty list with <add> // RcodeSuccess/NOERROR so that email clients can treat it as "implicit MX" <add> // [RFC 5321 Section-5.1] and issue a Type A/AAAA query for the name. <add> <add> resp := createRespMsg(query) <add> return resp, nil <add>} <add> <ide> func (r *resolver) handleIPQuery(name string, query *dns.Msg, ipType int) (*dns.Msg, error) { <ide> var addr []net.IP <ide> var ipv6Miss bool <ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) { <ide> resp, err = r.handleIPQuery(name, query, types.IPv4) <ide> case dns.TypeAAAA: <ide> resp, err = r.handleIPQuery(name, query, types.IPv6) <add> case dns.TypeMX: <add> resp, err = r.handleMXQuery(name, query) <ide> case dns.TypePTR: <ide> resp, err = r.handlePTRQuery(name, query) <ide> case dns.TypeSRV:
1
Ruby
Ruby
check input class
68ebf8866ab14334aa6aab8d0672d804c632035d
<ide><path>Library/Homebrew/extend/os/linux/formula.rb <ide> def shared_library(name, version = nil) <ide> <ide> undef allowed_missing_lib? <ide> def allowed_missing_lib?(lib) <add> raise TypeError "Library must be a string; got a #{lib.class} (#{lib})" unless lib.is_a? String <add> <ide> # lib: Full path to the missing library <ide> # Ex.: /home/linuxbrew/.linuxbrew/lib/libsomething.so.1 <ide> # x - Name of or a pattern for a library, linkage to which is allowed to be missing. <ide> def allowed_missing_lib?(lib) <ide> when Regexp <ide> x.match? lib <ide> when String <del> lib.to_s.include? x <add> lib.include? x <ide> end <ide> end <ide> end
1
Python
Python
set bleu_min/max to match acceptable range
c5943a0a34483668be3641e240eba010b75307a6
<ide><path>official/transformer/v2/transformer_benchmark.py <ide> def benchmark_8_gpu(self): <ide> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu') <ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size, <ide> log_steps=FLAGS.log_steps, <del> bleu_min=28, <del> bleu_max=29) <add> bleu_min=27.9, <add> bleu_max=29.2) <ide> <ide> def benchmark_8_gpu_static_batch(self): <ide> """Benchmark 8 gpu. <ide> def benchmark_8_gpu_static_batch(self): <ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size, <ide> log_steps=FLAGS.log_steps, <ide> bleu_min=28, <del> bleu_max=29) <add> bleu_max=29.2) <ide> <ide> def benchmark_8_gpu_fp16(self): <ide> """Benchmark 8 gpu with dynamic batch and fp16. <ide> <del> Should converge to 28.4 BLEU (uncased). This has not be verified yet." <add> Over 6 runs with eval every 20K steps the average highest value was 28.247 <add> (bleu uncased). 28.424 was the highest and 28.09 the lowest. The values are <add> the highest value seen during a run and occurred at a median of iteration <add> 11. While this could be interpreted as worse than FP32, if looking at the <add> first iteration at which 28 is passed FP16 performs equal and possibly <add> better. Although not part of the initial test runs, the highest value <add> recorded with the arguments below was 28.9 at iteration 12. Iterations are <add> not epochs, an iteration is a number of steps between evals. <ide> """ <ide> self._setup() <ide> FLAGS.num_gpus = 8 <ide> def benchmark_8_gpu_fp16(self): <ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size, <ide> log_steps=FLAGS.log_steps, <ide> bleu_min=28, <del> bleu_max=29) <add> bleu_max=29.2) <ide> <ide> def benchmark_8_gpu_static_batch_fp16(self): <ide> """Benchmark 8 gpu with static batch and fp16. <ide> def benchmark_8_gpu_static_batch_fp16(self): <ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size, <ide> log_steps=FLAGS.log_steps, <ide> bleu_min=28, <del> bleu_max=29) <add> bleu_max=29.2) <ide> <ide> def benchmark_xla_8_gpu_static_batch_fp16(self): <ide> """Benchmark 8 gpu with static batch, XLA, and FP16. <ide> def benchmark_xla_8_gpu_static_batch_fp16(self): <ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size, <ide> log_steps=FLAGS.log_steps, <ide> bleu_min=28, <del> bleu_max=29) <add> bleu_max=29.2) <ide> <ide> <ide> class TransformerKerasBenchmark(TransformerBenchmark):
1
Text
Text
remove isstatic and change image to my-icon
a8b34a1516ed1eb3aaac6282db6107f6587c3ac5
<ide><path>docs/Image.md <ide> When your entire codebase respects this convention, you're able to do interestin <ide> <ide> > **NOTE**: PNG images are required when loading with `require('image!my-icon')` <ide> > <del>> At this time, only PNG images are supported in iOS. There is an [issue](https://github.com/facebook/react-native/issues/646) that is currently addressing this bug. In the meantime a quick fix is to rename your files to image.png or to use the `isStatic` flag like: `source={{ uri: 'image', isStatic: true }}`. <add>> At this time, only PNG images are supported in iOS. There is an [issue](https://github.com/facebook/react-native/issues/646) that is currently addressing this bug. In the meantime a quick fix is to rename your files to image.png or to use the `uri` flag like: `source={{ uri: 'my-icon' }}`. <ide> <ide> ### Adding Static Resources to your Android app <ide>
1
Text
Text
update install instructions
3a3e4daf6076fd7d5057fa6890b4c73c9511003a
<ide><path>website/docs/usage/index.md <ide> You can configure the build process with the following environment variables: <ide> | `PYVER` | The Python version to build against. This version needs to be available on your build and runtime machines. Defaults to `3.6`. | <ide> | `WHEELHOUSE` | Directory to store the wheel files during compilation. Defaults to `./wheelhouse`. | <ide> <del>#### Additional options for developers {#source-developers} <del> <del>Some additional options may be useful for spaCy developers who are editing the <del>source code and recompiling frequently. <del> <del>- Install in editable mode. Changes to `.py` files will be reflected as soon as <del> the files are saved, but edits to Cython files (`.pxd`, `.pyx`) will require <del> the `pip install` or `python setup.py build_ext` command below to be run <del> again. Before installing in editable mode, be sure you have removed any <del> previous installs with `pip uninstall spacy`, which you may need to run <del> multiple times to remove all traces of earlier installs. <del> <del> ```diff <del> pip install -U pip setuptools wheel <del> - pip install . <del> + pip install -r requirements.txt <del> + pip install --no-build-isolation --editable . <del> ``` <del> <del>- Build in parallel using `N` CPUs to speed up compilation and then install in <del> editable mode: <del> <del> ```diff <del> pip install -U pip setuptools wheel <del> - pip install . <del> + pip install -r requirements.txt <del> + python setup.py build_ext --inplace -j N <del> + python setup.py develop <del> ``` <del> <ide> ### Run tests {#run-tests} <ide> <ide> spaCy comes with an [extensive test suite](%%GITHUB_SPACY/spacy/tests). In order
1
Javascript
Javascript
check status code in afterwrite
8295c806181654fc6bbc8845c727b7378a196304
<ide><path>lib/net.js <ide> function afterWrite(status, handle, req, buffer) { <ide> if (self.destroyed) { <ide> return; <ide> } <del> // TODO check status. <add> <add> if (status) { <add> self.destroy(errnoException(errno, 'write')); <add> return; <add> } <ide> <ide> timers.active(this); <ide>
1
Go
Go
replace latest log by logrus
10e114fb956db1b1a8bc9308cc6d14cbf30a5bab
<ide><path>daemon/execdriver/lxc/init.go <ide> import ( <ide> "encoding/json" <ide> "flag" <ide> "fmt" <del> "log" <ide> "os" <ide> "os/exec" <ide> "runtime" <ide> "strings" <ide> "syscall" <ide> <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/reexec" <ide> ) <ide> <ide> func initializer() { <ide> args := getArgs() <ide> <ide> if err := setupNamespace(args); err != nil { <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> } <ide> <ide> func setupNamespace(args *InitArgs) error { <ide> <ide> path, err := exec.LookPath(args.Args[0]) <ide> if err != nil { <del> log.Printf("Unable to locate %v", args.Args[0]) <add> logrus.Infof("Unable to locate %v", args.Args[0]) <ide> os.Exit(127) <ide> } <ide> <ide><path>graph/list.go <ide> package graph <ide> <ide> import ( <ide> "fmt" <del> "log" <ide> "path" <ide> "sort" <ide> "strings" <ide> <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/parsers/filters" <ide> func (s *TagStore) Images(config *ImagesConfig) ([]*types.Image, error) { <ide> imgRef := utils.ImageReference(repoName, ref) <ide> image, err := s.graph.Get(id) <ide> if err != nil { <del> log.Printf("Warning: couldn't load %s from %s: %s", id, imgRef, err) <add> logrus.Warnf("couldn't load %s from %s: %s", id, imgRef, err) <ide> continue <ide> } <ide>
2
Ruby
Ruby
use sass-rails 4.0.3
61a8fd5e1b23fc0a0630cd1831abdda0bedd1c73
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def assets_gemfile_entry <ide> 'Use SCSS for stylesheets') <ide> else <ide> gems << GemfileEntry.version('sass-rails', <del> '~> 4.0.2', <add> '~> 4.0.3', <ide> 'Use SCSS for stylesheets') <ide> end <ide>
1
Java
Java
fix typo in test from previous commit
acb3d1cf888125d7663628e766a42adaee8e78df
<ide><path>spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java <ide> public void compareTests() { <ide> @Test <ide> public void separatorTests() { <ide> PathPatternParser parser = new PathPatternParser(); <del> parser.setPathOptions(PathContainer.Options.HTTP_PATH); <add> parser.setPathOptions(PathContainer.Options.create('.', false)); <ide> String rawPattern = "first.second.{last}"; <ide> PathPattern pattern = parser.parse(rawPattern); <ide> assertThat(pattern.computePatternString()).isEqualTo(rawPattern);
1
Javascript
Javascript
add git revision to build version
9a0cf68a4d609a571d8840fada2e2e2d85a426bf
<ide><path>shells/browser/shared/build.js <ide> const build = async (tempPath, manifestPath) => { <ide> `${webpackPath} --config webpack.config.js --output-path ${binPath}`, <ide> { <ide> cwd: __dirname, <del> env: Object.assign({}, process.env, { NODE_ENV: 'production' }), <add> env: Object.assign({}, process.env, { <add> NODE_ENV: 'production', <add> }), <ide> stdio: 'inherit', <ide> } <ide> ); <ide> execSync( <ide> `${webpackPath} --config webpack.backend.js --output-path ${binPath}`, <ide> { <ide> cwd: __dirname, <del> env: Object.assign({}, process.env, { NODE_ENV: 'production' }), <add> env: Object.assign({}, process.env, { <add> NODE_ENV: 'production', <add> }), <ide> stdio: 'inherit', <ide> } <ide> ); <ide><path>shells/browser/shared/webpack.backend.js <del>const { execSync } = require('child_process'); <ide> const { readFileSync } = require('fs'); <ide> const { resolve } = require('path'); <ide> const { DefinePlugin } = require('webpack'); <add>const { getGitHubURL, getVersionString } = require('../../utils'); <ide> <ide> const __DEV__ = process.env.NODE_ENV !== 'production'; <ide> <del>// TODO potentially replac this with an fb.me URL (if it can forward the query params) <del>const GITHUB_URL = execSync('git remote get-url origin') <del> .toString() <del> .trim() <del> .replace(':', '/') <del> .replace('git@', 'https://') <del> .replace('.git', ''); <del> <del>const DEVTOOLS_VERSION = JSON.parse( <del> readFileSync(resolve(__dirname, '../../../package.json')) <del>).version; <add>const GITHUB_URL = getGitHubURL(); <add>const DEVTOOLS_VERSION = getVersionString(); <ide> <ide> module.exports = { <ide> mode: __DEV__ ? 'development' : 'production', <ide><path>shells/browser/shared/webpack.config.js <del>const { execSync } = require('child_process'); <ide> const { readFileSync } = require('fs'); <ide> const { resolve } = require('path'); <ide> const { DefinePlugin } = require('webpack'); <add>const { getGitHubURL, getVersionString } = require('../../utils'); <ide> <ide> const NODE_ENV = process.env.NODE_ENV; <ide> const __DEV__ = NODE_ENV !== 'production'; <ide> <del>// TODO potentially replac this with an fb.me URL (if it can forward the query params) <del>const GITHUB_URL = execSync('git remote get-url origin') <del> .toString() <del> .trim() <del> .replace(':', '/') <del> .replace('git@', 'https://') <del> .replace('.git', ''); <del> <del>const DEVTOOLS_VERSION = JSON.parse( <del> readFileSync(resolve(__dirname, '../../../package.json')) <del>).version; <add>const GITHUB_URL = getGitHubURL(); <add>const DEVTOOLS_VERSION = getVersionString(); <ide> <ide> module.exports = { <ide> mode: __DEV__ ? 'development' : 'production', <ide><path>shells/dev/webpack.config.js <del>const { execSync } = require('child_process'); <ide> const { readFileSync } = require('fs'); <ide> const { resolve } = require('path'); <ide> const { DefinePlugin } = require('webpack'); <add>const { getGitHubURL, getVersionString } = require('../utils'); <ide> <ide> const __DEV__ = process.env.NODE_ENV !== 'production'; <ide> <del>// TODO potentially replac this with an fb.me URL (if it can forward the query params) <del>const GITHUB_URL = execSync('git remote get-url origin') <del> .toString() <del> .trim() <del> .replace(':', '/') <del> .replace('git@', 'https://') <del> .replace('.git', ''); <del> <del>const DEVTOOLS_VERSION = JSON.parse( <del> readFileSync(resolve(__dirname, '../../package.json')) <del>).version; <del> <del>// TODO Share Webpack configs like alias <add>const GITHUB_URL = getGitHubURL(); <add>const DEVTOOLS_VERSION = getVersionString(); <ide> <ide> module.exports = { <ide> mode: 'development', <ide><path>shells/utils.js <add>const { execSync } = require('child_process'); <add>const { readFileSync } = require('fs'); <add>const { resolve } = require('path'); <add> <add>function getGitHubURL() { <add> // TODO potentially replac this with an fb.me URL (if it can forward the query params) <add> return execSync('git remote get-url origin') <add> .toString() <add> .trim() <add> .replace(':', '/') <add> .replace('git@', 'https://') <add> .replace('.git', ''); <add>} <add> <add>function getVersionString() { <add> const packageVersion = JSON.parse( <add> readFileSync(resolve(__dirname, '../package.json')) <add> ).version; <add> <add> const commit = execSync('git show -s --format=%h') <add> .toString() <add> .trim(); <add> <add> return `${packageVersion}-${commit}`; <add>} <add> <add>module.exports = { getGitHubURL, getVersionString };
5
Javascript
Javascript
add example for overwriting defaults on provider
6d3329479fae215c5f2fc7df77f9fee893c387bf
<ide><path>src/ngCookies/cookies.js <ide> angular.module('ngCookies', ['ng']). <ide> * Note: By default, the address that appears in your `<base>` tag will be used as the path. <ide> * This is important so that cookies will be visible for all routes when html5mode is enabled. <ide> * <add> * @example <add> * <add> * ```js <add> * angular.module('cookiesProviderExample', ['ngCookies']) <add> * .config(['$cookiesProvider', function($cookiesProvider) { <add> * // Setting default options <add> * $cookiesProvider.defaults.domain = 'foo.com'; <add> * $cookiesProvider.defaults.secure = true; <add> * }]); <add> * ``` <ide> **/ <ide> var defaults = this.defaults = {}; <ide>
1
Python
Python
fix small bug/typo
364920e216c16d73c782a61a4cf6652e541fbe18
<ide><path>examples/distillation/dataset.py <ide> def divide_chunks(l, n): <ide> if sub_s[0] != cls_id: <ide> sub_s = np.insert(sub_s, 0, cls_id) <ide> if sub_s[-1] != sep_id: <del> sub_s = np.insert(sub_s, len(sub_s), cls_id) <add> sub_s = np.insert(sub_s, len(sub_s), sep_id) <ide> assert len(sub_s) <= max_len <ide> sub_seqs.append(sub_s) <ide>
1
Text
Text
fix path to old run_language_modeling.py script
b1d3e95eb5d3e980b9d97f7b98280bab1153cc1b
<ide><path>examples/language-modeling/README.md <ide> These scripts leverage the 🤗 Datasets library and the Trainer API. You can ea <ide> need extra processing on your datasets. <ide> <ide> **Note:** The old script `run_language_modeling.py` is still available <del>[here](https://github.com/huggingface/transformers/blob/master/examples/contrib/legacy/language-modeling/run_language_modeling.py). <add>[here](https://github.com/huggingface/transformers/blob/master/examples/contrib/legacy/run_language_modeling.py). <ide> <ide> The following examples, will run on a datasets hosted on our [hub](https://huggingface.co/datasets) or with your own <ide> text files for training and validation. We give examples of both below.
1
Text
Text
add postmates to airflow users list
ce362c312ccb1bace7215d156909f42d7e51898a
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> * [Lucid](http://luc.id) [[@jbrownlucid](https://github.com/jbrownlucid) & [@kkourtchikov](https://github.com/kkourtchikov)] <ide> * [Lyft](https://www.lyft.com/)[[@SaurabhBajaj](https://github.com/SaurabhBajaj)] <ide> * [Nerdwallet](https://www.nerdwallet.com) <add>* [Postmates](http://www.postmates.com) [[@syeoryn](https://github.com/syeoryn)] <ide> * [Qubole](https://qubole.com) [[@msumit](https://github.com/msumit)] <ide> * [Sense360](https://github.com/Sense360) [[@kamilmroczek](https://github.com/KamilMroczek)] <ide> * [Sidecar](https://hello.getsidecar.com/) [[@getsidecar](https://github.com/getsidecar)]
1
Go
Go
undo 908db518 for windows daemon
d66ae6741851e587e881b31e4b72bbccc253e958
<ide><path>pkg/chrootarchive/archive.go <ide> func untar() { <ide> <ide> var options *archive.TarOptions <ide> <del> //read the options from the pipe "ExtraFiles" <del> if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil { <del> fatal(err) <add> if runtime.GOOS != "windows" { <add> //read the options from the pipe "ExtraFiles" <add> if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil { <add> fatal(err) <add> } <add> } else { <add> if err := json.Unmarshal([]byte(os.Getenv("OPT")), &options); err != nil { <add> fatal(err) <add> } <ide> } <ide> <ide> if err := chroot(flag.Arg(0)); err != nil { <ide> func Untar(tarArchive io.Reader, dest string, options *archive.TarOptions) error <ide> if err != nil { <ide> return err <ide> } <add> <add> var data []byte <add> var r, w *os.File <ide> defer decompressedArchive.Close() <ide> <del> // We can't pass a potentially large exclude list directly via cmd line <del> // because we easily overrun the kernel's max argument/environment size <del> // when the full image list is passed (e.g. when this is used by <del> // `docker load`). We will marshall the options via a pipe to the <del> // child <del> r, w, err := os.Pipe() <del> if err != nil { <del> return fmt.Errorf("Untar pipe failure: %v", err) <add> if runtime.GOOS != "windows" { <add> // We can't pass a potentially large exclude list directly via cmd line <add> // because we easily overrun the kernel's max argument/environment size <add> // when the full image list is passed (e.g. when this is used by <add> // `docker load`). We will marshall the options via a pipe to the <add> // child <add> <add> // This solution won't work on Windows as it will fail in golang <add> // exec_windows.go as at the lowest layer because attr.Files > 3 <add> r, w, err = os.Pipe() <add> if err != nil { <add> return fmt.Errorf("Untar pipe failure: %v", err) <add> } <add> } else { <add> // We can't pass the exclude list directly via cmd line <add> // because we easily overrun the shell max argument list length <add> // when the full image list is passed (e.g. when this is used <add> // by `docker load`). Instead we will add the JSON marshalled <add> // and placed in the env, which has significantly larger <add> // max size <add> data, err = json.Marshal(options) <add> if err != nil { <add> return fmt.Errorf("Untar json encode: %v", err) <add> } <ide> } <add> <ide> cmd := reexec.Command("docker-untar", dest) <ide> cmd.Stdin = decompressedArchive <del> cmd.ExtraFiles = append(cmd.ExtraFiles, r) <del> output := bytes.NewBuffer(nil) <del> cmd.Stdout = output <del> cmd.Stderr = output <ide> <del> if err := cmd.Start(); err != nil { <del> return fmt.Errorf("Untar error on re-exec cmd: %v", err) <del> } <del> //write the options to the pipe for the untar exec to read <del> if err := json.NewEncoder(w).Encode(options); err != nil { <del> return fmt.Errorf("Untar json encode to pipe failed: %v", err) <del> } <del> w.Close() <add> if runtime.GOOS != "windows" { <add> cmd.ExtraFiles = append(cmd.ExtraFiles, r) <add> output := bytes.NewBuffer(nil) <add> cmd.Stdout = output <add> cmd.Stderr = output <add> <add> if err := cmd.Start(); err != nil { <add> return fmt.Errorf("Untar error on re-exec cmd: %v", err) <add> } <add> //write the options to the pipe for the untar exec to read <add> if err := json.NewEncoder(w).Encode(options); err != nil { <add> return fmt.Errorf("Untar json encode to pipe failed: %v", err) <add> } <add> w.Close() <ide> <del> if err := cmd.Wait(); err != nil { <del> return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output) <add> if err := cmd.Wait(); err != nil { <add> return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output) <add> } <add> return nil <add> } else { <add> cmd.Env = append(cmd.Env, fmt.Sprintf("OPT=%s", data)) <add> out, err := cmd.CombinedOutput() <add> if err != nil { <add> return fmt.Errorf("Untar %s %s", err, out) <add> } <add> return nil <ide> } <del> return nil <add> <ide> } <ide> <ide> func TarUntar(src, dst string) error {
1
Ruby
Ruby
switch regex for delete_suffix in normalize_path
4fb78a0b87b00f6efab4519bd5f744c100c2c76d
<ide><path>actionpack/lib/action_dispatch/journey/router/utils.rb <ide> def self.normalize_path(path) <ide> encoding = path.encoding <ide> path = +"/#{path}" <ide> path.squeeze!("/") <del> path.sub!(%r{/+\Z}, "") <del> path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase } <del> path = +"/" if path == "" <add> <add> unless path == "/" <add> path.delete_suffix!("/") <add> path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase } <add> end <add> <ide> path.force_encoding(encoding) <del> path <ide> end <ide> <ide> # URI path and fragment escaping
1
Javascript
Javascript
improve pointerevents doc
f1a0695c7d1d1199558a53fbd943c0b18188a444
<ide><path>Libraries/Components/View/View.js <ide> const View = React.createClass({ <ide> onLayout: PropTypes.func, <ide> <ide> /** <del> * In the absence of `auto` property, `none` is much like `CSS`'s `none` <del> * value. `box-none` is as if you had applied the `CSS` class: <add> * Controls whether the View can be the target of touch events. <ide> * <add> * - 'auto': The View can be the target of touch events. <add> * - 'none': The View is never the target of touch events. <add> * - 'box-none': The View is never the target of touch events but it's <add> * subviews can be. It behaves like if the following classes <add> * in CSS: <ide> * ``` <ide> * .box-none { <del> * pointer-events: none; <add> * pointer-events: none; <ide> * } <ide> * .box-none * { <del> * pointer-events: all; <add> * pointer-events: all; <ide> * } <ide> * ``` <del> * <del> * `box-only` is the equivalent of <del> * <add> * - 'box-only': The view can be the target of touch events but it's <add> * subviews cannot be. It behaves like if the following classes <add> * in CSS: <ide> * ``` <ide> * .box-only { <del> * pointer-events: all; <add> * pointer-events: all; <ide> * } <ide> * .box-only * { <del> * pointer-events: none; <add> * pointer-events: none; <ide> * } <ide> * ``` <del> * <del> * But since `pointerEvents` does not affect layout/appearance, and we are <del> * already deviating from the spec by adding additional modes, we opt to not <del> * include `pointerEvents` on `style`. On some platforms, we would need to <del> * implement it as a `className` anyways. Using `style` or not is an <del> * implementation detail of the platform. <ide> */ <add> // Since `pointerEvents` does not affect layout/appearance, and we are <add> // already deviating from the spec by adding additional modes, we opt to not <add> // include `pointerEvents` on `style`. On some platforms, we would need to <add> // implement it as a `className` anyways. Using `style` or not is an <add> // implementation detail of the platform. <ide> pointerEvents: PropTypes.oneOf([ <ide> 'box-none', <ide> 'none',
1
Text
Text
fix a markdown error in ctc meeting minutes
4c86fa30d83aa06780825c579cbb2b732ffe4f49
<ide><path>doc/ctc-meetings/2016-07-13.md <ide> ELOOP issue has been resolved. Windows problem being addressed in another PR. Ma <ide> <ide> ### http: don't inherit from Object.prototype [#6102](https://github.com/nodejs/node/pull/6102) <ide> <del>@mscdex: Prevent clash of header names with properties inherited from Object (e.g., __proto__). An object with a null prototype is already being used for the same purpose in `querystring.parse` since v6 release. <add>@mscdex: Prevent clash of header names with properties inherited from Object (e.g., `__proto__`). An object with a null prototype is already being used for the same purpose in `querystring.parse` since v6 release. <ide> <ide> @mscdex: Some have suggested cherry-picking some methods from Object such as `toString`: <ide>
1
Python
Python
require downloaded model in pkg_resources
6bec24cdd09c8168d2ce8667e376bb1f0e320c07
<ide><path>spacy/cli/download.py <ide> import os <ide> import subprocess <ide> import sys <add>import pkg_resources <ide> from wasabi import Printer <ide> <ide> from .link import link <ide> def download(model, direct=False, *pip_args): <ide> "the model via its full package name: " <ide> "nlp = spacy.load('{}')".format(model, model_name), <ide> ) <add> # If a model is downloaded and then loaded within the same process, our <add> # is_package check currently fails, because pkg_resources.working_set <add> # is not refreshed automatically (see #3923). We're trying to work <add> # around this here be requiring the package explicitly. <add> try: <add> pkg_resources.working_set.require(model_name) <add> except: # noqa: E722 <add> # Maybe it's possible to remove this – mostly worried about cross- <add> # platform and cross-Python copmpatibility here <add> pass <ide> <ide> <ide> def get_json(url, desc):
1
Javascript
Javascript
add async to observable methods
c2ca5e80e969f4e04a2f6044a3b87cd171cec7a2
<ide><path>packages/@ember/-internals/runtime/lib/mixins/observable.js <ide> export default Mixin.create({ <ide> observer should be prepared to handle that. <ide> <ide> There are two common invocation patterns for `.addObserver()`: <del> <add> <ide> - Passing two arguments: <ide> - the name of the property to observe (as a string) <ide> - the function to invoke (an actual function) <ide> export default Mixin.create({ <ide> @param {String} key The key to observe <ide> @param {Object} target The target object to invoke <ide> @param {String|Function} method The method to invoke <add> @param {Boolean} async Whether the observer is async or not <ide> @return {Observable} <ide> @public <ide> */ <del> addObserver(key, target, method) { <del> addObserver(this, key, target, method); <add> addObserver(key, target, method, async) { <add> addObserver(this, key, target, method, async); <ide> return this; <ide> }, <ide> <ide> export default Mixin.create({ <ide> @param {String} key The key to observe <ide> @param {Object} target The target object to invoke <ide> @param {String|Function} method The method to invoke <add> @param {Boolean} async Whether the observer is async or not <ide> @return {Observable} <ide> @public <ide> */ <del> removeObserver(key, target, method) { <del> removeObserver(this, key, target, method); <add> removeObserver(key, target, method, async) { <add> removeObserver(this, key, target, method, async); <ide> return this; <ide> }, <ide>
1
Javascript
Javascript
return non-zero exit code from wrong-react-native
ec762717153bbe434e4b8188898f35e3491c88ed
<ide><path>local-cli/wrong-react-native.js <ide> console.error([ <ide> 'npm uninstall -g react-native', <ide> 'npm install -g react-native-cli' <ide> ].join('\n')); <add> <add>process.exit(1);
1
Java
Java
improve importstack#tostring output
40798bd48f63a8f0d9c6529ca6aaa7203b95cbc3
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java <ide> private void processImport(ConfigurationClass configClass, String[] classesToImp <ide> // the candidate class is an ImportSelector -> delegate to it to determine imports <ide> try { <ide> ImportSelector selector = BeanUtils.instantiateClass(Class.forName(candidate), ImportSelector.class); <del> ImportSelectorContext context = new ImportSelectorContext(importingClassMetadata, this.registry); <del> processImport(configClass, selector.selectImports(context), false); <add> processImport(configClass, selector.selectImports(importingClassMetadata), false); <add> } catch (ClassNotFoundException ex) { <add> throw new IllegalStateException(ex); <add> } <add> } <add> else if (new AssignableTypeFilter(ImportBeanDefinitionRegistrar.class).match(reader, metadataReaderFactory)) { <add> // the candidate class is an ImportBeanDefinitionRegistrar -> delegate to it to register additional bean definitions <add> try { <add> ImportBeanDefinitionRegistrar registrar = BeanUtils.instantiateClass(Class.forName(candidate), ImportBeanDefinitionRegistrar.class); <add> registrar.registerBeanDefinitions(importingClassMetadata, registry); <ide> } catch (ClassNotFoundException ex) { <ide> throw new IllegalStateException(ex); <ide> } <ide> } <ide> else { <del> // the candidate class not an ImportSelector -> process it as a @Configuration class <add> // the candidate class not an ImportSelector or ImportBeanDefinitionRegistrar -> process it as a @Configuration class <ide> this.importStack.registerImport(importingClassMetadata.getClassName(), candidate); <ide> processConfigurationClass(new ConfigurationClass(reader, null)); <ide> } <ide> public int compare(ConfigurationClass first, ConfigurationClass second) { <ide> <ide> /** <ide> * Given a stack containing (in order) <del> * <ol> <add> * <ul> <ide> * <li>com.acme.Foo</li> <ide> * <li>com.acme.Bar</li> <ide> * <li>com.acme.Baz</li> <del> * </ol> <del> * Returns "Foo->Bar->Baz". In the case of an empty stack, returns empty string. <add> * </ul> <add> * return "ImportStack: [Foo->Bar->Baz]". <ide> */ <ide> @Override <ide> public String toString() { <del> StringBuilder builder = new StringBuilder(); <add> StringBuilder builder = new StringBuilder("ImportStack: ["); <ide> Iterator<ConfigurationClass> iterator = iterator(); <ide> while (iterator.hasNext()) { <ide> builder.append(iterator.next().getSimpleName()); <ide> if (iterator.hasNext()) { <ide> builder.append("->"); <ide> } <ide> } <del> return builder.toString(); <add> return builder.append(']').toString(); <ide> } <ide> } <ide>
1
Text
Text
change csharp nullable-types spanish guide
129cb6d509142d46d8d07ff42f8a8db294aef3d4
<ide><path>guide/spanish/csharp/nullable-types/index.md <ide> --- <ide> title: Nullable Types <del>localeTitle: Tipos anulables <add>localeTitle: Tipos que aceptan valores NULL <ide> --- <del>## Tipos anulables <add>## Tipos que aceptan valores NULL <ide> <del>Los tipos anulables son instancias de [System.Nullable \\](https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1) estructura Un tipo anulable puede representar el rango correcto de valores para su tipo de valor subyacente, más un valor `null` adicional. Esta capacidad es muy útil cuando se trata de bases de datos u otros tipos de datos que pueden contener elementos sin valor asignado. <add>Los tipos que aceptan valores NULL son instancias de la estructura [System.Nullable\<T\>](https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1). Pueden representar el rango de valores para su tipo de valor subyacente, más un valor `null`. Esta capacidad es muy útil cuando se trata de bases de datos u otros tipos de datos que pueden contener elementos sin valor asignado. <ide> <ide> #### Cómo utilizar el tipo nullable <ide> <ide> ```csharp <del>// Declare a variable of Nullable type (Nullable<int>) <add> // Declaración de una variable que acepta valores NULL (Nullable<int>) <ide> int? i = null; <ide> <ide> int j = 0; <del> int defaultValue = 0; <add> int valorPorDefecto = 0; <ide> <del> // test for null and assign value to another variable <add> // pruebo si es NULL y asigno el valor a otra variable <ide> if (i.HasValue) <ide> { <ide> j = i.Value; <ide> } <ide> <del> // get assigned value or default when current value is null <del> j = i.GetValueOrDefault(); // i.GetValueOrDefault(defaultValue) <add> // obtengo el valor asinado o el valor default cuando el valor es NULL <add> j = i.GetValueOrDefault(); // i.GetValueOrDefault(valorPorDefecto) <ide> <del> //use coalescing operator to assign default value when current value is null <del> j = i ?? defaultValue; <add> // uso el operador coalescente para asignar el valor por defecto cuando el valor actual es NULL <add> j = i ?? valorPorDefecto; <ide> ``` <ide> <del>Para más información, visite el siguiente enlace: <add>Para más información, visite los siguientes enlaces: <ide> <del>* [Guía de programación de C #: tipos anulables](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/) <ide>\ No newline at end of file <add>* [Guía de programación de C#: tipos que aceptan valores null](https://docs.microsoft.com/es-es/dotnet/csharp/programming-guide/nullable-types/using-nullable-types) <add>* [Tipos que aceptan valores null](https://docs.microsoft.com/es-es/dotnet/csharp/programming-guide/nullable-types/index)
1
Ruby
Ruby
fix the method signature
15ff4264b23a6f381c211529ca5da21913e20f6f
<ide><path>activerecord/lib/active_record/statement_cache.rb <ide> def sql_for(binds, connection) <ide> end <ide> end <ide> <del> def self.query(connection, visitor, ast) <add> def self.query(visitor, ast) <ide> Query.new visitor.accept(ast) <ide> end <ide>
1
Ruby
Ruby
add ldflags if disabling weak imports
53d1000739bc29913ab956cff2748428b66f969d
<ide><path>Library/Homebrew/extend/os/mac/extend/ENV/std.rb <ide> def setup_build_environment(formula = nil) <ide> # depend on it already being installed to build itself. <ide> ld64 if Formula["ld64"].installed? <ide> end <add> <add> # Xcode 8 should be told to fail to link against weak links <add> # Issue from Apple engineer: <add> # https://github.com/Homebrew/homebrew-core/issues/3727 <add> append "LDFLAGS", "-Wl,-no_weak_imports" if no_weak_imports? <ide> end <ide> <ide> def homebrew_extra_pkg_config_paths
1
Ruby
Ruby
remove unnecessary comma
acab767c9d042031320b1ed7a7e2faa653ab1bb9
<ide><path>activerecord/lib/active_record/counter_cache.rb <ide> def reset_counters(id, *counters) <ide> # Post.update_counters [10, 15], :comment_count => 1 <ide> # # Executes the following SQL: <ide> # # UPDATE posts <del> # # SET comment_count = COALESCE(comment_count, 0) + 1, <add> # # SET comment_count = COALESCE(comment_count, 0) + 1 <ide> # # WHERE id IN (10, 15) <ide> def update_counters(id, counters) <ide> updates = counters.map do |counter_name, value|
1
Javascript
Javascript
remove unreachable return
b4e670dc26b50271457a257ccb244b14ff323b64
<ide><path>benchmark/_cli.js <ide> function CLI(usage, settings) { <ide> } else { <ide> // Bad case, abort <ide> this.abort(usage); <del> return; <ide> } <ide> } <ide> } <ide><path>benchmark/common.js <ide> Benchmark.prototype._run = function() { <ide> child.on('close', (code) => { <ide> if (code) { <ide> process.exit(code); <del> return; <ide> } <ide> <ide> if (queueIndex + 1 < self.queue.length) { <ide><path>benchmark/compare.js <ide> const cli = CLI(`usage: ./node compare.js [options] [--] <category> ... <ide> <ide> if (!cli.optional.new || !cli.optional.old) { <ide> cli.abort(cli.usage); <del> return; <ide> } <ide> <ide> const binaries = ['old', 'new']; <ide> if (showProgress) { <ide> child.once('close', (code) => { <ide> if (code) { <ide> process.exit(code); <del> return; <ide> } <ide> if (showProgress) { <ide> progress.completeRun(job); <ide><path>benchmark/run.js <ide> if (format === 'csv') { <ide> child.once('close', (code) => { <ide> if (code) { <ide> process.exit(code); <del> return; <ide> } <ide> <ide> // If there are more benchmarks execute the next <ide><path>benchmark/scatter.js <ide> const cli = CLI(`usage: ./node scatter.js [options] [--] <filename> <ide> <ide> if (cli.items.length !== 1) { <ide> cli.abort(cli.usage); <del> return; <ide> } <ide> <ide> // Create queue from the benchmarks list such both node versions are tested
5
PHP
PHP
improve query builder implode method
13cf97954b639572d167393e4531910aa0bf5c97
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> protected function getListSelect($column, $key) <ide> * @param string $glue <ide> * @return string <ide> */ <del> public function implode($column, $glue = null) <add> public function implode($column, $glue = '') <ide> { <del> if (is_null($glue)) { <del> return implode($this->lists($column)); <del> } <del> <ide> return implode($glue, $this->lists($column)); <ide> } <ide>
1
Javascript
Javascript
pass changed file into `invalid` plugin hook
466d20890cc000b8ccc4176dcb28fbe8043447fa
<ide><path>lib/Compiler.js <ide> Watching.prototype.watch = function(files, dirs, missing) { <ide> this.compiler.fileTimestamps = fileTimestamps; <ide> this.compiler.contextTimestamps = contextTimestamps; <ide> this.invalidate(); <del> }.bind(this), function() { <del> this.compiler.applyPlugins("invalid"); <add> }.bind(this), function(fileName, changeTime) { <add> this.compiler.applyPlugins("invalid", fileName, changeTime); <ide> }.bind(this)); <ide> }; <ide>
1
Javascript
Javascript
fix extend_prototypes for sproutcore-runtime
1fa9fa630fc31a7310fd838c2ee51ac940464a9d
<ide><path>packages/sproutcore-handlebars/tests/each_test.js <ide> var people, view; <ide> module("the #each helper", { <ide> setup: function() { <ide> template = templateFor("{{#each people}}{{name}}{{/each}}"); <del> people = SC.Array.apply([{ name: "Steve Holt" }, { name: "Annabelle" }]); <add> people = SC.NativeArray.apply([{ name: "Steve Holt" }, { name: "Annabelle" }]); <ide> <ide> view = SC.View.create({ <ide> template: template, <ide><path>packages/sproutcore-runtime/tests/controllers/array_controller_test.js <ide> SC.MutableArrayTests.extend({ <ide> newObject: function(ary) { <ide> var ret = ary ? ary.slice() : this.newFixture(3); <ide> return SC.ArrayController.create({ <del> content: ret <add> content: SC.NativeArray.apply(ret) <ide> }); <ide> }, <ide> <ide><path>packages/sproutcore-runtime/tests/legacy_1x/mixins/observable/chained_test.js <ide> test("chained observers on enumerable properties are triggered when the observed <ide> var child4 = SC.Object.create({ name: "Nancy" }); <ide> <ide> set(family, 'momma', momma); <del> set(momma, 'children', [child1, child2, child3]); <add> set(momma, 'children', SC.NativeArray.apply([child1, child2, child3])); <ide> <ide> var observerFiredCount = 0; <ide> SC.addObserver(family, 'momma.children.@each.name', this, function() { <ide><path>packages/sproutcore-runtime/tests/legacy_1x/mixins/observable/observable_test.js <ide> module("Computed properties", { <ide> test("getting values should call function return value", function() { <ide> <ide> // get each property twice. Verify return. <del> var keys = 'computed computedCached dependent dependentCached'.w(); <add> var keys = SC.String.w('computed computedCached dependent dependentCached'); <ide> <ide> keys.forEach(function(key) { <del> equals(object.get(key), key, 'Try #1: object.get(%@) should run function'.fmt(key)); <del> equals(object.get(key), key, 'Try #2: object.get(%@) should run function'.fmt(key)); <add> equals(object.get(key), key, SC.String.fmt('Try #1: object.get(%@) should run function', key)); <add> equals(object.get(key), key, SC.String.fmt('Try #2: object.get(%@) should run function', key)); <ide> }); <ide> <ide> // verify each call count. cached should only be called once <del> 'computedCalls dependentCalls'.w().forEach(function(key) { <del> equals(object[key].length, 2, 'non-cached property %@ should be called 2x'.fmt(key)); <add> SC.String.w('computedCalls dependentCalls').forEach(function(key) { <add> equals(object[key].length, 2, SC.String.fmt('non-cached property %@ should be called 2x', key)); <ide> }); <ide> <del> 'computedCachedCalls dependentCachedCalls'.w().forEach(function(key) { <del> equals(object[key].length, 1, 'non-cached property %@ should be called 1x'.fmt(key)); <add> SC.String.w('computedCachedCalls dependentCachedCalls').forEach(function(key) { <add> equals(object[key].length, 1, SC.String.fmt('non-cached property %@ should be called 1x', key)); <ide> }); <ide> <ide> }); <ide> <ide> test("setting values should call function return value", function() { <ide> <ide> // get each property twice. Verify return. <del> var keys = 'computed dependent computedCached dependentCached'.w(); <del> var values = 'value1 value2'.w(); <add> var keys = SC.String.w('computed dependent computedCached dependentCached'); <add> var values = SC.String.w('value1 value2'); <ide> <ide> keys.forEach(function(key) { <ide> <del> equals(object.set(key, values[0]), object, 'Try #1: object.set(%@, %@) should run function'.fmt(key, values[0])); <add> equals(object.set(key, values[0]), object, SC.String.fmt('Try #1: object.set(%@, %@) should run function', key, values[0])); <ide> <del> equals(object.set(key, values[1]), object, 'Try #2: object.set(%@, %@) should run function'.fmt(key, values[1])); <add> equals(object.set(key, values[1]), object, SC.String.fmt('Try #2: object.set(%@, %@) should run function', key, values[1])); <ide> <del> equals(object.set(key, values[1]), object, 'Try #3: object.set(%@, %@) should not run function since it is setting same value as before'.fmt(key, values[1])); <add> equals(object.set(key, values[1]), object, SC.String.fmt('Try #3: object.set(%@, %@) should not run function since it is setting same value as before', key, values[1])); <ide> <ide> }); <ide> <ide> test("setting values should call function return value", function() { <ide> // Cached properties first check their cached value before setting the <ide> // property. Other properties blindly call set. <ide> expectedLength = 3; <del> equals(calls.length, expectedLength, 'set(%@) should be called the right amount of times'.fmt(key)); <add> equals(calls.length, expectedLength, SC.String.fmt('set(%@) should be called the right amount of times', key)); <ide> for(idx=0;idx<2;idx++) { <del> equals(calls[idx], values[idx], 'call #%@ to set(%@) should have passed value %@'.fmt(idx+1, key, values[idx])); <add> equals(calls[idx], values[idx], SC.String.fmt('call #%@ to set(%@) should have passed value %@', idx+1, key, values[idx])); <ide> } <ide> }); <ide> <ide> module("Observable objects & object properties ", { <ide> toggleVal: true, <ide> observedProperty: 'beingWatched', <ide> testRemove: 'observerToBeRemoved', <del> normalArray: [1,2,3,4,5], <add> normalArray: SC.NativeArray.apply([1,2,3,4,5]), <ide> <ide> getEach: function() { <ide> var keys = ['normal','abnormal']; <ide><path>packages/sproutcore-runtime/tests/legacy_1x/mixins/observable/observersForKey_test.js <ide> test("should get observers", function() { <ide> o3 = ObservableObject.create({ func: function() {} }), <ide> observers = null; <ide> <del> equals(o1.observersForKey('foo').get('length'), 0, "o1.observersForKey should return empty array"); <add> equals(SC.get(o1.observersForKey('foo'), 'length'), 0, "o1.observersForKey should return empty array"); <ide> <ide> o1.addObserver('foo', o2, o2.func); <ide> o1.addObserver('foo', o3, o3.func); <ide> <ide> observers = o1.observersForKey('foo'); <ide> <del> equals(observers.get('length'), 2, "o2.observersForKey should return an array with length 2"); <add> equals(SC.get(observers, 'length'), 2, "o2.observersForKey should return an array with length 2"); <ide> equals(observers[0][0], o2, "first item in observers array should be o2"); <ide> equals(observers[1][0], o3, "second item in observers array should be o3"); <ide> }); <ide><path>packages/sproutcore-runtime/tests/legacy_1x/system/binding_test.js <ide> test("toObject.value should be second value if first is falsy", function() { <ide> <ide> module("Binding with '[]'", { <ide> setup: function() { <del> fromObject = SC.Object.create({ value: [] }); <add> fromObject = SC.Object.create({ value: SC.NativeArray.apply([]) }); <ide> toObject = SC.Object.create({ value: '' }); <ide> root = { toObject: toObject, fromObject: fromObject }; <ide> <ide><path>packages/sproutcore-runtime/tests/legacy_1x/system/object/base_test.js <ide> test("Checking the detectInstance() function on an object and its subclass", fun <ide> }); <ide> <ide> test("subclasses should contain defined subclasses", function() { <del> ok(obj.subclasses.contains(obj1), 'obj.subclasses should contain obj1'); <add> ok(jQuery.inArray(obj1, obj.subclasses) > -1, 'obj.subclasses should contain obj1'); <ide> <ide> equals(get(obj1.subclasses, 'length'),0,'obj1.subclasses should be empty'); <ide> <ide> var kls2 = obj1.extend(); <del> ok(obj1.subclasses.contains(kls2), 'obj1.subclasses should contain kls2'); <add> ok(jQuery.inArray(kls2, obj1.subclasses) > -1, 'obj1.subclasses should contain kls2'); <ide> }); <ide><path>packages/sproutcore-runtime/tests/legacy_1x/system/object/concatenated_test.js <ide> <ide> var values = get(obj, 'values'), <ide> expected = ['a', 'b', 'c', 'd', 'e', 'f']; <del> same(values, expected, "should concatenate values property (expected: %@, got: %@)".fmt(expected, values)); <add> same(values, expected, SC.String.fmt("should concatenate values property (expected: %@, got: %@)", expected, values)); <ide> }); <ide> <ide> test("concatenates subclasses", function() { <ide> <ide> var values = get(obj, 'values'), <ide> expected = ['a', 'b', 'c', 'd', 'e', 'f']; <del> same(values, expected, "should concatenate values property (expected: %@, got: %@)".fmt(expected, values)); <add> same(values, expected, SC.String.fmt("should concatenate values property (expected: %@, got: %@)", expected, values)); <ide> }); <ide> <ide> test("concatenates reopen", function() { <ide> <ide> var values = get(obj, 'values'), <ide> expected = ['a', 'b', 'c', 'd', 'e', 'f']; <del> same(values, expected, "should concatenate values property (expected: %@, got: %@)".fmt(expected, values)); <add> same(values, expected, SC.String.fmt("should concatenate values property (expected: %@, got: %@)", expected, values)); <ide> }); <ide> <ide> test("concatenates mixin", function() { <ide> <ide> var values = get(obj, 'values'), <ide> expected = ['a', 'b', 'c', 'd', 'e', 'f']; <del> same(values, expected, "should concatenate values property (expected: %@, got: %@)".fmt(expected, values)); <add> same(values, expected, SC.String.fmt("should concatenate values property (expected: %@, got: %@)", expected, values)); <ide> }); <ide> <ide> test("concatenates reopen, subclass, and instance", function() { <ide> <ide> var values = get(obj, 'values'), <ide> expected = ['a', 'b', 'c', 'd', 'e', 'f']; <del> same(values, expected, "should concatenate values property (expected: %@, got: %@)".fmt(expected, values)); <add> same(values, expected, SC.String.fmt("should concatenate values property (expected: %@, got: %@)", expected, values)); <ide> }); <ide> <ide> <ide><path>packages/sproutcore-runtime/tests/legacy_1x/system/set_test.js <ide> test("SC.Set.create() should create empty set", function() { <ide> }); <ide> <ide> test("SC.Set.create([1,2,3]) should create set with three items in them", function() { <del> var set = SC.Set.create([a,b,c]) ; <add> var set = SC.Set.create(SC.NativeArray.apply([a,b,c])) ; <ide> equals(set.length, 3) ; <ide> equals(set.contains(a), YES) ; <ide> equals(set.contains(b), YES) ; <ide> module("SC.Set.remove + SC.Set.contains", { <ide> // generate a set with every type of object, but none of the specific <ide> // ones we add in the tests below... <ide> setup: function() { <del> set = SC.Set.create([ <add> set = SC.Set.create(SC.NativeArray.apply([ <ide> SC.Object.create({ dummy: YES }), <ide> { isHash: YES }, <ide> "Not the String", <del> 16, true, false, 0]) ; <add> 16, true, false, 0])) ; <ide> }, <ide> <ide> teardown: function() { <ide> module("SC.Set.pop + SC.Set.copy", { <ide> // generate a set with every type of object, but none of the specific <ide> // ones we add in the tests below... <ide> setup: function() { <del> set = SC.Set.create([ <add> set = SC.Set.create(SC.NativeArray.apply([ <ide> SC.Object.create({ dummy: YES }), <ide> { isHash: YES }, <ide> "Not the String", <del> 16, false]) ; <add> 16, false])) ; <ide> }, <ide> <ide> teardown: function() { <ide> test("the pop() should remove an arbitrary object from the set", function() { <ide> }); <ide> <ide> test("should pop false and 0", function(){ <del> set = SC.Set.create([false]); <add> set = SC.Set.create(SC.NativeArray.apply([false])); <ide> ok(set.pop() === false, "should pop false"); <ide> <del> set = SC.Set.create([0]); <add> set = SC.Set.create(SC.NativeArray.apply([0])); <ide> ok(set.pop() === 0, "should pop 0"); <ide> }); <ide> <ide><path>packages/sproutcore-runtime/tests/mixins/array_test.js <ide> test('modifying the array should also indicate the isDone prop itself has change <ide> testBoth("should be clear caches for computed properties that have dependent keys on arrays that are changed after object initialization", function(get, set) { <ide> var obj = SC.Object.create({ <ide> init: function() { <del> set(this, 'resources', SC.MutableArray.apply([])); <add> set(this, 'resources', SC.NativeArray.apply([])); <ide> }, <ide> <ide> common: SC.computed(function() { <ide> testBoth("observers that contain @each in the path should fire only once the fir <ide> var obj = SC.Object.create({ <ide> init: function() { <ide> // Observer fires once when resources changes <del> set(this, 'resources', SC.MutableArray.apply([])); <add> set(this, 'resources', SC.NativeArray.apply([])); <ide> }, <ide> <ide> commonDidChange: function() { <ide><path>packages/sproutcore-runtime/tests/mixins/mutable_array_test.js <ide> var TestMutableArray = SC.Object.extend(SC.MutableArray, { <ide> _content: null, <ide> <ide> init: function(ary) { <del> this._content = ary || []; <add> this._content = SC.NativeArray.apply(ary || []); <ide> }, <ide> <ide> replace: function(idx, amt, objects) { <ide><path>packages/sproutcore-runtime/tests/suites/array/indexOf.js <ide> suite.test("should return index of object", function() { <ide> idx; <ide> <ide> for(idx=0;idx<len;idx++) { <del> equals(obj.indexOf(expected[idx]), idx, 'obj.indexOf(%@) should match idx'.fmt(expected[idx])); <add> equals(obj.indexOf(expected[idx]), idx, SC.String.fmt('obj.indexOf(%@) should match idx', expected[idx])); <ide> } <ide> <ide> }); <ide><path>packages/sproutcore-runtime/tests/suites/array/objectAt.js <ide> suite.test("should return object at specified index", function() { <ide> idx; <ide> <ide> for(idx=0;idx<len;idx++) { <del> equals(obj.objectAt(idx), expected[idx], 'obj.objectAt(%@) should match'.fmt(idx)); <add> equals(obj.objectAt(idx), expected[idx], SC.String.fmt('obj.objectAt(%@) should match', idx)); <ide> } <ide> <ide> }); <ide><path>packages/sproutcore-runtime/tests/system/array_proxy/suite_test.js <ide> SC.MutableArrayTests.extend({ <ide> <ide> newObject: function(ary) { <ide> var ret = ary ? ary.slice() : this.newFixture(3); <del> return new SC.ArrayProxy(ret); <add> return new SC.ArrayProxy(SC.NativeArray.apply(ret)); <ide> }, <ide> <ide> mutate: function(obj) { <ide><path>packages/sproutcore-runtime/tests/system/native_array/copyable_suite_test.js <ide> SC.CopyableTests.extend({ <ide> name: 'NativeArray Copyable', <ide> <ide> newObject: function() { <del> return [SC.generateGuid()]; <add> return SC.NativeArray.apply([SC.generateGuid()]); <ide> }, <ide> <ide> isEqual: function(a,b) { <ide><path>packages/sproutcore-runtime/tests/system/native_array/suite_test.js <ide> SC.MutableArrayTests.extend({ <ide> name: 'Native Array', <ide> <ide> newObject: function(ary) { <del> return ary ? ary.slice() : this.newFixture(3); <add> return SC.NativeArray.apply(ary ? ary.slice() : this.newFixture(3)); <ide> }, <ide> <ide> mutate: function(obj) {
16
Javascript
Javascript
add default configs to buffer benchmark
b62343d83ceaec35b6af2d3cd77f5271497744a0
<ide><path>benchmark/buffers/buffer-creation.js <ide> function main(conf) { <ide> const len = +conf.len; <ide> const n = +conf.n; <ide> switch (conf.type) { <add> case '': <ide> case 'fast-alloc': <ide> bench.start(); <ide> for (let i = 0; i < n * 1024; i++) { <ide><path>benchmark/buffers/buffer-iterate.js <ide> var methods = { <ide> }; <ide> <ide> function main(conf) { <del> var len = +conf.size; <del> var clazz = conf.type === 'fast' ? Buffer : SlowBuffer; <del> var buffer = new clazz(len); <add> const len = +conf.size; <add> const clazz = conf.type === 'fast' ? Buffer : SlowBuffer; <add> const buffer = new clazz(len); <ide> buffer.fill(0); <ide> <del> methods[conf.method](buffer, conf.n); <add> const method = conf.method || 'for'; <add> methods[method](buffer, conf.n); <ide> } <ide> <ide> <ide><path>benchmark/buffers/buffer-read.js <ide> var bench = common.createBenchmark(main, { <ide> }); <ide> <ide> function main(conf) { <del> var noAssert = conf.noAssert === 'true'; <del> var len = +conf.millions * 1e6; <del> var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; <del> var buff = new clazz(8); <del> var fn = `read${conf.type}`; <add> const noAssert = conf.noAssert === 'true'; <add> const len = +conf.millions * 1e6; <add> const clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; <add> const buff = new clazz(8); <add> const type = conf.type || 'UInt8'; <add> const fn = `read${type}`; <ide> <ide> buff.writeDoubleLE(0, 0, noAssert); <del> var testFunction = new Function('buff', ` <add> const testFunction = new Function('buff', ` <ide> for (var i = 0; i !== ${len}; i++) { <ide> buff.${fn}(0, ${JSON.stringify(noAssert)}); <ide> } <ide><path>benchmark/buffers/buffer-swap.js <ide> function genMethod(method) { <ide> } <ide> <ide> function main(conf) { <del> const method = conf.method; <add> const method = conf.method || 'swap16'; <ide> const len = conf.len | 0; <ide> const n = conf.n | 0; <ide> const aligned = conf.aligned || 'true'; <ide><path>benchmark/buffers/buffer-write.js <ide> var mod = { <ide> }; <ide> <ide> function main(conf) { <del> var noAssert = conf.noAssert === 'true'; <del> var len = +conf.millions * 1e6; <del> var clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; <del> var buff = new clazz(8); <del> var fn = `write${conf.type}`; <add> const noAssert = conf.noAssert === 'true'; <add> const len = +conf.millions * 1e6; <add> const clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; <add> const buff = new clazz(8); <add> const type = conf.type || 'UInt8'; <add> const fn = `write${type}`; <ide> <ide> if (/Int/.test(fn)) <ide> benchInt(buff, fn, len, noAssert); <ide><path>benchmark/buffers/dataview-set.js <ide> var mod = { <ide> }; <ide> <ide> function main(conf) { <del> var len = +conf.millions * 1e6; <del> var ab = new ArrayBuffer(8); <del> var dv = new DataView(ab, 0, 8); <del> var le = /LE$/.test(conf.type); <del> var fn = `set${conf.type.replace(/[LB]E$/, '')}`; <add> const len = +conf.millions * 1e6; <add> const ab = new ArrayBuffer(8); <add> const dv = new DataView(ab, 0, 8); <add> const type = conf.type || 'Uint8'; <add> const le = /LE$/.test(type); <add> const fn = `set${type.replace(/[LB]E$/, '')}`; <ide> <ide> if (/int/i.test(fn)) <ide> benchInt(dv, fn, len, le);
6
Python
Python
use less chunks to speed up the test
faf718ae5fe1e1294cf9eec61a12d983139d28a7
<ide><path>integration/storage/base.py <ide> def test_upload_via_stream_with_content_encoding(self): <ide> content = gzip.compress(os.urandom(MB // 100)) <ide> container = self.driver.create_container(self._random_container_name()) <ide> self.driver.upload_object_via_stream( <del> get_content_iter_with_chunk_size(content, 500), <add> get_content_iter_with_chunk_size(content, 1000), <ide> container, <ide> object_name, <ide> headers={'Content-Encoding': 'gzip'}, <ide> def test_upload_via_stream_with_content_encoding(self): <ide> def test_cdn_url(self): <ide> content = os.urandom(MB // 100) <ide> container = self.driver.create_container(self._random_container_name()) <del> content_iter = get_content_iter_with_chunk_size(content, 500) <add> content_iter = get_content_iter_with_chunk_size(content, 1000) <ide> obj = self.driver.upload_object_via_stream(content_iter, container, 'cdn') <ide> <ide> response = requests.get(self.driver.get_object_cdn_url(obj))
1
Ruby
Ruby
fix typo in macos.sdk_path
ffd6e7f34043c70402bd28a35e998049ff890a07
<ide><path>Library/Homebrew/macos.rb <ide> def sdk_path(v = version) <ide> # Xcode.prefix is pretty smart, so lets look inside to find the sdk <ide> opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" <ide> # Xcode < 4.3 style <del> opts << "/Developer/SDKs/MacOS#{v}.sdk" <add> opts << "/Developer/SDKs/MacOSX#{v}.sdk" <ide> opts.map{|a| Pathname.new(a) }.detect { |p| p.directory? } <ide> end <ide> end
1
Javascript
Javascript
rewrite code to no longer use __guard__
498d7c90ebd382ca966b9f1bed32ba8228d225f1
<ide><path>spec/project-spec.js <ide> /* <ide> * decaffeinate suggestions: <del> * DS103: Rewrite code to no longer use __guard__ <ide> * DS201: Simplify complex destructure assignments <ide> * DS207: Consider shorter variations of null checks <ide> * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md <ide> const GitRepository = require('../src/git-repository') <ide> <ide> describe('Project', function () { <ide> beforeEach(function () { <del> atom.project.setPaths([__guard__(atom.project.getDirectories()[0], x => x.resolve('dir'))]) <add> const directory = atom.project.getDirectories()[0] <add> const paths = directory ? [directory.resolve('dir')] : [null] <add> atom.project.setPaths(paths) <ide> <ide> // Wait for project's service consumers to be asynchronously added <ide> waits(1) <ide> describe('Project', function () { <ide> waitsForPromise(() => notQuittingProject.deserialize(atom.project.serialize({isUnloading: false}))) <ide> <ide> runs(function () { <del> expect(__guard__(notQuittingProject.getBuffers()[0].getMarkerLayer(layerA.id), x => x.getMarker(markerA.id))).toBeUndefined() <add> expect(notQuittingProject.getBuffers()[0].getMarkerLayer(layerA.id), x => x.getMarker(markerA.id)).toBeUndefined() <ide> expect(notQuittingProject.getBuffers()[0].undo()).toBe(false) <ide> quittingProject = new Project({notificationManager: atom.notifications, packageManager: atom.packages, confirm: atom.confirm}) <ide> }) <ide> <ide> waitsForPromise(() => quittingProject.deserialize(atom.project.serialize({isUnloading: true}))) <ide> <ide> runs(function () { <del> expect(__guard__(quittingProject.getBuffers()[0].getMarkerLayer(layerA.id), x => x.getMarker(markerA.id))).not.toBeUndefined() <add> expect(quittingProject.getBuffers()[0].getMarkerLayer(layerA.id), x => x.getMarker(markerA.id)).not.toBeUndefined() <ide> expect(quittingProject.getBuffers()[0].undo()).toBe(true) <ide> }) <ide> }) <ide> describe('Project', function () { <ide> it('normalizes disk drive letter in passed path on #win32', () => expect(atom.project.resolvePath('d:\\file.txt')).toEqual('D:\\file.txt')) <ide> ) <ide> }) <del> <del>function __guard__ (value, transform) { <del> return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined <del>}
1
Ruby
Ruby
remove the mounted? method
9f63a78d554690efba3819310710634228089d24
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def define_generate_prefix(app, name) <ide> _routes = @set <ide> app.routes.define_mounted_helper(name) <ide> app.routes.extend Module.new { <del> def mounted?; true; end <add> def optimize_routes_generation?; false; end <ide> define_method :find_script_name do |options| <ide> super(options) || begin <ide> prefix_options = options.slice(*_route.segment_keys) <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def generate(route_key, options, recall = {}) <ide> :trailing_slash, :anchor, :params, :only_path, :script_name, <ide> :original_script_name] <ide> <del> def mounted? <del> false <del> end <del> <ide> def optimize_routes_generation? <del> !mounted? && default_url_options.empty? <add> default_url_options.empty? <ide> end <ide> <ide> def find_script_name(options)
2
Python
Python
pass x-trino-client-info in trino hook
0c30564992a9250e294106e809123f0d5b1c2b78
<ide><path>airflow/providers/trino/hooks/trino.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <add>import json <ide> import os <ide> import warnings <ide> from typing import Any, Callable, Iterable, Optional, overload <ide> from airflow.configuration import conf <ide> from airflow.hooks.dbapi import DbApiHook <ide> from airflow.models import Connection <add>from airflow.utils.operator_helpers import AIRFLOW_VAR_NAME_FORMAT_MAPPING <add> <add>try: <add> from airflow.utils.operator_helpers import DEFAULT_FORMAT_PREFIX <add>except ImportError: <add> # This is from airflow.utils.operator_helpers, <add> # For the sake of provider backward compatibility, this is hardcoded if import fails <add> # https://github.com/apache/airflow/pull/22416#issuecomment-1075531290 <add> DEFAULT_FORMAT_PREFIX = 'airflow.ctx.' <add> <add> <add>def generate_trino_client_info() -> str: <add> """Return json string with dag_id, task_id, execution_date and try_number""" <add> context_var = { <add> format_map['default'].replace(DEFAULT_FORMAT_PREFIX, ''): os.environ.get( <add> format_map['env_var_format'], '' <add> ) <add> for format_map in AIRFLOW_VAR_NAME_FORMAT_MAPPING.values() <add> } <add> task_info = { <add> 'dag_id': context_var['dag_id'], <add> 'task_id': context_var['task_id'], <add> 'execution_date': context_var['execution_date'], <add> 'try_number': context_var['try_number'], <add> 'dag_run_id': context_var['dag_run_id'], <add> 'dag_owner': context_var['dag_owner'], <add> } <add> return json.dumps(task_info, sort_keys=True) <ide> <ide> <ide> class TrinoException(Exception): <ide> def get_conn(self) -> Connection: <ide> delegate=_boolify(extra.get('kerberos__delegate', False)), <ide> ca_bundle=extra.get('kerberos__ca_bundle'), <ide> ) <add> <add> http_headers = {"X-Trino-Client-Info": generate_trino_client_info()} <ide> trino_conn = trino.dbapi.connect( <ide> host=db.host, <ide> port=db.port, <ide> user=db.login, <ide> source=extra.get('source', 'airflow'), <ide> http_scheme=extra.get('protocol', 'http'), <add> http_headers=http_headers, <ide> catalog=extra.get('catalog', 'hive'), <ide> schema=db.schema, <ide> auth=auth, <ide><path>tests/providers/trino/hooks/test_trino.py <ide> def test_get_conn_basic_auth(self, mock_get_connection, mock_connect, mock_basic <ide> self.assert_connection_called_with(mock_connect, auth=mock_basic_auth) <ide> mock_basic_auth.assert_called_once_with('login', 'password') <ide> <add> @patch('airflow.providers.trino.hooks.trino.generate_trino_client_info') <add> @patch(BASIC_AUTHENTICATION) <add> @patch(TRINO_DBAPI_CONNECT) <add> @patch(HOOK_GET_CONNECTION) <add> def test_http_headers( <add> self, <add> mock_get_connection, <add> mock_connect, <add> mock_basic_auth, <add> mocked_generate_airflow_trino_client_info_header, <add> ): <add> mock_get_connection.return_value = Connection( <add> login='login', password='password', host='host', schema='hive' <add> ) <add> client = json.dumps( <add> { <add> "dag_id": "dag-id", <add> "execution_date": "2022-01-01T00:00:00", <add> "task_id": "task-id", <add> "try_number": "1", <add> "dag_run_id": "dag-run-id", <add> "dag_owner": "dag-owner", <add> }, <add> sort_keys=True, <add> ) <add> http_headers = {'X-Trino-Client-Info': client} <add> <add> mocked_generate_airflow_trino_client_info_header.return_value = http_headers['X-Trino-Client-Info'] <add> <add> conn = TrinoHook().get_conn() <add> self.assert_connection_called_with(mock_connect, auth=mock_basic_auth, http_headers=http_headers) <add> <add> mock_basic_auth.assert_called_once_with('login', 'password') <add> assert mock_connect.return_value == conn <add> <ide> @patch(HOOK_GET_CONNECTION) <ide> def test_get_conn_invalid_auth(self, mock_get_connection): <ide> extras = {'auth': 'kerberos'} <ide> def set_get_connection_return_value(mock_get_connection, extra=None, password=No <ide> mock_get_connection.return_value = mocked_connection <ide> <ide> @staticmethod <del> def assert_connection_called_with(mock_connect, auth=None, verify=True): <add> def assert_connection_called_with(mock_connect, http_headers=mock.ANY, auth=None, verify=True): <ide> mock_connect.assert_called_once_with( <ide> catalog='hive', <ide> host='host', <ide> port=None, <ide> http_scheme='http', <add> http_headers=http_headers, <ide> schema='hive', <ide> source='airflow', <ide> user='login',
2
Text
Text
add contributor doc
c33d6ca36014ddb09416dcc977fab86240e43209
<ide><path>.github/contributors/iann0036.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [x] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Ian Mckay | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 22/03/2018 | <add>| GitHub username | iann0036 | <add>| Website (optional) | |
1
PHP
PHP
fix bug in place-holder replacement
73340aed77b9d06b065b629bf5834ec2ae92ad9f
<ide><path>src/Illuminate/Routing/Route.php <ide> protected static function compileParameters($value, array $wheres = array()) <ide> { <ide> $value = static::compileWhereParameters($value, $wheres); <ide> <del> return preg_replace('/\{((.*?)[^?])\}/', static::$wildcard, $value); <add> return preg_replace('/\{(([\w\-]+)[^?])\}/', static::$wildcard, $value); <ide> } <ide> <ide> /** <ide> protected static function compileOptional($value, $wheres = array()) <ide> */ <ide> protected static function compileStandardOptional($value, $custom = 0) <ide> { <del> $value = preg_replace('/\/\{(.*?)\?\}/', static::$optional, $value, -1, $count); <add> $value = preg_replace('/\/\{([\w\-]+)\?\}/', static::$optional, $value, -1, $count); <ide> <del> $value = preg_replace('/^(\{(.*?)\?\})/', static::$leadingOptional, $value, -1, $leading); <add> $value = preg_replace('/^(\{([\w\-]+)\?\})/', static::$leadingOptional, $value, -1, $leading); <ide> <ide> $total = $leading + $count + $custom; <ide>
1
Text
Text
move tests to /learn
c0b9ad6bf2fd17661064586dd1b1decaeb43b399
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md <ide> When you are done, make sure a working demo of your project is hosted somewhere <ide> - To run the challenge tests on this page, set `NODE_ENV` to `test` without quotes in the `.env` file <ide> - To run the tests in the console, use the command `npm run test`. To open the Repl.it console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell" <ide> <add>Write the following tests in `tests/1_unit-tests.js`: <add> <add>- Logic handles a valid puzzle string of 81 characters <add>- Logic handles a puzzle string with invalid characters (not 1-9 or `.`) <add>- Logic handles a puzzle string that is not 81 characters in length <add>- Logic handles a valid row placement <add>- Logic handles an invalid row placement <add>- Logic handles a valid column placement <add>- Logic handles an invalid column placement <add>- Logic handles a valid region (3x3 grid) placement <add>- Logic handles an invalid region (3x3 grid) placement <add>- Valid puzzle strings pass the solver <add>- Invalid puzzle strings fail the solver <add>- Solver returns the the expected solution for an incomplete puzzzle <add> <add>Write the following tests in `tests/2_functional-tests.js` <add> <add>- Solve a puzzle with valid puzzle string: POST request to `/api/solve` <add>- Solve a puzzle with missing puzzle string: POST request to `/api/solve` <add>- Solve a puzzle with invalid characters: POST request to `/api/solve` <add>- Solve a puzzle with incorrect length: POST request to `/api/solve` <add>- Solve a puzzle that cannot be solved: POST request to `/api/solve` <add>- Check a puzzle placement with all fields: POST request to `/api/check` <add>- Check a puzzle placement with single placement conflict: POST request to `/api/check` <add>- Check a puzzle placement with multiple placement conflicts: POST request to `/api/check` <add>- Check a puzzle placement with all placement conflicts: POST request to `/api/check` <add>- Check a puzzle placement with missing required fields: POST request to `/api/check` <add>- Check a puzzle placement with invalid characters: POST request to `/api/check` <add>- Check a puzzle placement with incorrect length: POST request to `/api/check` <add>- Check a puzzle placement with invalid placement coordinate: POST request to `/api/check` <add>- Check a puzzle placement with invalid placement value: POST request to `/api/check` <add> <ide> </section> <ide> <ide> ## Tests
1
Text
Text
add wiki link to mvc
ed30c4d0ea820d79601ca17e2c670e6acae16eb7
<ide><path>README.md <ide> component in an interconnected way like a well-oiled machine. AngularJS is JavaS <ide> and done right. (Well it is not really MVC, read on, to understand what this means.) <ide> <ide> #### MVC, no, MV* done the right way! <del>MVC, short for Model-View-Controller, is a design pattern, i.e. how the code should be organized and <del>how the different parts of an application separated for proper readability and debugging. Model is <del>the data and the database. View is the user interface and what the user sees. Controller is the main <del>link between Model and View. These are the three pillars of major programming frameworks present on <del>the market today. On the other hand AngularJS works on MV*, short for Model-View-_Whatever_. The <add>[MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller), short for <add>Model-View-Controller, is a design pattern, i.e. how the code should be organized and how the <add>different parts of an application separated for proper readability and debugging. Model is the data <add>and the database. View is the user interface and what the user sees. Controller is the main link <add>between Model and View. These are the three pillars of major programming frameworks present on the <add>market today. On the other hand AngularJS works on MV*, short for Model-View-_Whatever_. The <ide> _Whatever_ is AngularJS's way of telling that you may create any kind of linking between the Model <ide> and the View here. <ide>
1
Text
Text
react conf lanches
67a8d8951d3ffdc49f7a31403b3f08626565707c
<ide><path>blog/2017-03-13-better-list-views.md <add>--- <add>title: Better List Views in React Native <add>author: Spencer Ahrens <add>authorTitle: Software Engineer at Facebook <add>authorURL: https://github.com/sahrens <add>authorImage: https://avatars1.githubusercontent.com/u/1509831 <add>authorTwitter: sahrens2012 <add>category: engineering <add>--- <add> <add>Many of you have started playing with some of our new List components already after our [teaser announcement in the community group](https://www.facebook.com/groups/react.native.community/permalink/921378591331053), but we are officially announcing them today! No more `ListView`s or `DataSource`s, stale rows, ignored bugs, or excessive memory consumption - with the latest React Native March 2017 release candidate (`0.43-rc.1`) you can pick from the new suite of components what best fits your use-case, with great perf and feature sets out of the box: <add> <add>### [`<FlatList>`](https://facebook.github.io/react-native/releases/next/docs/flatlist.html) ### <add> <add>This is the workhorse component for simple, performant lists. Provide an array of data and a `renderItem` function and you're good to go: <add> <add>``` <add><FlatList <add> data={[{title: 'Title Text', key: 'item1'}, ...]} <add> renderItem={({item}) => <ListItem title={item.title}} <add>/> <add>``` <add> <add>### [`<SectionList>`](https://facebook.github.io/react-native/releases/next/docs/sectionlist.html) ### <add> <add>If you want to render a set of data broken into logical sections, maybe with section headers (e.g. in an alphabetical address book), and potentially with heterogeneous data and rendering (such as a profile view with some buttons followed by a composer, then a photo grid, then a friend grid, and finally a list of stories), this is the way to go. <add> <add>``` <add><SectionList <add> renderItem={({item}) => <ListItem title={item.title}} <add> renderSectionHeader={({section}) => <H1 title={section.key} />} <add> sections={[ // homogenous rendering between sections <add> {data: [...], key: ...}, <add> {data: [...], key: ...}, <add> {data: [...], key: ...}, <add> ]} <add>/> <add> <add><SectionList <add> sections={[ // heterogeneous rendering between sections <add> {data: [...], key: ..., renderItem: ...}, <add> {data: [...], key: ..., renderItem: ...}, <add> {data: [...], key: ..., renderItem: ...}, <add> ]} <add>/> <add>``` <add> <add>### [`<VirtualizedList>`](https://facebook.github.io/react-native/releases/next/docs/virtualizedlist.html) ## <add> <add>The implementation behind the scenes with a more flexible API. Especially handy if your data is not in a plain array (e.g. an immutable list). <add> <add>## Features ## <add> <add>Lists are used in many contexts, so we packed the new components full of features to handle the majority of use cases out of the box: <add> <add>* Scroll loading (`onEndReached`). <add>* Pull to refresh (`onRefresh` / `refreshing`). <add>* [Configurable](https://github.com/facebook/react-native/blob/master/Libraries/CustomComponents/Lists/ViewabilityHelper.js) viewability (VPV) callbacks (`onViewableItemsChanged` / `viewabilityConfig`). <add>* Horizontal mode (`horizontal`). <add>* Intelligent item and section separators. <add>* Multi-column support (`numColumns`) <add>* `scrollToEnd`, `scrollToIndex`, and `scrollToItem` <add>* Better Flow typing. <add> <add>### Some Caveats ### <add> <add>- The internal state of item subtrees is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay. <add> <add>- These components are based on `PureComponent` which means that they will not re-render if `props` remains shallow-equal. Make sure that everything your `renderItem` function depends on directly is passed as a prop that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state. For example: <add> <add> ```javascript <add> <FlatList <add> data={this.state.data} <add> renderItem={({item}) => <MyItem <add> item={item} <add> onPress={() => this.setState((oldState) => ({ <add> selected: { // New instance breaks `===` <add> ...oldState.selected, // copy old data <add> [item.key]: !oldState.selected[item.key], // toggle <add> }})) <add> } <add> selected={ <add> !!this.state.selected[item.key] // renderItem depends on state <add> } <add> />} <add> selected={ // Can be any prop that doesn't collide with existing props <add> this.state.selected // A change to selected should re-render FlatList <add> } <add> /> <add> ``` <add> <add>- In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes. <add> <add>- By default, these new lists look for a `key` prop on each item and use that for the React key. Alternatively, you can provide a custom `keyExtractor` prop. <add> <add>## Performance ## <add> <add>Besides simplifying the API, the new list components also have significant performance enhancements, the main one being nearly constant memory usage for any number of rows. This is done by 'virtualizing' elements that are outside of the render window by completely unmounting them from the component hierarchy and reclaiming the JS memory from the react components, along with the native memory from the shadow tree and the UI views. This has a catch which is that internal component state will not be preserved, so **make sure you track any important state outside of the components themselves, e.g. in Relay or Redux or Flux store.** <add> <add>Limiting the render window also reduces the amount of work that needs to be done by React and the native platform, e.g from view traversals. Even if you are rendering the last of a million elements, with these new lists there is no need to iterate through all those elements in order to render. You can even jump to the middle with `scrollToIndex` without excessive rendering. <add> <add>We've also made some improvements with scheduling which should help with application responsiveness. Items at the edge of the render window are rendered infrequently and at a lower priority after any active gestures or animations or other interactions have completed. <add> <add>## Advanced Usage ## <add> <add>Unlike `ListView`, all items in the render window are re-rendered any time any props change. Often this is fine because the windowing reduces the number of items to a constant number, but if your items are on the complex side, you should make sure to follow React best practices for performance and use `React.PureComponent` and/or `shouldComponentUpdate` as appropriate within your components to limit re-renders of the recursive subtree. <add> <add>If you can calculate the height of your rows without rendering them, you can improve the user experience by providing the `getItemLayout` prop. This makes it much smoother to scroll to specific items with e.g. `scrollToIndex`, and will improve the scroll indicator UI because the height of the content can be determined without rendering it. <add> <add>If you have an alternative data type, like an immutable list, `<VirtualizedList>` is the way to go. It takes a `getItem` prop that lets you return the item data for any given index and has looser flow typing. <add> <add>There are also a bunch of parameters you can tweak if you have an unusual use case. For example, you can use `windowSize` to trade off memory usage vs. user experience, `maxToRenderPerBatch` to adjust fill rate vs. responsiveness, `onEndReachedThreshold` to control when scroll loading happens, and more. <add> <add>## Future Work ## <add> <add>* Migration of existing surfaces (ultimately deprecation of `ListView`). <add>* More features as we see/hear the need (let us know!). <add>* Sticky section header support. <add>* More performance optimizations. <add>* Support functional item components with state. <ide><path>blog/2017-03-13-idx-the-existential-function.md <add>--- <add>title: idx: The Existential Function <add>author: Timothy Yung <add>authorTitle: Engineering Manager at Facebook <add>authorURL: https://github.com/yungsters <add>authorImage: https://pbs.twimg.com/profile_images/1592444107/image.jpg <add>authorTwitter: yungsters <add>category: engineering <add>--- <add> <add>At Facebook, we often need to access deeply nested values in data structures fetched with GraphQL. On the way to accessing these deeply nested values, it is common for one or more intermediate fields to be nullable. These intermediate fields may be null for a variety of reasons, from failed privacy checks to the mere fact that null happens to be the most flexible way to represent non-fatal errors. <add> <add>Unfortunately, accessing these deeply nested values is currently tedious and verbose. <add> <add>```javascript <add>props.user && <add>props.user.friends && <add>props.user.friends[0] && <add>props.user.friends[0].friends <add>``` <add> <add>There is [an ECMAScript proposal to introduce the existential operator](https://github.com/claudepache/es-optional-chaining) which will make this much more convenient. But until a time when that proposal is finalized, we want a solution that improves our quality of life, maintains existing language semantics, and encourages type safety with Flow. <add> <add>We came up with an existential _function_ we call `idx`. <add> <add>```javascript <add>idx(props, _ => _.user.friends[0].friends) <add>``` <add> <add>The invocation in this code snippet behaves similarly to the boolean expression in the code snippet above, except with significantly less repetition. The `idx` function takes exactly two arguments: <add> <add>- Any value, typically an object or array into which you want to access a nested value. <add>- A function that receives the first argument and accesses a nested value on it. <add> <add>In theory, the `idx` function will try-catch errors that are the result of accessing properties on null or undefined. If such an error is caught, it will return either null or undefined. (And you can see how this might be implemented in [idx.js](https://github.com/facebookincubator/idx/blob/master/packages/idx/src/idx.js).) <add> <add>In practice, try-catching every nested property access is slow, and differentiating between specific kinds of TypeErrors is fragile. To deal with these shortcomings, we created a Babel plugin that transforms the above `idx` invocation into the following expression: <add> <add>```javascript <add>props.user == null ? props.user : <add>props.user.friends == null ? props.user.friends : <add>props.user.friends[0] == null ? props.user.friends[0] : <add>props.user.friends[0].friends <add>``` <add> <add>Finally, we added a custom Flow type declaration for `idx` that allows the traversal in the second argument to be properly type-checked while permitting nested access on nullable properties. <add> <add>The function, Babel plugin, and Flow declaration are now [available on GitHub](https://github.com/facebookincubator/idx). They are used by installing the **idx** and **babel-plugin-idx** npm packages, and adding “idx” to the list of plugins in your `.babelrc` file. <ide><path>blog/2017-03-13-introducing-create-react-native-app.md <add>--- <add>title: Introducing Create React Native App <add>author: Adam Perry <add>authorTitle: Software Engineer at Expo <add>authorURL: https://github.com/dikaiosune <add>authorImage: https://avatars2.githubusercontent.com/u/6812281 <add>authorTwitter: dika10sune <add>category: engineering <add>--- <add> <add>Today we’re announcing [Create React Native App](https://github.com/react-community/create-react-native-app): a new tool that makes it significantly easier to get started with a React Native project! It’s heavily inspired by the design of [Create React App](https://github.com/facebookincubator/create-react-app) and is the product of a collaboration between [Facebook](https://code.facebook.com) and [Expo](https://expo.io) (formerly Exponent). <add> <add>Many developers struggle with installing and configuring React Native’s current native build dependencies, especially for Android. With Create React Native App, there’s no need to use Xcode or Android Studio, and you can develop for your iOS device using Linux or Windows. This is accomplished using the Expo app, which loads and runs CRNA projects written in pure JavaScript without compiling any native code. <add> <add>Try creating a new project (replace with suitable yarn commands if you have it installed): <add> <add>``` <add>$ npm i -g create-react-native-app <add>$ create-react-native-app my-project <add>$ cd my-project <add>$ npm start <add>``` <add> <add>This will start the React Native packager and print a QR code. Open it in the [Expo app](https://expo.io) to load your JavaScript. Calls to `console.log` are forwarded to your terminal. You can make use of any standard React Native APIs as well as the [Expo SDK](https://docs.expo.io/versions/latest/sdk/index.html). <add> <add>## What about native code? <add> <add>Many React Native projects have Java or Objective-C/Swift dependencies that need to be compiled. The Expo app does include APIs for camera, video, contacts, and more, and bundles popular libraries like [Airbnb’s react-native-maps](https://docs.expo.io/versions/v14.0.0/sdk/map-view.html), or [Facebook authentication](https://docs.expo.io/versions/latest/sdk/facebook.html). However if you need a native code dependency that Expo doesn’t bundle then you’ll probably need to have your own build configuration for it. Just like Create React App, “ejecting” is supported by CRNA. <add> <add>You can run `npm run eject` to get a project very similar to what `react-native init` would generate. At that point you’ll need Xcode and/or Android Studio just as you would if you started with `react-native init` , adding libraries with `react-native link` will work, and you’ll have full control over the native code compilation process. <add> <add>## Questions? Feedback? <add> <add>Create React Native App is now stable enough for general use, which means we’re very eager to hear about your experience using it! You can find me [on Twitter](https://twitter.com/dika10sune) or open an issue on [the GitHub repository](https://github.com/react-community/create-react-native-app). Pull requests are very welcome!
3
Ruby
Ruby
fix output when no packages to upgrade
5de3686cd2e041dae893f9e84d74c925cb6c85f5
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> outdated -= pinned <ide> end <ide> <del> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:" <del> puts outdated.map{ |f| "#{f.name} #{f.version}" } * ", " <add> unless outdated.empty? <add> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:" <add> puts outdated.map{ |f| "#{f.name} #{f.version}" } * ", " <add> else <add> oh1 "No packages to upgrade" <add> end <ide> <ide> unless upgrade_pinned? || pinned.empty? <ide> oh1 "Not upgrading #{pinned.length} pinned package#{pinned.length.plural_s}:"
1
PHP
PHP
move generation of full message to message class
124ebdc5033c37d207a969dcf0ca4e5f97ab35d9
<ide><path>src/Mailer/Email.php <ide> class Email implements JsonSerializable, Serializable <ide> */ <ide> protected $renderer; <ide> <del> /** <del> * If set, boundary to use for multipart mime messages <del> * <del> * @var string|null <del> */ <del> protected $_boundary; <del> <ide> /** <ide> * A copy of the configuration profile for this <ide> * instance. This copy can be modified with Email::profile(). <ide> public function send($content = null): array <ide> */ <ide> public function render(?string $content = null): void <ide> { <del> $data = $this->getRenderer()->render($this, $content); <del> $this->_boundary = $data['boundary']; <del> <del> $this->message->setContent($data); <add> $content = $this->getRenderer()->getContent( <add> $content, <add> $this->message->getBodyTypes() <add> ); <add> foreach ($content as $type => $body) { <add> $this->message->setBody($body, $type); <add> } <ide> } <ide> <ide> /** <ide><path>src/Mailer/Message.php <ide> namespace Cake\Mailer; <ide> <ide> use Cake\Core\Configure; <add>use Cake\Http\Client\FormDataPart; <add>use Cake\Utility\Hash; <add>use Cake\Utility\Security; <ide> use Cake\Utility\Text; <ide> use InvalidArgumentException; <ide> use JsonSerializable; <ide> */ <ide> class Message implements JsonSerializable, Serializable <ide> { <add> /** <add> * Line length - no should more - RFC 2822 - 2.1.1 <add> * <add> * @var int <add> */ <add> public const LINE_LENGTH_SHOULD = 78; <add> <add> /** <add> * Line length - no must more - RFC 2822 - 2.1.1 <add> * <add> * @var int <add> */ <add> public const LINE_LENGTH_MUST = 998; <add> <ide> /** <ide> * Type of message - HTML <ide> * <ide> class Message implements JsonSerializable, Serializable <ide> */ <ide> protected $_priority; <ide> <del> /** <del> * A copy of the configuration profile for this <del> * instance. This copy can be modified with Email::profile(). <del> * <del> * @var array <del> */ <del> protected $_profile = []; <del> <ide> /** <ide> * 8Bit character sets <ide> * <ide> public function addHeaders(array $headers): self <ide> */ <ide> public function getHeaders(array $include = []): array <ide> { <add> $this->createBoundary(); <add> <ide> if ($include === array_values($include)) { <ide> $include = array_fill_keys($include, true); <ide> } <ide> public function getEmailFormat(): string <ide> return $this->_emailFormat; <ide> } <ide> <add> /** <add> * Gets the body types that are in this email message <add> * <add> * @return array Array of types. Valid types are Email::MESSAGE_TEXT and Email::MESSAGE_HTML <add> */ <add> public function getBodyTypes(): array <add> { <add> $format = $this->_emailFormat; <add> <add> if ($format === self::MESSAGE_BOTH) { <add> return [self::MESSAGE_HTML, self::MESSAGE_TEXT]; <add> } <add> <add> return $types = [$format]; <add> } <add> <ide> /** <ide> * Sets message ID. <ide> * <ide> public function getDomain(): string <ide> * Attach a single file: <ide> * <ide> * ``` <del> * $email->setAttachments('path/to/file'); <add> * $this->setAttachments('path/to/file'); <ide> * ``` <ide> * <ide> * Attach a file with a different filename: <ide> * <ide> * ``` <del> * $email->setAttachments(['custom_name.txt' => 'path/to/file.txt']); <add> * $this->setAttachments(['custom_name.txt' => 'path/to/file.txt']); <ide> * ``` <ide> * <ide> * Attach a file and specify additional properties: <ide> * <ide> * ``` <del> * $email->setAttachments(['custom_name.png' => [ <add> * $this->setAttachments(['custom_name.png' => [ <ide> * 'file' => 'path/to/file', <ide> * 'mimetype' => 'image/png', <ide> * 'contentId' => 'abc123', <ide> public function getDomain(): string <ide> * Attach a file from string and specify additional properties: <ide> * <ide> * ``` <del> * $email->setAttachments(['custom_name.png' => [ <add> * $this->setAttachments(['custom_name.png' => [ <ide> * 'data' => file_get_contents('path/to/file'), <ide> * 'mimetype' => 'image/png' <ide> * ] <ide> public function message(?string $type = null) <ide> return $this->_textMessage; <ide> } <ide> <add> if (empty($this->_message)) { <add> $this->_message = $this->generateMessage(); <add> } <add> <ide> return $this->_message; <ide> } <ide> <add> /** <add> * Create unique boundary identifier <add> * <add> * @return void <add> */ <add> protected function createBoundary(): void <add> { <add> if ($this->_boundary === null && <add> ($this->_attachments || $this->_emailFormat === self::MESSAGE_BOTH) <add> ) { <add> $this->_boundary = md5(Security::randomBytes(16)); <add> } <add> } <add> <add> /** <add> * Generate full message. <add> * <add> * @return void <add> */ <add> protected function generateMessage() <add> { <add> $this->createBoundary(); <add> $msg = []; <add> <add> $contentIds = array_filter((array)Hash::extract($this->_attachments, '{s}.contentId')); <add> $hasInlineAttachments = count($contentIds) > 0; <add> $hasAttachments = !empty($this->_attachments); <add> $hasMultipleTypes = $this->_emailFormat === self::MESSAGE_BOTH; <add> $multiPart = ($hasAttachments || $hasMultipleTypes); <add> <add> $boundary = $relBoundary = $textBoundary = $this->_boundary; <add> <add> if ($hasInlineAttachments) { <add> $msg[] = '--' . $boundary; <add> $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"'; <add> $msg[] = ''; <add> $relBoundary = $textBoundary = 'rel-' . $boundary; <add> } <add> <add> if ($hasMultipleTypes && $hasAttachments) { <add> $msg[] = '--' . $relBoundary; <add> $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"'; <add> $msg[] = ''; <add> $textBoundary = 'alt-' . $boundary; <add> } <add> <add> if ($this->_textMessage) { <add> if ($multiPart) { <add> $msg[] = '--' . $textBoundary; <add> $msg[] = 'Content-Type: text/plain; charset=' . $this->getContentTypeCharset(); <add> $msg[] = 'Content-Transfer-Encoding: ' . $this->getContentTransferEncoding(); <add> $msg[] = ''; <add> } <add> $content = explode("\n", $this->_textMessage); <add> $msg = array_merge($msg, $content); <add> $msg[] = ''; <add> $msg[] = ''; <add> } <add> <add> if ($this->_htmlMessage) { <add> if ($multiPart) { <add> $msg[] = '--' . $textBoundary; <add> $msg[] = 'Content-Type: text/html; charset=' . $this->getContentTypeCharset(); <add> $msg[] = 'Content-Transfer-Encoding: ' . $this->getContentTransferEncoding(); <add> $msg[] = ''; <add> } <add> $content = explode("\n", $this->_htmlMessage); <add> $msg = array_merge($msg, $content); <add> $msg[] = ''; <add> $msg[] = ''; <add> } <add> <add> if ($textBoundary !== $relBoundary) { <add> $msg[] = '--' . $textBoundary . '--'; <add> $msg[] = ''; <add> } <add> <add> if ($hasInlineAttachments) { <add> $attachments = $this->attachInlineFiles($relBoundary); <add> $msg = array_merge($msg, $attachments); <add> $msg[] = ''; <add> $msg[] = '--' . $relBoundary . '--'; <add> $msg[] = ''; <add> } <add> <add> if ($hasAttachments) { <add> $attachments = $this->attachFiles($boundary); <add> $msg = array_merge($msg, $attachments); <add> } <add> if ($hasAttachments || $hasMultipleTypes) { <add> $msg[] = ''; <add> $msg[] = '--' . $boundary . '--'; <add> $msg[] = ''; <add> } <add> <add> return $msg; <add> } <add> <add> /** <add> * Attach non-embedded files by adding file contents inside boundaries. <add> * <add> * @param string|null $boundary Boundary to use. If null, will default to $this->boundary <add> * @return array An array of lines to add to the message <add> */ <add> protected function attachFiles(?string $boundary = null): array <add> { <add> if ($boundary === null) { <add> $boundary = $this->_boundary; <add> } <add> <add> $msg = []; <add> foreach ($this->_attachments as $filename => $fileInfo) { <add> if (!empty($fileInfo['contentId'])) { <add> continue; <add> } <add> $data = $fileInfo['data'] ?? $this->_readFile($fileInfo['file']); <add> $hasDisposition = ( <add> !isset($fileInfo['contentDisposition']) || <add> $fileInfo['contentDisposition'] <add> ); <add> $part = new FormDataPart('', $data, ''); <add> <add> if ($hasDisposition) { <add> $part->disposition('attachment'); <add> $part->filename($filename); <add> } <add> $part->transferEncoding('base64'); <add> $part->type($fileInfo['mimetype']); <add> <add> $msg[] = '--' . $boundary; <add> $msg[] = (string)$part; <add> $msg[] = ''; <add> } <add> <add> return $msg; <add> } <add> <add> /** <add> * Attach inline/embedded files to the message. <add> * <add> * @param string|null $boundary Boundary to use. If null, will default to $this->_boundary <add> * @return array An array of lines to add to the message <add> */ <add> protected function attachInlineFiles(?string $boundary = null): array <add> { <add> if ($boundary === null) { <add> $boundary = $this->_boundary; <add> } <add> <add> $msg = []; <add> foreach ($this->getAttachments() as $filename => $fileInfo) { <add> if (empty($fileInfo['contentId'])) { <add> continue; <add> } <add> $data = $fileInfo['data'] ?? $this->_readFile($fileInfo['file']); <add> <add> $msg[] = '--' . $boundary; <add> $part = new FormDataPart('', $data, 'inline'); <add> $part->type($fileInfo['mimetype']); <add> $part->transferEncoding('base64'); <add> $part->contentId($fileInfo['contentId']); <add> $part->filename($filename); <add> $msg[] = (string)$part; <add> $msg[] = ''; <add> } <add> <add> return $msg; <add> } <add> <ide> /** <ide> * Sets priority. <ide> * <ide> public function setConfig(array $config): self <ide> /** <ide> * Set message content. <ide> * <del> * @param array $content Content array with keys: <del> * - `textMessage` <del> * - `htmlMessage` <del> * - `boundary` <del> * - `message` <add> * @param string $content Content. <add> * @param string $type Content type. Valid types are: <add> * Message::MESSAGE_TEXT, Message::MESSAGE_HTML <ide> * @return $this <ide> */ <del> public function setContent(array $content) <add> public function setBody(string $content, string $type = self::MESSAGE_TEXT) <ide> { <del> $this->_message = $content['message']; <del> $this->_boundary = $content['boundary']; <del> $this->_textMessage = $content['textMessage']; <del> $this->_htmlMessage = $content['htmlMessage']; <add> $content = str_replace(["\r\n", "\r"], "\n", $content); <add> $content = $this->encodeString($content, $this->getCharset()); <add> $content = $this->wrap($content); <add> $content = implode("\n", $content); <add> $content = rtrim($content, "\n"); <add> <add> $property = "_{$type}Message"; <add> $this->$property = $content; <add> <add> $this->_boundary = null; <add> $this->_message = []; <ide> <ide> return $this; <ide> } <ide> <add> /** <add> * Translates a string for one charset to another if the App.encoding value <add> * differs and the mb_convert_encoding function exists <add> * <add> * @param string $text The text to be converted <add> * @param string $charset the target encoding <add> * @return string <add> */ <add> protected function encodeString(string $text, string $charset): string <add> { <add> if ($this->_appCharset === $charset) { <add> return $text; <add> } <add> <add> return mb_convert_encoding($text, $charset, $this->_appCharset); <add> } <add> <add> /** <add> * Wrap the message to follow the RFC 2822 - 2.1.1 <add> * <add> * @param string|null $message Message to wrap <add> * @param int $wrapLength The line length <add> * @return array Wrapped message <add> */ <add> protected function wrap(?string $message = null, int $wrapLength = self::LINE_LENGTH_MUST): array <add> { <add> if ($message === null || strlen($message) === 0) { <add> return ['']; <add> } <add> $message = str_replace(["\r\n", "\r"], "\n", $message); <add> $lines = explode("\n", $message); <add> $formatted = []; <add> $cut = ($wrapLength === static::LINE_LENGTH_MUST); <add> <add> foreach ($lines as $line) { <add> if (empty($line) && $line !== '0') { <add> $formatted[] = ''; <add> continue; <add> } <add> if (strlen($line) < $wrapLength) { <add> $formatted[] = $line; <add> continue; <add> } <add> if (!preg_match('/<[a-z]+.*>/i', $line)) { <add> $formatted = array_merge( <add> $formatted, <add> explode("\n", Text::wordWrap($line, $wrapLength, "\n", $cut)) <add> ); <add> continue; <add> } <add> <add> $tagOpen = false; <add> $tmpLine = $tag = ''; <add> $tmpLineLength = 0; <add> for ($i = 0, $count = strlen($line); $i < $count; $i++) { <add> $char = $line[$i]; <add> if ($tagOpen) { <add> $tag .= $char; <add> if ($char === '>') { <add> $tagLength = strlen($tag); <add> if ($tagLength + $tmpLineLength < $wrapLength) { <add> $tmpLine .= $tag; <add> $tmpLineLength += $tagLength; <add> } else { <add> if ($tmpLineLength > 0) { <add> $formatted = array_merge( <add> $formatted, <add> explode("\n", Text::wordWrap(trim($tmpLine), $wrapLength, "\n", $cut)) <add> ); <add> $tmpLine = ''; <add> $tmpLineLength = 0; <add> } <add> if ($tagLength > $wrapLength) { <add> $formatted[] = $tag; <add> } else { <add> $tmpLine = $tag; <add> $tmpLineLength = $tagLength; <add> } <add> } <add> $tag = ''; <add> $tagOpen = false; <add> } <add> continue; <add> } <add> if ($char === '<') { <add> $tagOpen = true; <add> $tag = '<'; <add> continue; <add> } <add> if ($char === ' ' && $tmpLineLength >= $wrapLength) { <add> $formatted[] = $tmpLine; <add> $tmpLineLength = 0; <add> continue; <add> } <add> $tmpLine .= $char; <add> $tmpLineLength++; <add> if ($tmpLineLength === $wrapLength) { <add> $nextChar = $line[$i + 1]; <add> if ($nextChar === ' ' || $nextChar === '<') { <add> $formatted[] = trim($tmpLine); <add> $tmpLine = ''; <add> $tmpLineLength = 0; <add> if ($nextChar === ' ') { <add> $i++; <add> } <add> } else { <add> $lastSpace = strrpos($tmpLine, ' '); <add> if ($lastSpace === false) { <add> continue; <add> } <add> $formatted[] = trim(substr($tmpLine, 0, $lastSpace)); <add> $tmpLine = substr($tmpLine, $lastSpace + 1); <add> <add> $tmpLineLength = strlen($tmpLine); <add> } <add> } <add> } <add> if (!empty($tmpLine)) { <add> $formatted[] = $tmpLine; <add> } <add> } <add> $formatted[] = ''; <add> <add> return $formatted; <add> } <add> <ide> /** <ide> * Reset all the internal variables to be able to send out a new email. <ide> * <ide> public function reset(): self <ide> $this->headerCharset = null; <ide> $this->transferEncoding = null; <ide> $this->_attachments = []; <del> $this->_profile = []; <ide> $this->_emailPattern = self::EMAIL_PATTERN; <ide> <ide> return $this; <ide><path>src/Mailer/Renderer.php <ide> class Renderer <ide> { <ide> use ViewVarsTrait; <ide> <del> /** <del> * Line length - no should more - RFC 2822 - 2.1.1 <del> * <del> * @var int <del> */ <del> public const LINE_LENGTH_SHOULD = 78; <del> <del> /** <del> * Line length - no must more - RFC 2822 - 2.1.1 <del> * <del> * @var int <del> */ <del> public const LINE_LENGTH_MUST = 998; <del> <ide> /** <ide> * Constant for folder name containing email templates. <ide> * <ide> * @var string <ide> */ <ide> public const TEMPLATE_FOLDER = 'email'; <ide> <del> /** <del> * The application wide charset, used to encode headers and body <del> * <del> * @var string|null <del> */ <del> protected $appCharset; <del> <del> /** <del> * If set, boundary to use for multipart mime messages <del> * <del> * @var string <del> */ <del> protected $boundary; <del> <del> /** <del> * Email instance. <del> * <del> * @var \Cake\Mailer\Email <del> */ <del> protected $email; <del> <del> /** <del> * Constructor. <del> * <del> * @param string|null $appCharset Application's character set. <del> */ <del> public function __construct(?string $appCharset = null) <del> { <del> $this->appCharset = $appCharset ?: Configure::read('App.encoding'); <del> } <del> <del> /** <del> * Render the body of the email. <del> * <del> * @param \Cake\Mailer\Email $email Email instance. <del> * @param string|null $content Content to render. <del> * @return array Email Body ready to be sent <del> */ <del> public function render(Email $email, ?string $content = null): array <del> { <del> $rendered = $this->renderTemplates($email, $content); <del> <del> $this->email = $email; <del> $textMessage = $htmlMessage = ''; <del> <del> $this->createBoundary(); <del> $msg = []; <del> <del> $contentIds = array_filter((array)Hash::extract($email->getAttachments(), '{s}.contentId')); <del> $hasInlineAttachments = count($contentIds) > 0; <del> $hasAttachments = !empty($email->getAttachments()); <del> $hasMultipleTypes = count($rendered) > 1; <del> $multiPart = ($hasAttachments || $hasMultipleTypes); <del> <del> $boundary = $relBoundary = $textBoundary = $this->boundary; <del> <del> if ($hasInlineAttachments) { <del> $msg[] = '--' . $boundary; <del> $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"'; <del> $msg[] = ''; <del> $relBoundary = $textBoundary = 'rel-' . $boundary; <del> } <del> <del> if ($hasMultipleTypes && $hasAttachments) { <del> $msg[] = '--' . $relBoundary; <del> $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"'; <del> $msg[] = ''; <del> $textBoundary = 'alt-' . $boundary; <del> } <del> <del> if (isset($rendered[Email::MESSAGE_TEXT])) { <del> if ($multiPart) { <del> $msg[] = '--' . $textBoundary; <del> $msg[] = 'Content-Type: text/plain; charset=' . $email->getContentTypeCharset(); <del> $msg[] = 'Content-Transfer-Encoding: ' . $email->getContentTransferEncoding(); <del> $msg[] = ''; <del> } <del> $textMessage = $rendered[Email::MESSAGE_TEXT]; <del> $content = explode("\n", $textMessage); <del> $msg = array_merge($msg, $content); <del> $msg[] = ''; <del> $msg[] = ''; <del> } <del> <del> if (isset($rendered[Email::MESSAGE_HTML])) { <del> if ($multiPart) { <del> $msg[] = '--' . $textBoundary; <del> $msg[] = 'Content-Type: text/html; charset=' . $email->getContentTypeCharset(); <del> $msg[] = 'Content-Transfer-Encoding: ' . $email->getContentTransferEncoding(); <del> $msg[] = ''; <del> } <del> $htmlMessage = $rendered[Email::MESSAGE_HTML]; <del> $content = explode("\n", $htmlMessage); <del> $msg = array_merge($msg, $content); <del> $msg[] = ''; <del> $msg[] = ''; <del> } <del> <del> if ($textBoundary !== $relBoundary) { <del> $msg[] = '--' . $textBoundary . '--'; <del> $msg[] = ''; <del> } <del> <del> if ($hasInlineAttachments) { <del> $attachments = $this->attachInlineFiles($relBoundary); <del> $msg = array_merge($msg, $attachments); <del> $msg[] = ''; <del> $msg[] = '--' . $relBoundary . '--'; <del> $msg[] = ''; <del> } <del> <del> if ($hasAttachments) { <del> $attachments = $this->attachFiles($boundary); <del> $msg = array_merge($msg, $attachments); <del> } <del> if ($hasAttachments || $hasMultipleTypes) { <del> $msg[] = ''; <del> $msg[] = '--' . $boundary . '--'; <del> $msg[] = ''; <del> } <del> <del> return [ <del> 'message' => $msg, <del> 'boundary' => $boundary, <del> 'textMessage' => $textMessage, <del> 'htmlMessage' => $htmlMessage, <del> ]; <del> } <del> <del> /** <del> * Translates a string for one charset to another if the App.encoding value <del> * differs and the mb_convert_encoding function exists <del> * <del> * @param string $text The text to be converted <del> * @param string $charset the target encoding <del> * @return string <del> */ <del> protected function encodeString(string $text, string $charset): string <del> { <del> if ($this->appCharset === $charset) { <del> return $text; <del> } <del> <del> return mb_convert_encoding($text, $charset, $this->appCharset); <del> } <del> <del> /** <del> * Wrap the message to follow the RFC 2822 - 2.1.1 <del> * <del> * @param string|null $message Message to wrap <del> * @param int $wrapLength The line length <del> * @return array Wrapped message <del> */ <del> protected function wrap(?string $message = null, int $wrapLength = self::LINE_LENGTH_MUST): array <del> { <del> if ($message === null || strlen($message) === 0) { <del> return ['']; <del> } <del> $message = str_replace(["\r\n", "\r"], "\n", $message); <del> $lines = explode("\n", $message); <del> $formatted = []; <del> $cut = ($wrapLength === static::LINE_LENGTH_MUST); <del> <del> foreach ($lines as $line) { <del> if (empty($line) && $line !== '0') { <del> $formatted[] = ''; <del> continue; <del> } <del> if (strlen($line) < $wrapLength) { <del> $formatted[] = $line; <del> continue; <del> } <del> if (!preg_match('/<[a-z]+.*>/i', $line)) { <del> $formatted = array_merge( <del> $formatted, <del> explode("\n", Text::wordWrap($line, $wrapLength, "\n", $cut)) <del> ); <del> continue; <del> } <del> <del> $tagOpen = false; <del> $tmpLine = $tag = ''; <del> $tmpLineLength = 0; <del> for ($i = 0, $count = strlen($line); $i < $count; $i++) { <del> $char = $line[$i]; <del> if ($tagOpen) { <del> $tag .= $char; <del> if ($char === '>') { <del> $tagLength = strlen($tag); <del> if ($tagLength + $tmpLineLength < $wrapLength) { <del> $tmpLine .= $tag; <del> $tmpLineLength += $tagLength; <del> } else { <del> if ($tmpLineLength > 0) { <del> $formatted = array_merge( <del> $formatted, <del> explode("\n", Text::wordWrap(trim($tmpLine), $wrapLength, "\n", $cut)) <del> ); <del> $tmpLine = ''; <del> $tmpLineLength = 0; <del> } <del> if ($tagLength > $wrapLength) { <del> $formatted[] = $tag; <del> } else { <del> $tmpLine = $tag; <del> $tmpLineLength = $tagLength; <del> } <del> } <del> $tag = ''; <del> $tagOpen = false; <del> } <del> continue; <del> } <del> if ($char === '<') { <del> $tagOpen = true; <del> $tag = '<'; <del> continue; <del> } <del> if ($char === ' ' && $tmpLineLength >= $wrapLength) { <del> $formatted[] = $tmpLine; <del> $tmpLineLength = 0; <del> continue; <del> } <del> $tmpLine .= $char; <del> $tmpLineLength++; <del> if ($tmpLineLength === $wrapLength) { <del> $nextChar = $line[$i + 1]; <del> if ($nextChar === ' ' || $nextChar === '<') { <del> $formatted[] = trim($tmpLine); <del> $tmpLine = ''; <del> $tmpLineLength = 0; <del> if ($nextChar === ' ') { <del> $i++; <del> } <del> } else { <del> $lastSpace = strrpos($tmpLine, ' '); <del> if ($lastSpace === false) { <del> continue; <del> } <del> $formatted[] = trim(substr($tmpLine, 0, $lastSpace)); <del> $tmpLine = substr($tmpLine, $lastSpace + 1); <del> <del> $tmpLineLength = strlen($tmpLine); <del> } <del> } <del> } <del> if (!empty($tmpLine)) { <del> $formatted[] = $tmpLine; <del> } <del> } <del> $formatted[] = ''; <del> <del> return $formatted; <del> } <del> <del> /** <del> * Create unique boundary identifier <del> * <del> * @return void <del> */ <del> protected function createBoundary(): void <del> { <del> if ($this->email->getAttachments() || $this->email->getEmailFormat() === Email::MESSAGE_BOTH) { <del> $this->boundary = md5(Security::randomBytes(16)); <del> } <del> } <del> <del> /** <del> * Attach non-embedded files by adding file contents inside boundaries. <del> * <del> * @param string|null $boundary Boundary to use. If null, will default to $this->boundary <del> * @return array An array of lines to add to the message <del> */ <del> protected function attachFiles(?string $boundary = null): array <del> { <del> if ($boundary === null) { <del> $boundary = $this->boundary; <del> } <del> <del> $msg = []; <del> foreach ($this->email->getAttachments() as $filename => $fileInfo) { <del> if (!empty($fileInfo['contentId'])) { <del> continue; <del> } <del> $data = $fileInfo['data'] ?? $this->readFile($fileInfo['file']); <del> $hasDisposition = ( <del> !isset($fileInfo['contentDisposition']) || <del> $fileInfo['contentDisposition'] <del> ); <del> $part = new FormDataPart('', $data, ''); <del> <del> if ($hasDisposition) { <del> $part->disposition('attachment'); <del> $part->filename($filename); <del> } <del> $part->transferEncoding('base64'); <del> $part->type($fileInfo['mimetype']); <del> <del> $msg[] = '--' . $boundary; <del> $msg[] = (string)$part; <del> $msg[] = ''; <del> } <del> <del> return $msg; <del> } <del> <del> /** <del> * Read the file contents and return a base64 version of the file contents. <del> * <del> * @param string $path The absolute path to the file to read. <del> * @return string File contents in base64 encoding <del> */ <del> protected function readFile(string $path): string <del> { <del> return chunk_split(base64_encode((string)file_get_contents($path))); <del> } <del> <del> /** <del> * Attach inline/embedded files to the message. <del> * <del> * @param string|null $boundary Boundary to use. If null, will default to $this->boundary <del> * @return array An array of lines to add to the message <del> */ <del> protected function attachInlineFiles(?string $boundary = null): array <del> { <del> if ($boundary === null) { <del> $boundary = $this->boundary; <del> } <del> <del> $msg = []; <del> foreach ($this->email->getAttachments() as $filename => $fileInfo) { <del> if (empty($fileInfo['contentId'])) { <del> continue; <del> } <del> $data = $fileInfo['data'] ?? $this->readFile($fileInfo['file']); <del> <del> $msg[] = '--' . $boundary; <del> $part = new FormDataPart('', $data, 'inline'); <del> $part->type($fileInfo['mimetype']); <del> $part->transferEncoding('base64'); <del> $part->contentId($fileInfo['contentId']); <del> $part->filename($filename); <del> $msg[] = (string)$part; <del> $msg[] = ''; <del> } <del> <del> return $msg; <del> } <del> <del> /** <del> * Gets the text body types that are in this email message <del> * <del> * @param \Cake\Mailer\Email $email Email instance. <del> * @return array Array of types. Valid types are Email::MESSAGE_TEXT and Email::MESSAGE_HTML <del> */ <del> protected function getTypes(Email $email): array <del> { <del> $format = $email->getEmailFormat(); <del> <del> $types = [$format]; <del> if ($format === Email::MESSAGE_BOTH) { <del> $types = [Email::MESSAGE_HTML, Email::MESSAGE_TEXT]; <del> } <del> <del> return $types; <del> } <del> <ide> /** <ide> * Build and set all the view properties needed to render the templated emails. <ide> * If there is no template set, the $content will be returned in a hash <ide> * of the text content types for the email. <ide> * <del> * @param \Cake\Mailer\Email $email Email instance. <del> * @param string|null $content The content passed in from send() in most cases. <del> * @return array The rendered content with html and text keys. <add> * @param string|null $content The content. <add> * @return array The rendered content with "html" and/or "text" keys. <ide> */ <del> public function renderTemplates(Email $email, ?string $content = null): array <add> public function getContent(?string $content = null, array $types = []): array <ide> { <del> $types = $this->getTypes($email); <ide> $rendered = []; <ide> $template = $this->viewBuilder()->getTemplate(); <ide> if (empty($template)) { <ide> foreach ($types as $type) { <del> $content = str_replace(["\r\n", "\r"], "\n", $content); <del> $rendered[$type] = $this->encodeString($content, $email->getCharset()); <del> $rendered[$type] = $this->wrap($rendered[$type]); <del> $rendered[$type] = implode("\n", $rendered[$type]); <del> $rendered[$type] = rtrim($rendered[$type], "\n"); <add> $rendered[$type] = (string)$content; <ide> } <ide> <ide> return $rendered; <ide> public function renderTemplates(Email $email, ?string $content = null): array <ide> $view->setTemplatePath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type); <ide> $view->setLayoutPath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type); <ide> <del> $content = $view->render(); <del> $content = str_replace(["\r\n", "\r"], "\n", $content); <del> $rendered[$type] = $this->encodeString($content, $email->getCharset()); <del> $rendered[$type] = $this->wrap($rendered[$type]); <del> $rendered[$type] = implode("\n", $rendered[$type]); <del> $rendered[$type] = rtrim($rendered[$type], "\n"); <add> $rendered[$type] = (string)$view->render(); <ide> } <ide> <ide> return $rendered; <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Log\Log; <ide> use Cake\Mailer\Email; <del>use Cake\Mailer\Renderer; <add>use Cake\Mailer\Message; <ide> use Cake\Mailer\TransportFactory; <ide> use Cake\TestSuite\TestCase; <ide> use Exception; <ide> protected function _getEmailByNewStyleCharset($charset, $headerCharset) <ide> */ <ide> public function testWrapLongLine() <ide> { <del> $message = '<a href="http://cakephp.org">' . str_repeat('x', Renderer::LINE_LENGTH_MUST) . '</a>'; <add> $message = '<a href="http://cakephp.org">' . str_repeat('x', Message::LINE_LENGTH_MUST) . '</a>'; <ide> <ide> $this->Email->reset(); <ide> $this->Email->setTransport('debug'); <ide> public function testWrapLongLine() <ide> $this->Email->setSubject('Wordwrap Test'); <ide> $this->Email->setProfile(['empty']); <ide> $result = $this->Email->send($message); <del> $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('x', Renderer::LINE_LENGTH_MUST - 26) . "\r\n" . <add> $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('x', Message::LINE_LENGTH_MUST - 26) . "\r\n" . <ide> str_repeat('x', 26) . "\r\n</a>\r\n\r\n"; <ide> $this->assertEquals($expected, $result['message']); <ide> $this->assertLineLengths($result['message']); <ide> <ide> $str1 = 'a '; <ide> $str2 = ' b'; <ide> $length = strlen($str1) + strlen($str2); <del> $message = $str1 . str_repeat('x', Renderer::LINE_LENGTH_MUST - $length - 1) . $str2; <add> $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length - 1) . $str2; <ide> <ide> $result = $this->Email->send($message); <ide> $expected = "{$message}\r\n\r\n"; <ide> $this->assertEquals($expected, $result['message']); <ide> $this->assertLineLengths($result['message']); <ide> <del> $message = $str1 . str_repeat('x', Renderer::LINE_LENGTH_MUST - $length) . $str2; <add> $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length) . $str2; <ide> <ide> $result = $this->Email->send($message); <ide> $expected = "{$message}\r\n\r\n"; <ide> $this->assertEquals($expected, $result['message']); <ide> $this->assertLineLengths($result['message']); <ide> <del> $message = $str1 . str_repeat('x', Renderer::LINE_LENGTH_MUST - $length + 1) . $str2; <add> $message = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1) . $str2; <ide> <ide> $result = $this->Email->send($message); <del> $expected = $str1 . str_repeat('x', Renderer::LINE_LENGTH_MUST - $length + 1) . sprintf("\r\n%s\r\n\r\n", trim($str2)); <add> $expected = $str1 . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1) . sprintf("\r\n%s\r\n\r\n", trim($str2)); <ide> $this->assertEquals($expected, $result['message']); <ide> $this->assertLineLengths($result['message']); <ide> } <ide> public function testWrapWithTagsAcrossLines() <ide> style="font-weight: bold">The tag is across multiple lines</th> <ide> </table> <ide> HTML; <del> $message = $str . str_repeat('x', Renderer::LINE_LENGTH_MUST + 1); <add> $message = $str . str_repeat('x', Message::LINE_LENGTH_MUST + 1); <ide> <ide> $this->Email->reset(); <ide> $this->Email->setTransport('debug'); <ide> public function testWrapIncludeLessThanSign() <ide> { <ide> $str = 'foo<bar'; <ide> $length = strlen($str); <del> $message = $str . str_repeat('x', Renderer::LINE_LENGTH_MUST - $length + 1); <add> $message = $str . str_repeat('x', Message::LINE_LENGTH_MUST - $length + 1); <ide> <ide> $this->Email->reset(); <ide> $this->Email->setTransport('debug'); <ide> public function assertLineLengths($message) <ide> $lines = explode("\r\n", $message); <ide> foreach ($lines as $line) { <ide> $this->assertTrue( <del> strlen($line) <= Renderer::LINE_LENGTH_MUST, <del> 'Line length exceeds the max. limit of Renderer::LINE_LENGTH_MUST' <add> strlen($line) <= Message::LINE_LENGTH_MUST, <add> 'Line length exceeds the max. limit of Message::LINE_LENGTH_MUST' <ide> ); <ide> } <ide> } <add><path>tests/TestCase/Mailer/MessageTest.php <del><path>tests/TestCase/Mailer/RendererTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Mailer; <ide> <del>use Cake\Mailer\Renderer; <add>use Cake\Mailer\Message; <ide> use Cake\TestSuite\TestCase; <del>use TestApp\Renderer\TestRenderer; <add>use TestApp\Mailer\TestMessage; <ide> <ide> /** <del> * RendererTest class <add> * MessageTest class <ide> */ <del>class RendererTest extends TestCase <add>class MessageTest extends TestCase <ide> { <ide> /** <ide> * testWrap method <ide> class RendererTest extends TestCase <ide> */ <ide> public function testWrap() <ide> { <del> $renderer = new TestRenderer(); <add> $renderer = new TestMessage(); <ide> <ide> $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci,', <ide> 'non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.', <ide> public function testWrap() <ide> $this->assertSame($expected, $result); <ide> <ide> $text = 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan amet.'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis', <ide> 'orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan', <ide> public function testWrap() <ide> $this->assertSame($expected, $result); <ide> <ide> $text = '<p>Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Donec ac turpis orci, non <b>commodo</b> odio. <br /> Morbi nibh nisi, vehicula pellentesque accumsan amet.<hr></p>'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> '<p>Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Donec ac', <ide> 'turpis orci, non <b>commodo</b> odio. <br /> Morbi nibh nisi, vehicula', <ide> public function testWrap() <ide> $this->assertSame($expected, $result); <ide> <ide> $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac <a href="http://cakephp.org">turpis</a> orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac', <ide> '<a href="http://cakephp.org">turpis</a> orci, non commodo odio. Morbi nibh', <ide> public function testWrap() <ide> $this->assertSame($expected, $result); <ide> <ide> $text = 'Lorem ipsum <a href="http://www.cakephp.org/controller/action/param1/param2" class="nice cool fine amazing awesome">ok</a>'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> 'Lorem ipsum', <ide> '<a href="http://www.cakephp.org/controller/action/param1/param2" class="nice cool fine amazing awesome">', <ide> public function testWrap() <ide> $this->assertSame($expected, $result); <ide> <ide> $text = 'Lorem ipsum withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite ok.'; <del> $result = $renderer->doWrap($text, Renderer::LINE_LENGTH_SHOULD); <add> $result = $renderer->doWrap($text, Message::LINE_LENGTH_SHOULD); <ide> $expected = [ <ide> 'Lorem ipsum', <ide> 'withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite', <ide><path>tests/test_app/TestApp/Mailer/TestMessage.php <ide> public function decode($text) <ide> { <ide> return $this->_decode($text); <ide> } <add> <add> /** <add> * Wrap to protected method <add> * <add> * @param string $text <add> * @param int $length <add> * @return array <add> */ <add> public function doWrap($text, $length = Message::LINE_LENGTH_MUST) <add> { <add> return $this->wrap($text, $length); <add> } <ide> } <ide><path>tests/test_app/TestApp/Renderer/TestRenderer.php <del><?php <del>declare(strict_types=1); <del>namespace TestApp\Renderer; <del> <del>use Cake\Mailer\Renderer; <del> <del>class TestRenderer extends Renderer <del>{ <del> /** <del> * Wrap to protected method <del> * <del> * @param string $text <del> * @param int $length <del> * @return array <del> */ <del> public function doWrap($text, $length = Renderer::LINE_LENGTH_MUST) <del> { <del> return $this->wrap($text, $length); <del> } <del>} <ide><path>tests/test_app/templates/email/html/html.php <ide> <?php <del>use Cake\Mailer\Renderer; <add>use Cake\Mailer\Message; <ide> ?> <ide> <h1>HTML Ipsum Presents</h1><p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p><h2>Header Level 2</h2><ol><li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li><li>Aliquam tincidunt mauris eu risus.</li></ol><blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote><h3>Header Level 3</h3><ul><li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li><li>Aliquam tincidunt mauris eu risus.</li></ul> <ide> <pre><code> <ide> }</code></pre> <ide> <table> <ide> <th align="right" valign="top" <del> style="font-weight: bold">The tag is across multiple lines - <?= str_repeat('x', Renderer::LINE_LENGTH_MUST); ?></th> <add> style="font-weight: bold">The tag is across multiple lines - <?= str_repeat('x', Message::LINE_LENGTH_MUST); ?></th> <ide> </table> <del><p>Some more <?= str_repeat('x', Renderer::LINE_LENGTH_MUST); ?> <b>Bold</b> test.</p> <add><p>Some more <?= str_repeat('x', Message::LINE_LENGTH_MUST); ?> <b>Bold</b> test.</p>
8
Text
Text
use case-sensitive in the example
cb62f16164da70446baa002ef5a0eda95f7a5b93
<ide><path>doc/api/process.md <ide> present. <ide> <ide> ```js <ide> const data = process.report.getReport(); <del>console.log(data.header.nodeJsVersion); <add>console.log(data.header.nodejsVersion); <ide> <ide> // Similar to process.report.writeReport() <ide> const fs = require('fs');
1
Python
Python
add missing imports
18c859500b4797677a2adde351f2047b20b161cc
<ide><path>spacy/lang/pl/tokenizer_exceptions.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ..symbols import ORTH, LEMMA, POS <add>from ...symbols import ORTH, LEMMA, POS, ADV, ADJ, NOUN <ide> <ide> <ide> _exc = {}
1
Text
Text
add extra material
f59395a0c043bef09311a2d6cd6633ad9301581c
<ide><path>guide/chinese/android-development/index.md <ide> localeTitle: Android安卓开发 <ide> --- <ide> # Android安卓开发 <ide> <add>Android 簡介 <add>如要瞭解應用程式的運作方式,請參閱應用程式基礎知識。 <add> <add>如果想立即編寫程式碼,請參閱建立您的第一個應用程式。 <add> <add>Android 提供內容豐富的應用程式架構,可讓您在 Java 語言環境中建置適用於行動裝置的新穎應用程式和遊戲。 您可以參閱左側導覽區所列的文件,進一步瞭解如何使用 Android 的各種 API 建置應用程式。 <add> <add>如果您是剛開始接觸 Android 開發環境,請務必詳閱下列有關 Android 應用程式架構的基本概念: <add> <add>應用程式可提供多個進入點 <add>Android 應用程式是由許多不同元件建置而成,應用程式可個別呼叫每個元件。 例如,「Activity」可在單一畫面中顯示使用者介面,而「服務」則個別可在背景中執行作業。 <add> <add>您可以透過某個元件使用「意圖」啟動另一個元件。您甚至可以啟動其他應用程式中的元件,例如啟動地圖應用程式的 Activity 來顯示地址。 這個模型可為單一應用程式提供多個進入點,還能讓任何應用程式針對其他應用程式可能呼叫的動作,以使用者設定的「預設值」運作。 <add> <add>瞭解詳情: <add> <add>應用程式基礎知識 <add>意圖和意圖篩選器 <add>Activity <add>應用程式會針對不同裝置進行調整 <add>Android 提供的應用程式架構可視情況進行調整,讓您能夠針對不同的裝置設定提供專屬資源。 例如,您可以針對不同的螢幕大小建立各種 XML 版面配置檔案,藉此讓系統根據目前裝置的螢幕大小決定要套用的版面配置設定。 <add> <add>如果有應用程式功能需要特定硬體 (例如相機) 才能運作,您可以在執行階段查詢裝置功能的可用性。 此外,您還可以視需要宣告您的應用程式所需的功能,以便讓 Google Play 商店等應用程式市集禁止使用者在不支援相關功能的裝置上安裝您的應用程式。 <add> <ide> Android应用程序可以成为进入编程世界的一种有趣的方式。官方程序员可以使用Java,Kotlin或C ++为Android开发,虽然可能存在API限制,但使用工具,开发人员可以使用大量语言,包括JavaScript,C或汇编,并且可能性无穷无尽。 <ide> <ide> 从简单的游戏和实用程序应用程序到成熟的音乐播放器,有很多机会可以用Android创建有意义的东西。 Android开发人员社区很普遍,在线文档和资源很容易找到,因此您可以解决您遇到的任何问题。
1
Python
Python
fix import of utc
5717e853dbb9b1465cdfd5b7400db7fc844fa04f
<ide><path>rest_framework/compat.py <ide> def set_many(instance, field, value): <ide> <ide> try: <ide> # A `utc` instance is available in Django 1.11+ <del> from django.timezone import utc <add> from django.utils.timezone import utc <ide> except ImportError: <ide> # A `UTC` class is available in older versions <del> from django.timezone import UTC <add> from django.utils.timezone import UTC <ide> utc = UTC()
1