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
Text
Text
update mapbox link in learning resources
fe3a1accae8718f5fa6a40651773f8a8ec6837f7
<ide><path>docs/introduction/LearningResources.md <ide> _Patterns and practices for structuring larger Redux applications_ <ide> An excellent slideshow with a wide variety of tips and suggestions, including keeping action creators simple and data manipulation in reducers, abstracting away API calls, avoiding spreading props, and more. <ide> <ide> - **Redux for state management in large web apps** <br/> <del> https://www.mapbox.com/blog/redux-for-state-management-in-large-web-apps/ <br/> <add> https://blog.mapbox.com/redux-for-state-management-in-large-web-apps-c7f3fab3ce9b <br/> <ide> Excellent discussion and examples of idiomatic Redux architecture, and how Mapbox applies those approaches to their Mapbox Studio application. <ide> <ide> ## Apps and Examples
1
Text
Text
update instructions on testing
fe4ca9143c984997fd6e9c1ef253c4346f5064e6
<ide><path>docs/how-to-work-on-coding-challenges.md <ide> function myFunc() { <ide> <ide> ## Testing Challenges <ide> <del>Before you [create a pull request](how-to-open-a-pull-request.md) for your changes, you need to validate that the changes you have made do not inadvertently cause problems with the challenge. To test all challenges run `npm run test:curriculum`. To save time you can limit the tests to one challenge by performing the following steps: <add>Before you [create a pull request](how-to-open-a-pull-request.md) for your changes, you need to validate that the changes you have made do not inadvertently cause problems with the challenge. <ide> <del>1. In the `.env` file, set the environment variable `TEST_CHALLENGES_FOR_LANGS` to the language of the challenge(s) you need to test. The currently accepted values are `english`, `arabic`, `chinese`, `portuguese`, `russian` and `spanish`. <add>> [!WARNING] <add>> In the `.env` file, set the environment variable `TEST_CHALLENGES_FOR_LANGS` to the language of the challenge(s) you need to test. The currently accepted values are `english` and `chinese` for the language that you are working on <add>> <add>> This is set to test for `english` by default. <ide> <del>2. Switch to the `curriculum` directory: <add>1. To test all challenges run the below command from the root directory <ide> <ide> ``` <del> cd curriculum <del>``` <add>npm run test:curriculum <add>``` <ide> <del>3. Run the following for each challenge file for which you have changed any `testString`s or added solutions: <add>2. You can also test a block or a superblock of challenges with these commands <ide> <ide> ``` <del>npm run test -- -g 'the full English title of the challenge' <add>npm run test:curriculum --block='Basic HTML and HTML5' <add>``` <add> <ide> ``` <add>npm run test:curriculum --superblock=responsive-web-design <add>``` <add> <add>You are also able to test one challenge individually by performing the following steps: <add> <add>1. Switch to the `curriculum` directory: <add> <add> ``` <add> cd curriculum <add> ``` <add> <add>2. Run the following for each challenge file for which you have changed: <add> <add> ``` <add> npm run test -- -g 'the full English title of the challenge' <add> ``` <ide> <ide> Once you have verified that each challenge you've worked on passes the tests, [please create a pull request](https://github.com/freeCodeCamp/freeCodeCamp/blob/master/docs/how-to-open-a-pull-request.md). <ide>
1
Java
Java
fix typo in javadoc in abstracthandlermapping
c2f91765b401c2976fd802358e6453d0fad0d2fd
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java <ide> public void setInterceptors(Object... interceptors) { <ide> * determines the {@code CorsConfiguration} to use which is then further <ide> * {@link CorsConfiguration#combine(CorsConfiguration) combined} with the <ide> * {@code CorsConfiguration} for the selected handler. <del> * <p>This is mutually exclusie with <add> * <p>This is mutually exclusive with <ide> * {@link #setCorsConfigurationSource(CorsConfigurationSource)}. <ide> * @since 4.2 <ide> * @see #setCorsProcessor(CorsProcessor) <ide> public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurati <ide> * {@code CorsConfiguration} determined by the source is <ide> * {@link CorsConfiguration#combine(CorsConfiguration) combined} with the <ide> * {@code CorsConfiguration} for the selected handler. <del> * <p>This is mutually exclusie with {@link #setCorsConfigurations(Map)}. <add> * <p>This is mutually exclusive with {@link #setCorsConfigurations(Map)}. <ide> * @since 5.1 <ide> * @see #setCorsProcessor(CorsProcessor) <ide> */
1
Javascript
Javascript
favor strict equality check
7652ae98296ed46220b5505f491afcb464d096bd
<ide><path>test/pummel/test-tls-connect-memleak.js <ide> tls.createServer({ <ide> <ide> const options = { rejectUnauthorized: false }; <ide> tls.connect(common.PORT, '127.0.0.1', options, function() { <del> assert(junk.length != 0); // keep reference alive <add> assert.notStrictEqual(junk.length, 0); // keep reference alive <ide> setTimeout(done, 10); <ide> global.gc(); <ide> });
1
PHP
PHP
fix cs errors
801a812195673ec86316f18b13feb33b1a1bb273
<ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php <ide> public function assertOutputContains(string $expected, string $message = ''): vo <ide> { <ide> $this->assertThat($expected, new ContentsContain($this->_out->messages(), 'output'), $message); <ide> } <add> <ide> /** <ide> * Asserts `stdout` does not contain expected output <ide> * <ide><path>src/TestSuite/EmailTrait.php <ide> public function assertMailCount(int $count, string $message = ''): void <ide> { <ide> $this->assertThat($count, new MailCount(), $message); <ide> } <add> <ide> /** <ide> * <ide> * Asserts that no emails were sent <ide><path>tests/TestCase/Core/Retry/CommandRetryTest.php <ide> public function testExceedAttempts() <ide> $this->expectExceptionMessage('this is failing'); <ide> $retry->run($action); <ide> } <add> <ide> /** <ide> * Test that the strategy is respected <ide> * <ide><path>tests/TestCase/Http/ClientTest.php <ide> public static function methodProvider() <ide> [Request::METHOD_TRACE], <ide> ]; <ide> } <add> <ide> /** <ide> * test simple POST request. <ide> * <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testConstructStringUrlIgnoreServer() <ide> $request = new ServerRequest(['url' => '/']); <ide> $this->assertSame('/', $request->getUri()->getPath()); <ide> } <add> <ide> /** <ide> * Test that querystring args provided in the URL string are parsed. <ide> * <ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function timeAgoEndProvider() <ide> ], <ide> ]; <ide> } <add> <ide> /** <ide> * test the timezone option for timeAgoInWords <ide> * <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testTransportTypeInvalid() <ide> $this->expectExceptionMessage('The value passed for the "$name" argument must be either a string, or an object, integer given.'); <ide> $this->Email->setTransport(123); <ide> } <add> <ide> /** <ide> * Test reading/writing configuration profiles. <ide> * <ide> public function testSendWithNoContentDispositionAttachments() <ide> $this->assertStringContainsString($expected, $result['message']); <ide> $this->assertStringContainsString('--' . $boundary . '--', $result['message']); <ide> } <add> <ide> /** <ide> * testSendWithLog method <ide> * <ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php <ide> public function testScopeCallable() <ide> $count = $table->childCount($table->get(1), false); <ide> $this->assertEquals(4, $count); <ide> } <add> <ide> /** <ide> * Tests the find('children') method <ide> * <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testNotMatchingForBelongsToManyWithoutQueryBuilder() <ide> <ide> $this->assertEquals($expected, $result); <ide> } <add> <ide> /** <ide> * Tests deep formatters get the right object type when applied in a beforeFind <ide> * <ide><path>tests/TestCase/Shell/Helper/TableHelperTest.php <ide> public function testOutputWithoutHeaderStyle() <ide> ]; <ide> $this->assertEquals($expected, $this->stub->messages()); <ide> } <add> <ide> /** <ide> * Test output with different header style <ide> * <ide><path>tests/TestCase/View/ViewVarsTraitTest.php <ide> public function testSetTwoParamCombined() <ide> $expected = ['one' => 'two', 'key' => 'val']; <ide> $this->assertEquals($expected, $this->subject->viewBuilder()->getVars()); <ide> } <add> <ide> /** <ide> * test that createView() updates viewVars of View instance on each call. <ide> *
11
Go
Go
move "info" to daemon/info.go
94715e8e643f0bc9aa57841b346f5196f75f0dc0
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <ide> "create": daemon.ContainerCreate, <ide> "delete": daemon.ContainerDestroy, <ide> "export": daemon.ContainerExport, <add> "info": daemon.CmdInfo, <ide> "kill": daemon.ContainerKill, <ide> "logs": daemon.ContainerLogs, <ide> "pause": daemon.ContainerPause, <ide><path>daemon/info.go <add>package daemon <add> <add>import ( <add> "os" <add> "runtime" <add> <add> "github.com/docker/docker/dockerversion" <add> "github.com/docker/docker/engine" <add> "github.com/docker/docker/pkg/parsers/kernel" <add> "github.com/docker/docker/pkg/parsers/operatingsystem" <add> "github.com/docker/docker/registry" <add> "github.com/docker/docker/utils" <add>) <add> <add>func (daemon *Daemon) CmdInfo(job *engine.Job) engine.Status { <add> images, _ := daemon.Graph().Map() <add> var imgcount int <add> if images == nil { <add> imgcount = 0 <add> } else { <add> imgcount = len(images) <add> } <add> kernelVersion := "<unknown>" <add> if kv, err := kernel.GetKernelVersion(); err == nil { <add> kernelVersion = kv.String() <add> } <add> <add> operatingSystem := "<unknown>" <add> if s, err := operatingsystem.GetOperatingSystem(); err == nil { <add> operatingSystem = s <add> } <add> if inContainer, err := operatingsystem.IsContainerized(); err != nil { <add> utils.Errorf("Could not determine if daemon is containerized: %v", err) <add> operatingSystem += " (error determining if containerized)" <add> } else if inContainer { <add> operatingSystem += " (containerized)" <add> } <add> <add> // if we still have the original dockerinit binary from before we copied it locally, let's return the path to that, since that's more intuitive (the copied path is trivial to derive by hand given VERSION) <add> initPath := utils.DockerInitPath("") <add> if initPath == "" { <add> // if that fails, we'll just return the path from the daemon <add> initPath = daemon.SystemInitPath() <add> } <add> <add> cjob := job.Eng.Job("subscribers_count") <add> env, _ := cjob.Stdout.AddEnv() <add> if err := cjob.Run(); err != nil { <add> return job.Error(err) <add> } <add> v := &engine.Env{} <add> v.SetInt("Containers", len(daemon.List())) <add> v.SetInt("Images", imgcount) <add> v.Set("Driver", daemon.GraphDriver().String()) <add> v.SetJson("DriverStatus", daemon.GraphDriver().Status()) <add> v.SetBool("MemoryLimit", daemon.SystemConfig().MemoryLimit) <add> v.SetBool("SwapLimit", daemon.SystemConfig().SwapLimit) <add> v.SetBool("IPv4Forwarding", !daemon.SystemConfig().IPv4ForwardingDisabled) <add> v.SetBool("Debug", os.Getenv("DEBUG") != "") <add> v.SetInt("NFd", utils.GetTotalUsedFds()) <add> v.SetInt("NGoroutines", runtime.NumGoroutine()) <add> v.Set("ExecutionDriver", daemon.ExecutionDriver().Name()) <add> v.SetInt("NEventsListener", env.GetInt("count")) <add> v.Set("KernelVersion", kernelVersion) <add> v.Set("OperatingSystem", operatingSystem) <add> v.Set("IndexServerAddress", registry.IndexServerAddress()) <add> v.Set("InitSha1", dockerversion.INITSHA1) <add> v.Set("InitPath", initPath) <add> v.SetList("Sockets", daemon.Sockets) <add> if _, err := v.WriteTo(job.Stdout); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add>} <ide><path>server/init.go <ide> func InitServer(job *engine.Job) engine.Status { <ide> job.Eng.Hack_SetGlobalVar("httpapi.daemon", srv.daemon) <ide> <ide> for name, handler := range map[string]engine.Handler{ <del> "info": srv.DockerInfo, <ide> "build": srv.Build, <ide> "pull": srv.ImagePull, <ide> "push": srv.ImagePush, <ide><path>server/server.go <ide> package server <ide> <ide> import ( <del> "os" <del> "runtime" <ide> "sync" <ide> "time" <ide> <ide> "github.com/docker/docker/daemon" <del> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/engine" <del> "github.com/docker/docker/pkg/parsers/kernel" <del> "github.com/docker/docker/pkg/parsers/operatingsystem" <del> "github.com/docker/docker/registry" <del> "github.com/docker/docker/utils" <ide> ) <ide> <del>func (srv *Server) DockerInfo(job *engine.Job) engine.Status { <del> images, _ := srv.daemon.Graph().Map() <del> var imgcount int <del> if images == nil { <del> imgcount = 0 <del> } else { <del> imgcount = len(images) <del> } <del> kernelVersion := "<unknown>" <del> if kv, err := kernel.GetKernelVersion(); err == nil { <del> kernelVersion = kv.String() <del> } <del> <del> operatingSystem := "<unknown>" <del> if s, err := operatingsystem.GetOperatingSystem(); err == nil { <del> operatingSystem = s <del> } <del> if inContainer, err := operatingsystem.IsContainerized(); err != nil { <del> utils.Errorf("Could not determine if daemon is containerized: %v", err) <del> operatingSystem += " (error determining if containerized)" <del> } else if inContainer { <del> operatingSystem += " (containerized)" <del> } <del> <del> // if we still have the original dockerinit binary from before we copied it locally, let's return the path to that, since that's more intuitive (the copied path is trivial to derive by hand given VERSION) <del> initPath := utils.DockerInitPath("") <del> if initPath == "" { <del> // if that fails, we'll just return the path from the daemon <del> initPath = srv.daemon.SystemInitPath() <del> } <del> <del> cjob := job.Eng.Job("subscribers_count") <del> env, _ := cjob.Stdout.AddEnv() <del> if err := cjob.Run(); err != nil { <del> return job.Error(err) <del> } <del> v := &engine.Env{} <del> v.SetInt("Containers", len(srv.daemon.List())) <del> v.SetInt("Images", imgcount) <del> v.Set("Driver", srv.daemon.GraphDriver().String()) <del> v.SetJson("DriverStatus", srv.daemon.GraphDriver().Status()) <del> v.SetBool("MemoryLimit", srv.daemon.SystemConfig().MemoryLimit) <del> v.SetBool("SwapLimit", srv.daemon.SystemConfig().SwapLimit) <del> v.SetBool("IPv4Forwarding", !srv.daemon.SystemConfig().IPv4ForwardingDisabled) <del> v.SetBool("Debug", os.Getenv("DEBUG") != "") <del> v.SetInt("NFd", utils.GetTotalUsedFds()) <del> v.SetInt("NGoroutines", runtime.NumGoroutine()) <del> v.Set("ExecutionDriver", srv.daemon.ExecutionDriver().Name()) <del> v.SetInt("NEventsListener", env.GetInt("count")) <del> v.Set("KernelVersion", kernelVersion) <del> v.Set("OperatingSystem", operatingSystem) <del> v.Set("IndexServerAddress", registry.IndexServerAddress()) <del> v.Set("InitSha1", dockerversion.INITSHA1) <del> v.Set("InitPath", initPath) <del> v.SetList("Sockets", srv.daemon.Sockets) <del> if _, err := v.WriteTo(job.Stdout); err != nil { <del> return job.Error(err) <del> } <del> return engine.StatusOK <del>} <del> <ide> func (srv *Server) SetRunning(status bool) { <ide> srv.Lock() <ide> defer srv.Unlock()
4
PHP
PHP
update exception message
ed797c283fac7689836d6d32af5b759c8815051c
<ide><path>src/ORM/Table.php <ide> protected function _processSave(EntityInterface $entity, ArrayObject $options) <ide> <ide> if ($result !== false && !($result instanceof EntityInterface)) { <ide> throw new RuntimeException(sprintf( <del> 'beforeSave callback must return `false` or `EntityInterface` instance. Got `%s` instead.', <add> 'The beforeSave callback must return `false` or `EntityInterface` instance. Got `%s` instead.', <ide> getTypeName($result) <ide> )); <ide> } <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testBeforeSaveStopEventWithNoResult() <ide> public function testBeforeSaveException() <ide> { <ide> $this->expectException(RuntimeException::class); <del> $this->expectExceptionMessage('beforeSave callback must return `false` or `EntityInterface` instance. Got `integer` instead.'); <add> $this->expectExceptionMessage('The beforeSave callback must return `false` or `EntityInterface` instance. Got `integer` instead.'); <ide> <ide> $table = $this->getTableLocator()->get('users'); <ide> $data = new Entity([
2
Javascript
Javascript
fix deprecation messages in test
9b2b1b4bf7d44c24144de067ae69c9e298dee718
<ide><path>test/ConfigTestCases.test.js <ide> describe("ConfigTestCases", () => { <ide> const testDirectory = path.join(casesPath, cat, testName); <ide> const filterPath = path.join(testDirectory, "test.filter.js"); <ide> if (fs.existsSync(filterPath) && !require(filterPath)()) { <del> describe.skip(testName, () => it("filtered")); <add> describe.skip(testName, () => { <add> it("filtered", () => {}); <add> }); <ide> return false; <ide> } <ide> return true;
1
Python
Python
add xlm-roberta to auto tokenization
64a971a9156788ed6d95f850453578ecb74069c5
<ide><path>transformers/tokenization_auto.py <ide> from .tokenization_camembert import CamembertTokenizer <ide> from .tokenization_albert import AlbertTokenizer <ide> from .tokenization_t5 import T5Tokenizer <add>from .tokenization_xlm_roberta import XLMRobertaTokenizer <ide> <ide> logger = logging.getLogger(__name__) <ide> <ide> class method. <ide> - contains `distilbert`: DistilBertTokenizer (DistilBert model) <ide> - contains `albert`: AlbertTokenizer (ALBERT model) <ide> - contains `camembert`: CamembertTokenizer (CamemBERT model) <add> - contains `xlm-roberta`: XLMRobertaTokenizer (XLM-RoBERTa model) <ide> - contains `roberta`: RobertaTokenizer (RoBERTa model) <ide> - contains `bert`: BertTokenizer (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> - contains `distilbert`: DistilBertTokenizer (DistilBert model) <ide> - contains `albert`: AlbertTokenizer (ALBERT model) <ide> - contains `camembert`: CamembertTokenizer (CamemBERT model) <add> - contains `xlm-roberta`: XLMRobertaTokenizer (XLM-RoBERTa model) <ide> - contains `roberta`: RobertaTokenizer (RoBERTa model) <ide> - contains `bert-base-japanese`: BertJapaneseTokenizer (Bert model) <ide> - contains `bert`: BertTokenizer (Bert model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> return AlbertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <add> elif 'xlm-roberta' in pretrained_model_name_or_path: <add> return XLMRobertaTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> return RobertaTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> elif 'bert-base-japanese' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> return CTRLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta', 'distilbert,' 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path)) <add> "'xlm-roberta', 'xlm', 'roberta', 'distilbert,' 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path))
1
PHP
PHP
fix typo in pagination
dbc13686fcdcab624dcef057c455ab37e1258990
<ide><path>src/Illuminate/Pagination/AbstractPaginator.php <ide> abstract class AbstractPaginator implements Htmlable <ide> protected $pageName = 'page'; <ide> <ide> /** <del> * The current page resolver callback. <add> * The current path resolver callback. <ide> * <ide> * @var \Closure <ide> */
1
Javascript
Javascript
fix uncaught exceptions when testing
266d653bf2ec7164e6e420bc2a40e87ad5ee0dbf
<ide><path>test-challenges.js <ide> function createTest({ title, tests = [], solutions = [] }) { <ide> /* eslint-enable no-unused-vars */ <ide> solutions.forEach(solution => { <ide> tests.forEach(test => { <del> eval(solution + ';;' + test); <add> try { <add> eval(solution + ';;' + test); <add> } catch (e) { <add> t.fail(e); <add> } <ide> }); <ide> }); <ide> })
1
Go
Go
fix bitsequence set()
84a0a0a98f52a67bd8dd301fdcdd7f9bb8f2138d
<ide><path>libnetwork/bitseq/sequence.go <ide> func (h *Handle) set(ordinal uint32, any bool, release bool) (uint32, error) { <ide> return ret, err <ide> } <ide> <del> // Create a private copy of h and work on it, also copy the current db index <add> // Create a private copy of h and work on it <ide> nh := h.getCopy() <del> ci := h.dbIndex <ide> h.Unlock() <ide> <ide> nh.head = pushReservation(bytePos, bitPos, nh.head, release) <ide> func (h *Handle) set(ordinal uint32, any bool, release bool) (uint32, error) { <ide> continue <ide> } <ide> <del> // Unless unexpected error, save private copy to local copy <add> // Previous atomic push was succesfull. Save private copy to local copy <ide> h.Lock() <ide> defer h.Unlock() <del> if h.dbIndex != ci { <del> return ret, fmt.Errorf("unexected database index change") <del> } <ide> h.unselected = nh.unselected <ide> h.head = nh.head <ide> h.dbExists = nh.dbExists
1
Text
Text
add example to `recipes` section
e70c59517bba73874c06cc426fd927e618f03219
<ide><path>readme.md <ide> For the production deployment, you can use the [path alias](https://zeit.co/docs <ide> - [Setting up 301 redirects](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/) <ide> - [Dealing with SSR and server only modules](https://arunoda.me/blog/ssr-and-server-only-modules) <ide> - [Building with React-Material-UI-Next-Express-Mongoose-Mongodb](https://github.com/builderbook/builderbook) <add>- [Build a SaaS Product with React-Material-UI-Next-MobX-Express-Mongoose-MongoDB-TypeScript](https://github.com/async-labs/saas) <ide> <ide> ## FAQ <ide>
1
Ruby
Ruby
fix exception translation
1543863548bcd7515fac7b7b1931b6e23fedf80f
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def close <ide> <ide> protected <ide> <del> def translate_exception(e, sql) <add> def translate_exception_class(e, sql) <ide> message = "#{e.class.name}: #{e.message}: #{sql}" <ide> @logger.error message if @logger <ide> exception = translate_exception(e, message) <ide> exception.set_backtrace e.backtrace <add> exception <ide> end <ide> <ide> def log(sql, name = "SQL", binds = [], statement_name = nil) <ide> def log(sql, name = "SQL", binds = [], statement_name = nil) <ide> :statement_name => statement_name, <ide> :binds => binds) { yield } <ide> rescue => e <del> raise translate_exception(e, sql) <add> raise translate_exception_class(e, sql) <ide> end <ide> <ide> def translate_exception(exception, message) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def prepare_statement(sql) <ide> begin <ide> @connection.prepare nextkey, sql <ide> rescue => e <del> raise translate_exception(e, sql) <add> raise translate_exception_class(e, sql) <ide> end <ide> # Clear the queue <ide> @connection.get_last_result
2
PHP
PHP
fix bug in validate_mimes method
9f78c8be9033ce5461da5de2d8d86dff8c65f4ea
<ide><path>laravel/validation/validator.php <ide> protected function validate_active_url($attribute, $value) <ide> */ <ide> protected function validate_image($attribute, $value) <ide> { <del> return $this->validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp')); <add> return $this->validate_mimes($attribute, $value, array('jpg', 'png', 'gif', 'bmp')); <ide> } <ide> <ide> /** <ide> protected function validate_alpha_dash($attribute, $value) <ide> * Validate the MIME type of a file upload attribute is in a set of MIME types. <ide> * <ide> * @param string $attribute <add> * @param array $value <ide> * @param array $parameters <ide> * @return bool <ide> */ <del> protected function validate_mimes($attribute, $parameters) <add> protected function validate_mimes($attribute, $value, $parameters) <ide> { <add> if (is_array($value) and ! isset($value['tmp_name'])) return true; <add> <ide> foreach ($parameters as $extension) <ide> { <del> if (File::is($extension, $this->attributes[$attribute]['tmp_name'])) <add> if (File::is($extension, $value['tmp_name'])) <ide> { <ide> return true; <ide> }
1
PHP
PHP
remove redundant condition
9a805d3dac8208b7450b22717a0bfc6e16e030d0
<ide><path>src/Illuminate/Routing/CompiledRouteCollection.php <ide> public function match(Request $request) <ide> try { <ide> $dynamicRoute = $this->routes->match($request); <ide> <del> if (! $dynamicRoute->isFallback || ! $route->isFallback) { <add> if (! $dynamicRoute->isFallback) { <ide> $route = $dynamicRoute; <ide> } <ide> } catch (NotFoundHttpException $e) {
1
Javascript
Javascript
allow suspend compilation
df27a5e2bdce70280c0ae540bead993b7ef7e2b5
<ide><path>lib/MultiWatching.js <ide> class MultiWatching { <ide> } <ide> } <ide> <add> suspend() { <add> for (const watching of this.watchings) { <add> watching.suspend(); <add> } <add> } <add> <add> resume() { <add> for (const watching of this.watchings) { <add> watching.resume(); <add> } <add> } <add> <ide> close(callback) { <ide> asyncLib.forEach( <ide> this.watchings, <ide><path>lib/Watching.js <ide> class Watching { <ide> this.handler = handler; <ide> this.callbacks = []; <ide> this.closed = false; <add> this.suspended = false; <ide> if (typeof watchOptions === "number") { <ide> this.watchOptions = { <ide> aggregateTimeout: watchOptions <ide> class Watching { <ide> this.compiler.fileTimestamps = fileTimestamps; <ide> this.compiler.contextTimestamps = contextTimestamps; <ide> this.compiler.removedFiles = removedFiles; <del> this._invalidate(); <add> if (!this.suspended) { <add> this._invalidate(); <add> } <ide> }, <ide> (fileName, changeTime) => { <ide> this.compiler.hooks.invalid.call(fileName, changeTime); <ide> class Watching { <ide> } <ide> } <ide> <add> suspend() { <add> this.suspended = true; <add> } <add> <add> resume() { <add> if (this.suspended) { <add> this.suspended = false; <add> this._invalidate(); <add> } <add> } <add> <ide> close(callback) { <ide> const finalCallback = () => { <ide> this.compiler.hooks.watchClose.call();
2
PHP
PHP
remove unused var
a86665aee4bed73272b0b0365b73060db6dee984
<ide><path>src/Illuminate/Database/Concerns/ManagesTransactions.php <ide> public function transaction(Closure $callback, $attempts = 1) <ide> // catch any exception we can rollback this transaction so that none of this <ide> // gets actually persisted to a database or stored in a permanent fashion. <ide> try { <del> return tap($callback($this), function ($result) { <add> return tap($callback($this), function () { <ide> $this->commit(); <ide> }); <ide> }
1
Ruby
Ruby
fix the tests after e594000
61a51a5ea356bbe6e6d0bc41e9334d384b4f2c73
<ide><path>railties/test/generators/app_generator_test.rb <ide> def test_web_console_with_dev_option <ide> <ide> assert_file "Gemfile" do |content| <ide> assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) <del> assert_no_match(/gem 'web-console'/, content) <add> assert_no_match(/\Agem 'web-console'\z/, content) <ide> end <ide> end <ide> <ide> def test_web_console_with_edge_option <ide> <ide> assert_file "Gemfile" do |content| <ide> assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) <del> assert_no_match(/gem 'web-console'/, content) <add> assert_no_match(/\Agem 'web-console'\z/, content) <ide> end <ide> end <ide>
1
PHP
PHP
add missing @throws in phpdocs
3630964f96b8daf9f1bfa730564b4a10c9a5f7f4
<ide><path>src/Controller/Controller.php <ide> public function paginate($object = null, array $settings = []) <ide> * <ide> * @param string $action The action to check. <ide> * @return bool Whether or not the method is accessible from a URL. <add> * @throws ReflectionException <ide> */ <ide> public function isAction($action) <ide> { <ide><path>src/Core/ObjectRegistry.php <ide> abstract class ObjectRegistry implements Countable, IteratorAggregate <ide> * @param string $objectName The name/class of the object to load. <ide> * @param array $config Additional settings to use when loading the object. <ide> * @return mixed <add> * @throws \Exception <ide> */ <ide> public function load($objectName, $config = []) <ide> { <ide> public function set($objectName, $object) <ide> * <ide> * @param string $objectName The name of the object to remove from the registry. <ide> * @return $this <add> * @throws \Exception <ide> */ <ide> public function unload($objectName) <ide> { <ide><path>src/Core/Retry/CommandRetry.php <ide> public function __construct(RetryStrategyInterface $strategy, $retries = 1) <ide> * <ide> * @param callable $action The callable action to execute with a retry strategy <ide> * @return mixed The return value of the passed action callable <add> * @throws Exception <ide> */ <ide> public function run(callable $action) <ide> { <ide><path>src/Database/Connection.php <ide> public function isConnected() <ide> * <ide> * @param string|\Cake\Database\Query $sql The SQL to convert into a prepared statement. <ide> * @return \Cake\Database\StatementInterface <add> * @throws Exception <ide> */ <ide> public function prepare($sql) <ide> { <ide> public function prepare($sql) <ide> * @param array $params list or associative array of params to be interpolated in $query as values <ide> * @param array $types list or associative array of types to be used for casting values in query <ide> * @return \Cake\Database\StatementInterface executed statement <add> * @throws Exception <ide> */ <ide> public function execute($query, array $params = [], array $types = []) <ide> { <ide> public function compileQuery(Query $query, ValueBinder $generator) <ide> * <ide> * @param \Cake\Database\Query $query The query to be executed <ide> * @return \Cake\Database\StatementInterface executed statement <add> * @throws Exception <ide> */ <ide> public function run(Query $query) <ide> { <ide> public function run(Query $query) <ide> * <ide> * @param string $sql The SQL query to execute. <ide> * @return \Cake\Database\StatementInterface <add> * @throws Exception <ide> */ <ide> public function query($sql) <ide> { <ide> public function schemaCollection(SchemaCollection $collection = null) <ide> * @param array $data values to be inserted <ide> * @param array $types list of associative array containing the types to be used for casting <ide> * @return \Cake\Database\StatementInterface <add> * @throws Exception <ide> */ <ide> public function insert($table, array $data, array $types = []) <ide> { <ide> public function insert($table, array $data, array $types = []) <ide> * @param array $conditions conditions to be set for update statement <ide> * @param array $types list of associative array containing the types to be used for casting <ide> * @return \Cake\Database\StatementInterface <add> * @throws Exception <ide> */ <ide> public function update($table, array $data, array $conditions = [], $types = []) <ide> { <ide> public function update($table, array $data, array $conditions = [], $types = []) <ide> * @param array $conditions conditions to be set for delete statement <ide> * @param array $types list of associative array containing the types to be used for casting <ide> * @return \Cake\Database\StatementInterface <add> * @throws Exception <ide> */ <ide> public function delete($table, $conditions = [], $types = []) <ide> { <ide> public function delete($table, $conditions = [], $types = []) <ide> * Starts a new transaction. <ide> * <ide> * @return void <add> * @throws Exception <ide> */ <ide> public function begin() <ide> { <ide> public function rollbackSavepoint($name) <ide> * Run driver specific SQL to disable foreign key checks. <ide> * <ide> * @return void <add> * @throws Exception <ide> */ <ide> public function disableForeignKeys() <ide> { <ide> public function disableForeignKeys() <ide> * Run driver specific SQL to enable foreign key checks. <ide> * <ide> * @return void <add> * @throws Exception <ide> */ <ide> public function enableForeignKeys() <ide> { <ide><path>src/Error/BaseErrorHandler.php <ide> public function handleError($code, $description, $file = null, $line = null, $co <ide> * <ide> * @param \Exception|\Error $exception The exception to handle <ide> * @return void <add> * @throws Exception <ide> */ <ide> public function wrapAndHandleException($exception) <ide> { <ide> protected function _stop($code) <ide> * @param string $file File on which error occurred <ide> * @param int $line Line that triggered the error <ide> * @return bool <add> * @throws Exception <ide> */ <ide> public function handleFatalError($code, $description, $file, $line) <ide> { <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __invoke($request, $response, $next) <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Message\ResponseInterface $response The response. <ide> * @return \Psr\Http\Message\ResponseInterface A response <add> * @throws Exception <ide> */ <ide> public function handleException($exception, $request, $response) <ide> { <ide><path>src/Http/ControllerFactory.php <ide> class ControllerFactory <ide> * @param \Cake\Http\ServerRequest $request The request to build a controller for. <ide> * @param \Cake\Http\Response $response The response to use. <ide> * @return \Cake\Controller\Controller <add> * @throws \ReflectionException <ide> */ <ide> public function create(ServerRequest $request, Response $response) <ide> { <ide><path>src/Http/Cookie/CookieCollection.php <ide> public function addToRequest(RequestInterface $request, array $extraCookies = [] <ide> * @param string $host The host to match. <ide> * @param string $path The path to match <ide> * @return array An array of cookie name/value pairs <add> * @throws \Exception <ide> */ <ide> protected function findMatchingCookies($scheme, $host, $path) <ide> { <ide> protected function setRequestDefaults(array $cookies, $host, $path) <ide> * <ide> * @param array $values List of Set-Cookie Header values. <ide> * @return \Cake\Http\Cookie\Cookie[] An array of cookie objects <add> * @throws \Exception <ide> */ <ide> protected static function parseSetCookieHeader($values) <ide> { <ide> protected static function parseSetCookieHeader($values) <ide> * @param string $host The host to check for expired cookies on. <ide> * @param string $path The path to check for expired cookies on. <ide> * @return void <add> * @throws \Exception <ide> */ <ide> protected function removeExpiredCookies($host, $path) <ide> { <ide><path>src/I18n/Formatter/IcuFormatter.php <ide> class IcuFormatter implements FormatterInterface <ide> * @param string|array $message The message to be translated <ide> * @param array $vars The list of values to interpolate in the message <ide> * @return string The formatted message <add> * @throws CannotFormat <add> * @throws CannotInstantiateFormatter <ide> */ <ide> public function format($locale, $message, array $vars) <ide> { <ide><path>src/I18n/I18n.php <ide> public static function setTranslator($name, callable $loader, $locale = null) <ide> * @param string $name The domain of the translation messages. <ide> * @param string|null $locale The locale for the translator. <ide> * @return \Aura\Intl\TranslatorInterface The configured translator. <add> * @throws \Aura\Intl\Exception <ide> */ <ide> public static function getTranslator($name = 'default', $locale = null) <ide> { <ide><path>src/Mailer/Email.php <ide> public function createFromArray($config) <ide> * Serializes the Email object. <ide> * <ide> * @return string <add> * @throws Exception <ide> */ <ide> public function serialize() <ide> { <ide><path>src/ORM/Association/BelongsToMany.php <ide> protected function _saveLinks(EntityInterface $sourceEntity, $targetEntities, $o <ide> * @param array $targetEntities list of entities belonging to the `target` side <ide> * of this association <ide> * @param array $options list of options to be passed to the internal `save` call <del> * @throws \InvalidArgumentException when any of the values in $targetEntities is <del> * detected to not be already persisted <ide> * @return bool true on success, false otherwise <add> * @throws \Exception <ide> */ <ide> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = []) <ide> { <ide> function () use ($sourceEntity, $targetEntities, $options) { <ide> * this association <ide> * @param array|bool $options list of options to be passed to the internal `delete` call, <ide> * or a `boolean` <del> * @throws \InvalidArgumentException if non persisted entities are passed or if <del> * any of them is lacking a primary key value <ide> * @return bool Success <add> * @throws \Exception <ide> */ <ide> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = []) <ide> { <ide> protected function _appendJunctionJoin($query, $conditions) <ide> * @param array $targetEntities list of entities from the target table to be linked <ide> * @param array $options list of options to be passed to the internal `save`/`delete` calls <ide> * when persisting/updating new links, or deleting existing ones <del> * @throws \InvalidArgumentException if non persisted entities are passed or if <del> * any of them is lacking a primary key value <ide> * @return bool success <add> * @throws \Exception <ide> */ <ide> public function replaceLinks(EntityInterface $sourceEntity, array $targetEntities, array $options = []) <ide> { <ide><path>src/ORM/Association/HasMany.php <ide> protected function _saveTarget(array $foreignKeyReference, EntityInterface $pare <ide> * of this association <ide> * @param array $options list of options to be passed to the internal `save` call <ide> * @return bool true on success, false otherwise <add> * @throws \Exception <ide> */ <ide> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = []) <ide> { <ide><path>src/ORM/Behavior.php <ide> public function implementedMethods() <ide> * declared on Cake\ORM\Behavior <ide> * <ide> * @return array <add> * @throws \ReflectionException <ide> */ <ide> protected function _reflectionCache() <ide> { <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> public function formatTreeList(Query $query, array $options = []) <ide> * @param \Cake\Datasource\EntityInterface $node The node to remove from the tree <ide> * @return \Cake\Datasource\EntityInterface|false the node after being removed from the tree or <ide> * false on error <add> * @throws \Exception <ide> */ <ide> public function removeFromTree(EntityInterface $node) <ide> { <ide> protected function _removeFromTree($node) <ide> * <ide> * @param \Cake\Datasource\EntityInterface $node The node to move <ide> * @param int|bool $number How many places to move the node, or true to move to first position <del> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found <ide> * @return \Cake\Datasource\EntityInterface|bool $node The node after being moved or false on failure <add> * @throws \Exception <ide> */ <ide> public function moveUp(EntityInterface $node, $number = 1) <ide> { <ide> protected function _moveUp($node, $number) <ide> * <ide> * @param \Cake\Datasource\EntityInterface $node The node to move <ide> * @param int|bool $number How many places to move the node or true to move to last position <del> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found <ide> * @return \Cake\Datasource\EntityInterface|bool the entity after being moved or false on failure <add> * @throws \Exception <ide> */ <ide> public function moveDown(EntityInterface $node, $number = 1) <ide> { <ide> protected function _getNode($id) <ide> * parent column. <ide> * <ide> * @return void <add> * @throws \Exception <ide> */ <ide> public function recover() <ide> { <ide><path>src/ORM/Table.php <ide> public function get($primaryKey, $options = []) <ide> * @param callable $worker The worker that will run inside the transaction. <ide> * @param bool $atomic Whether to execute the worker inside a database transaction. <ide> * @return mixed <add> * @throws \Exception <ide> */ <ide> protected function _executeTransaction(callable $worker, $atomic = true) <ide> { <ide> protected function _update($entity, $data) <ide> * @param \Cake\Datasource\EntityInterface[]|\Cake\ORM\ResultSet $entities Entities to save. <ide> * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity. <ide> * @return bool|\Cake\Datasource\EntityInterface[]|\Cake\ORM\ResultSet False on failure, entities list on success. <add> * @throws \Exception <ide> */ <ide> public function saveMany($entities, $options = []) <ide> { <ide><path>src/Shell/Task/CommandTask.php <ide> public function commands() <ide> * <ide> * @param string $commandName The command you want subcommands from. <ide> * @return array <add> * @throws \ReflectionException <ide> */ <ide> public function subCommands($commandName) <ide> { <ide><path>src/TestSuite/Fixture/FixtureManager.php <ide> public function load($test) <ide> * @param array $fixtures A list of fixtures to operate on. <ide> * @param callable $operation The operation to run on each connection + fixture set. <ide> * @return void <add> * @throws \Exception <ide> */ <ide> protected function _runOperation($fixtures, $operation) <ide> { <ide><path>src/TestSuite/IntegrationTestCase.php <ide> public function cookieEncrypted($name, $value, $encrypt = 'aes', $key = null) <ide> * <ide> * @param string|array $url The URL to request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function get($url) <ide> { <ide> public function get($url) <ide> * @param string|array $url The URL to request. <ide> * @param array $data The data for the request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function post($url, $data = []) <ide> { <ide> public function post($url, $data = []) <ide> * @param string|array $url The URL to request. <ide> * @param array $data The data for the request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function patch($url, $data = []) <ide> { <ide> public function patch($url, $data = []) <ide> * @param string|array $url The URL to request. <ide> * @param array $data The data for the request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function put($url, $data = []) <ide> { <ide> public function put($url, $data = []) <ide> * <ide> * @param string|array $url The URL to request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function delete($url) <ide> { <ide> public function delete($url) <ide> * <ide> * @param string|array $url The URL to request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function head($url) <ide> { <ide> public function head($url) <ide> * <ide> * @param string|array $url The URL to request. <ide> * @return void <add> * @throws PhpunitException <ide> */ <ide> public function options($url) <ide> { <ide> public function options($url) <ide> * @param string $method The HTTP method <ide> * @param array|null $data The request data. <ide> * @return void <del> * @throws \Exception <add> * @throws PhpunitException <ide> */ <ide> protected function _sendRequest($url, $method, $data = []) <ide> { <ide><path>src/Utility/Security.php <ide> public static function setHash($hash) <ide> * <ide> * @param int $length The number of bytes you want. <ide> * @return string Random bytes in binary. <add> * @throws \Exception <ide> */ <ide> public static function randomBytes($length) <ide> { <ide><path>src/Validation/RulesProvider.php <ide> class RulesProvider <ide> * Constructor, sets the default class to use for calling methods <ide> * <ide> * @param string|object $class the default class to proxy <add> * @throws \ReflectionException <ide> */ <ide> public function __construct($class = Validation::class) <ide> { <ide><path>src/View/Helper/TimeHelper.php <ide> public function gmt($string = null) <ide> * @param bool|string $invalid Default value to display on invalid dates <ide> * @param string|\DateTimeZone|null $timezone User's timezone string or DateTimeZone object <ide> * @return string Formatted and translated date string <add> * @throws Exception <ide> * @see \Cake\I18n\Time::i18nFormat() <ide> */ <ide> public function format($date, $format = null, $invalid = false, $timezone = null) <ide><path>src/View/Widget/WidgetLocator.php <ide> public function clear() <ide> * <ide> * @param mixed $widget The widget to get <ide> * @return \Cake\View\Widget\WidgetInterface <del> * @throws \RuntimeException when class cannot be loaded or does not <del> * implement WidgetInterface. <add> * @throws \ReflectionException <ide> */ <ide> protected function _resolveWidget($widget) <ide> {
23
Java
Java
log getconstants for java modules
50de41d5d68bc2c28c4cc777ff9f3d041f960df3
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java <ide> public class ReactMarkerConstants { <ide> "CREATE_I18N_ASSETS_MODULE_START"; <ide> public static final String CREATE_I18N_ASSETS_MODULE_END = <ide> "CREATE_I18N_ASSETS_MODULE_END"; <add> public static final String GET_CONSTANTS_START = "GET_CONSTANTS_START"; <add> public static final String GET_CONSTANTS_END = "GET_CONSTANTS_END"; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/cxxbridge/JavaModuleWrapper.java <ide> import com.facebook.react.bridge.NativeArray; <ide> import com.facebook.react.bridge.NativeModuleLogger; <ide> import com.facebook.react.bridge.NativeModule; <add>import com.facebook.react.bridge.ReactMarker; <ide> import com.facebook.react.bridge.ReadableNativeArray; <ide> import com.facebook.react.bridge.WritableNativeArray; <ide> import com.facebook.react.bridge.WritableNativeMap; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <ide> <add>import static com.facebook.react.bridge.ReactMarkerConstants.GET_CONSTANTS_END; <add>import static com.facebook.react.bridge.ReactMarkerConstants.GET_CONSTANTS_START; <ide> import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; <ide> <ide> /** <ide> public List<MethodDescriptor> getMethodDescriptors() { <ide> // NativeMap out of OnLoad. <ide> @DoNotStrip <ide> public NativeArray getConstants() { <add> ReactMarker.logMarker(GET_CONSTANTS_START, getName()); <ide> SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "Map constants") <ide> .arg("moduleName", getName()) <ide> .flush(); <ide> public NativeArray getConstants() { <ide> if (baseJavaModule instanceof NativeModuleLogger) { <ide> ((NativeModuleLogger) baseJavaModule).endConstantsMapConversion(); <ide> } <add> ReactMarker.logMarker(GET_CONSTANTS_END); <ide> return array; <ide> } <ide>
2
Go
Go
use pointers for the object methods
f35f084059e5c34940f74f55ad32ecfcd78ce61c
<ide><path>builder_client.go <ide> type builderClient struct { <ide> needCommit bool <ide> } <ide> <del>func (b builderClient) clearTmp(containers, images map[string]struct{}) { <add>func (b *builderClient) clearTmp(containers, images map[string]struct{}) { <ide> for c := range containers { <ide> if _, _, err := b.cli.call("DELETE", "/containers/"+c, nil); err != nil { <ide> utils.Debugf("%s", err) <ide> func (b builderClient) clearTmp(containers, images map[string]struct{}) { <ide> } <ide> } <ide> <del>func (b builderClient) CmdFrom(name string) error { <add>func (b *builderClient) CmdFrom(name string) error { <ide> obj, statusCode, err := b.cli.call("GET", "/images/"+name+"/json", nil) <ide> if statusCode == 404 { <ide> if err := b.cli.hijack("POST", "/images/create?fromImage="+name, false); err != nil { <ide> func (b builderClient) CmdFrom(name string) error { <ide> return err <ide> } <ide> b.image = img.Id <add> utils.Debugf("Using image %s", b.image) <ide> return nil <ide> } <ide> <del>func (b builderClient) CmdMaintainer(name string) error { <add>func (b *builderClient) CmdMaintainer(name string) error { <ide> b.needCommit = true <ide> b.maintainer = name <ide> return nil <ide> } <ide> <del>func (b builderClient) CmdRun(args string) error { <add>func (b *builderClient) CmdRun(args string) error { <ide> if b.image == "" { <ide> return fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <ide> func (b builderClient) CmdRun(args string) error { <ide> return b.commit(cid) <ide> } <ide> <del>func (b builderClient) CmdEnv(args string) error { <add>func (b *builderClient) CmdEnv(args string) error { <ide> b.needCommit = true <ide> tmp := strings.SplitN(args, " ", 2) <ide> if len(tmp) != 2 { <ide> func (b builderClient) CmdEnv(args string) error { <ide> return nil <ide> } <ide> <del>func (b builderClient) CmdCmd(args string) error { <add>func (b *builderClient) CmdCmd(args string) error { <ide> b.needCommit = true <ide> var cmd []string <ide> if err := json.Unmarshal([]byte(args), &cmd); err != nil { <add> utils.Debugf("Error unmarshalling: %s, using /bin/sh -c", err) <ide> b.config.Cmd = []string{"/bin/sh", "-c", args} <ide> } else { <ide> b.config.Cmd = cmd <ide> } <ide> return nil <ide> } <ide> <del>func (b builderClient) CmdExpose(args string) error { <add>func (b *builderClient) CmdExpose(args string) error { <ide> ports := strings.Split(args, " ") <ide> b.config.PortSpecs = append(ports, b.config.PortSpecs...) <ide> return nil <ide> } <ide> <del>func (b builderClient) CmdInsert(args string) error { <add>func (b *builderClient) CmdInsert(args string) error { <ide> // FIXME: Reimplement this once the remove_hijack branch gets merged. <ide> // We need to retrieve the resulting Id <ide> return fmt.Errorf("INSERT not implemented") <ide> } <ide> <del>func (b builderClient) run() (string, error) { <add>func (b *builderClient) run() (string, error) { <ide> if b.image == "" { <ide> return "", fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <ide> func (b builderClient) run() (string, error) { <ide> return apiRun.Id, nil <ide> } <ide> <del>func (b builderClient) commit(id string) error { <add>func (b *builderClient) commit(id string) error { <ide> if b.image == "" { <ide> return fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <ide> func (b builderClient) commit(id string) error { <ide> return nil <ide> } <ide> <del>func (b builderClient) Build(dockerfile io.Reader) (string, error) { <add>func (b *builderClient) Build(dockerfile io.Reader) (string, error) { <ide> // defer b.clearTmp(tmpContainers, tmpImages) <ide> file := bufio.NewReader(dockerfile) <ide> for { <ide> func (b builderClient) Build(dockerfile io.Reader) (string, error) { <ide> instruction := strings.ToLower(strings.Trim(tmp[0], " ")) <ide> arguments := strings.Trim(tmp[1], " ") <ide> <del> fmt.Printf("%s %s\n", strings.ToUpper(instruction), arguments) <add> fmt.Printf("%s %s (%s)\n", strings.ToUpper(instruction), arguments, b.image) <ide> <ide> method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:])) <ide> if !exists {
1
Java
Java
fix race condition in partgenerator
4c0ece944aad373adea3a85874552ae982c989d7
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/PartGenerator.java <ide> public void body(DataBuffer dataBuffer) { <ide> <ide> @Override <ide> public void partComplete(boolean finalPart) { <del> this.completed = true; <del> this.finalPart = finalPart; <add> State state = PartGenerator.this.state.get(); <add> // writeComplete might have changed our state to IdleFileState <add> if (state != this) { <add> state.partComplete(finalPart); <add> } <add> else { <add> this.completed = true; <add> this.finalPart = finalPart; <add> } <ide> } <ide> <ide> public void writeBuffer(DataBuffer dataBuffer) { <ide> public void writeBuffers(Iterable<DataBuffer> dataBuffers) { <ide> <ide> private void writeComplete() { <ide> IdleFileState newState = new IdleFileState(this); <del> if (this.completed) { <del> newState.partComplete(this.finalPart); <del> } <del> else if (this.disposed) { <add> if (this.disposed) { <ide> newState.dispose(); <ide> } <ide> else if (changeState(this, newState)) { <del> requestToken(); <add> if (this.completed) { <add> newState.partComplete(this.finalPart); <add> } <add> else { <add> requestToken(); <add> } <ide> } <ide> else { <ide> MultipartUtils.closeChannel(this.channel);
1
PHP
PHP
use typehints instead of explicit type checks
47220c90173834377eb382a5a885aef7f15c6c44
<ide><path>src/View/Helper/FormHelper.php <ide> public function widget(string $name, array $data = []): string <ide> $secure = $data['secure']; <ide> unset($data['secure']); <ide> } <del> /** @var \Cake\View\Widget\WidgetInterface $widget */ <ide> $widget = $this->_locator->get($name); <ide> $out = $widget->render($data, $this->context()); <ide> if ( <ide><path>src/View/Widget/WidgetLocator.php <ide> public function add(array $widgets): void <ide> } <ide> <ide> if (is_object($widget) && !($widget instanceof WidgetInterface)) { <del> throw new RuntimeException('Widget objects must implement ' . WidgetInterface::class); <add> throw new RuntimeException(sprintf( <add> 'Widget objects must implement `%s`. Got `%s` instance instead.', <add> WidgetInterface::class, <add> getTypeName($widget) <add> )); <ide> } <ide> <ide> $this->_widgets[$key] = $widget; <ide> public function add(array $widgets): void <ide> * the `_default` widget is undefined. <ide> * <ide> * @param string $name The widget name to get. <del> * @return object WidgetInterface instance. <add> * @return \Cake\View\Widget\WidgetInterface WidgetInterface instance. <ide> * @throws \RuntimeException when widget is undefined. <del> * @throws \ReflectionException <ide> */ <del> public function get(string $name) <add> public function get(string $name): WidgetInterface <ide> { <ide> if (!isset($this->_widgets[$name])) { <ide> if (empty($this->_widgets['_default'])) { <ide> public function clear(): void <ide> * Resolves a widget spec into an instance. <ide> * <ide> * @param mixed $widget The widget to get <del> * @return object Either WidgetInterface or View instance. <del> * @throws \RuntimeException when class cannot be loaded or does not implement WidgetInterface. <add> * @return \Cake\View\Widget\WidgetInterface Widget instance. <ide> * @throws \ReflectionException <ide> */ <del> protected function _resolveWidget($widget): object <add> protected function _resolveWidget($widget): WidgetInterface <ide> { <ide> if (is_string($widget)) { <ide> $widget = [$widget]; <ide> protected function _resolveWidget($widget): object <ide> $arguments[] = $this->get($requirement); <ide> } <ide> } <add> /** @var \Cake\View\Widget\WidgetInterface $instance */ <ide> $instance = $reflection->newInstanceArgs($arguments); <ide> } else { <add> /** @var \Cake\View\Widget\WidgetInterface $instance */ <ide> $instance = new $className($this->_templates); <ide> } <del> if (!($instance instanceof WidgetInterface)) { <del> throw new RuntimeException(sprintf('"%s" does not implement the WidgetInterface', $className)); <del> } <ide> <ide> return $instance; <ide> } <ide><path>tests/TestCase/View/Widget/WidgetLocatorTest.php <ide> public function testAdd() <ide> public function testAddInvalidType() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> $this->expectExceptionMessage('Widget objects must implement Cake\View\Widget\WidgetInterface'); <add> $this->expectExceptionMessage( <add> 'Widget objects must implement `Cake\View\Widget\WidgetInterface`. Got `stdClass` instance instead.' <add> ); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->add([ <ide> 'text' => new \StdClass(), <ide> public function testGetFallback() <ide> public function testGetNoFallbackError() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> $this->expectExceptionMessage('Unknown widget "foo"'); <add> $this->expectExceptionMessage('Unknown widget `foo`'); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->clear(); <ide> $inputs->get('foo'); <ide> public function testGetResolveDependencyMissingClass() <ide> public function testGetResolveDependencyMissingDependency() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> $this->expectExceptionMessage('Unknown widget "label"'); <add> $this->expectExceptionMessage('Unknown widget `label`'); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->clear(); <ide> $inputs->add(['multicheckbox' => ['Cake\View\Widget\MultiCheckboxWidget', 'label']]);
3
Python
Python
fix example in wav2vec2 documentation
4ed763779e808591206b3ffb435a7ecf4063886f
<ide><path>src/transformers/models/wav2vec2/modeling_wav2vec2.py <ide> def forward( <ide> <ide> Example:: <ide> <del> >>> from transformers import Wav2Vec2Tokenizer, Wav2Vec2Model <add> >>> import torch <add> >>> from transformers import Wav2Vec2Tokenizer, Wav2Vec2ForCTC <ide> >>> from datasets import load_dataset <ide> >>> import soundfile as sf <ide>
1
Ruby
Ruby
add a test
b06fceda57ea8306e130ba11ccb2bd71f6907c23
<ide><path>Library/Homebrew/cmd/search.rb <ide> def search <ide> result = Formulary.factory(query).name <ide> results = Array(result) <ide> rescue FormulaUnavailableError <del> results = search_taps(query) <add> results = search_taps(query.split('/')[-1]) <ide> end <ide> <ide> puts Formatter.columns(results) unless results.empty? <ide><path>Library/Homebrew/test/cmd/search_spec.rb <ide> describe "brew search", :integration_test do <ide> before(:each) do <ide> setup_test_formula "testball" <add> setup_remote_tap "caskroom/cask/test" <ide> end <ide> <ide> it "lists all available Formulae when no argument is given" do <ide> .and be_a_success <ide> end <ide> <add> it "falls back to a tap search when no formula is found" do <add> expect { brew "search", "caskroom/cask/firefox" } <add> .to output(/firefox/).to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <add> <ide> describe "--desc" do <ide> let(:desc_cache) { HOMEBREW_CACHE/"desc_cache.json" } <ide>
2
Ruby
Ruby
remove call to source index
fe5a6ec45fed40f784ee3daede9d0a5e61fdf1f1
<ide><path>load_paths.rb <ide> # bust gem prelude <ide> if defined? Gem <del> Gem.source_index <ide> gem 'bundler' <ide> else <ide> require 'rubygems' <ide> end <ide> require 'bundler' <del>Bundler.setup <ide>\ No newline at end of file <add>Bundler.setup
1
Javascript
Javascript
add spacings to instancedbuffergeometry
41789c1aef9c89a01af1a74b41346de103b03a93
<ide><path>test/unit/core/InstancedBufferGeometry.js <ide> module( "InstancedBufferGeometry" ); <ide> function createClonableMock() { <ide> return { <ide> callCount: 0, <add> <ide> clone: function() { <ide> this.callCount++; <add> <ide> return this; <ide> } <ide> } <ide> test( "copy", function() { <ide> <ide> var instance = new THREE.InstancedBufferGeometry(); <ide> <del> instance.addGroup(0, 10, instanceMock1); <del> instance.addGroup(10, 5, instanceMock2); <del> instance.setIndex(indexMock); <del> instance.addAttribute('attributeMock1', attributeMock1); <del> instance.addAttribute('attributeMock2', attributeMock2); <add> instance.addGroup( 0, 10, instanceMock1 ); <add> instance.addGroup( 10, 5, instanceMock2 ); <add> instance.setIndex( indexMock ); <add> instance.addAttribute( 'attributeMock1', attributeMock1 ); <add> instance.addAttribute( 'attributeMock2', attributeMock2 ); <ide> <del> var copiedInstance = instance.copy(instance); <add> var copiedInstance = instance.copy( instance ); <ide> <ide> ok( copiedInstance instanceof THREE.InstancedBufferGeometry, "the clone has the correct type" ); <ide>
1
Javascript
Javascript
add test for rebind
a0e3e84972f3ca30e0ed4acfb62433b174119a69
<ide><path>test/core/rebind-test.js <add>require("../env"); <add>require("../../d3"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.rebind"); <add> <add>suite.addBatch({ <add> "rebind": { <add> topic: function() { <add> return d3.rebind; <add> }, <add> "bound function uses object as context": function(rebind) { <add> var a = {}, that, f = rebind(a, function() { that = this; }); <add> assert.strictEqual((f(), that), a); <add> assert.strictEqual((f.call({}), that), a); <add> }, <add> "bound function receives any arguments": function(rebind) { <add> var a = [], b = {}, f = rebind(a, function() { a = Array.prototype.slice.call(arguments); }); <add> assert.deepEqual((f(), a), []); <add> assert.deepEqual((f(1), a), [1]); <add> assert.deepEqual((f(null), a), [null]); <add> assert.deepEqual((f(b, b, 1), a), [b, b, 1]); <add> }, <add> "bound function returns object if arguments": function(rebind) { <add> var a = {}, f = rebind(a, function() {}); <add> assert.strictEqual(f(1), a); <add> assert.strictEqual(f(1, 2, 3), a); <add> }, <add> "bound function returns return value if no arguments": function(rebind) { <add> var a = {}, f = rebind({}, function() { return a; }); <add> assert.strictEqual(f(), a); <add> } <add> } <add>}); <add> <add>suite.export(module);
1
Python
Python
fix weight saving in batchnormalization
4e1ec93c2f0fcf432e74e3bcbf8eba89ac843cec
<ide><path>keras/layers/normalization.py <ide> from ..layers.core import Layer <del>from ..utils.theano_utils import shared_zeros, shared_ones, ndim_tensor <add>from ..utils.theano_utils import shared_zeros, shared_ones, ndim_tensor, floatX <ide> from .. import initializations <ide> <ide> import theano.tensor as T <ide> def __init__(self, input_shape, epsilon=1e-6, mode=0, momentum=0.9, weights=None <ide> self.beta = shared_zeros(self.input_shape) <ide> <ide> self.params = [self.gamma, self.beta] <add> self.running_mean = shared_zeros(self.input_shape) <add> self.running_std = shared_ones((self.input_shape)) <ide> if weights is not None: <ide> self.set_weights(weights) <ide> <add> def get_weights(self): <add> return super(BatchNormalization, self).get_weights() + [self.running_mean.get_value(), self.running_std.get_value()] <add> <add> def set_weights(self, weights): <add> self.running_mean.set_value(floatX(weights[-2])) <add> self.running_std.set_value(floatX(weights[-1])) <add> super(BatchNormalization, self).set_weights(weights[:-2]) <add> <ide> def init_updates(self): <del> self.running_mean = shared_zeros(self.input_shape) <del> self.running_std = shared_ones((self.input_shape)) <ide> X = self.get_input(train=True) <ide> m = X.mean(axis=0) <ide> std = T.mean((X - m) ** 2 + self.epsilon, axis=0) ** 0.5 <ide><path>tests/auto/keras/test_normalization.py <ide> def test_weight_init(self): <ide> Test weight initialization <ide> """ <ide> <del> norm_m1 = normalization.BatchNormalization((10,), mode=1, weights=[np.ones(10), np.ones(10)]) <add> norm_m1 = normalization.BatchNormalization((10,), mode=1, weights=[np.ones(10), np.ones(10), np.zeros(10), np.zeros(10)]) <ide> norm_m1.init_updates() <ide> <ide> for inp in [self.input_1, self.input_2, self.input_3]: <ide> def test_weight_init(self): <ide> assert_allclose(norm_m1.gamma.eval(), np.ones(10)) <ide> assert_allclose(norm_m1.beta.eval(), np.ones(10)) <ide> <del> # Weights must be an iterable of gamma AND beta. <del> self.assertRaises(Exception, normalization.BatchNormalization((10,)), weights=np.ones(10)) <del> <ide> def test_config(self): <ide> norm = normalization.BatchNormalization((10, 10), mode=1, epsilon=0.1) <ide> conf = norm.get_config() <ide> def test_config(self): <ide> <ide> self.assertDictEqual(conf, conf_target) <ide> <add> def test_save_weights(self): <add> norm = normalization.BatchNormalization((10, 10), mode=1, epsilon=0.1) <add> weights = norm.get_weights() <add> assert(len(weights) == 4) <add> norm.set_weights(weights) <add> <ide> <ide> if __name__ == '__main__': <ide> unittest.main()
2
Text
Text
fix typo in linkinglibraries.md
d3119a8fb1243dc127df8890f22b8aa9c0d46ed0
<ide><path>docs/LinkingLibraries.md <ide> on Xcode); <ide> <ide> Click on your main project file (the one that represents the `.xcodeproj`) <ide> select `Build Phases` and drag the static library from the `Products` folder <del>insed the Library you are importing to `Link Binary With Libraries` <add>inside the Library you are importing to `Link Binary With Libraries` <ide> <ide> ![](/react-native/img/AddToBuildPhases.png) <ide>
1
Python
Python
clarify svd documentation
40747ae50620631941e43dbbd5baaccab669922f
<ide><path>numpy/linalg/linalg.py <ide> def svd(a, full_matrices=True, compute_uv=True, hermitian=False): <ide> """ <ide> Singular Value Decomposition. <ide> <del> When `a` is a 2D array, it is factorized as ``u @ np.diag(s) @ vh <del> = (u * s) @ vh``, where `u` and `vh` are 2D unitary arrays and `s` is a 1D <add> When `a` is a 2D array, and when `full_matrices` is `False`, <add> it is factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, <add> where `u` and `vh` are 2D unitary arrays and `s` is a 1D <ide> array of `a`'s singular values. When `a` is higher-dimensional, SVD is <ide> applied in stacked mode as explained below. <ide>
1
Javascript
Javascript
add jsdoc typings for events
5ce015ec72be98f064041d1bf5c3527a89c276cc
<ide><path>lib/events.js <ide> const kMaxEventTargetListeners = Symbol('events.maxEventTargetListeners'); <ide> const kMaxEventTargetListenersWarned = <ide> Symbol('events.maxEventTargetListenersWarned'); <ide> <add>/** <add> * Creates a new `EventEmitter` instance. <add> * @param {{ captureRejections?: boolean; }} [opts] <add> * @returns {EventEmitter} <add> */ <ide> function EventEmitter(opts) { <ide> EventEmitter.init.call(this, opts); <ide> } <ide> ObjectDefineProperties(EventEmitter, { <ide> } <ide> }); <ide> <add>/** <add> * Sets the max listeners. <add> * @param {number} n <add> * @param {EventTarget[] | EventEmitter[]} [eventTargets] <add> * @returns {void} <add> */ <ide> EventEmitter.setMaxListeners = <ide> function(n = defaultMaxListeners, ...eventTargets) { <ide> if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) <ide> function emitUnhandledRejectionOrErr(ee, err, type, args) { <ide> } <ide> } <ide> <del>// Obviously not all Emitters should be limited to 10. This function allows <del>// that to be increased. Set to zero for unlimited. <add>/** <add> * Increases the max listeners of the event emitter. <add> * @param {number} n <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { <ide> if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { <ide> throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n); <ide> function _getMaxListeners(that) { <ide> return that._maxListeners; <ide> } <ide> <add>/** <add> * Returns the current max listener value for the event emitter. <add> * @returns {number} <add> */ <ide> EventEmitter.prototype.getMaxListeners = function getMaxListeners() { <ide> return _getMaxListeners(this); <ide> }; <ide> function enhanceStackTrace(err, own) { <ide> return err.stack + sep + ArrayPrototypeJoin(ownStack, '\n'); <ide> } <ide> <add>/** <add> * Synchronously calls each of the listeners registered <add> * for the event. <add> * @param {string | symbol} type <add> * @param {...any} [args] <add> * @returns {boolean} <add> */ <ide> EventEmitter.prototype.emit = function emit(type, ...args) { <ide> let doError = (type === 'error'); <ide> <ide> function _addListener(target, type, listener, prepend) { <ide> return target; <ide> } <ide> <add>/** <add> * Adds a listener to the event emitter. <add> * @param {string | symbol} type <add> * @param {Function} listener <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.addListener = function addListener(type, listener) { <ide> return _addListener(this, type, listener, false); <ide> }; <ide> <ide> EventEmitter.prototype.on = EventEmitter.prototype.addListener; <ide> <add>/** <add> * Adds the `listener` function to the beginning of <add> * the listeners array. <add> * @param {string | symbol} type <add> * @param {Function} listener <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.prependListener = <ide> function prependListener(type, listener) { <ide> return _addListener(this, type, listener, true); <ide> function _onceWrap(target, type, listener) { <ide> return wrapped; <ide> } <ide> <add>/** <add> * Adds a one-time `listener` function to the event emitter. <add> * @param {string | symbol} type <add> * @param {Function} listener <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.once = function once(type, listener) { <ide> checkListener(listener); <ide> <ide> this.on(type, _onceWrap(this, type, listener)); <ide> return this; <ide> }; <ide> <add>/** <add> * Adds a one-time `listener` function to the beginning of <add> * the listeners array. <add> * @param {string | symbol} type <add> * @param {Function} listener <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.prependOnceListener = <ide> function prependOnceListener(type, listener) { <ide> checkListener(listener); <ide> EventEmitter.prototype.prependOnceListener = <ide> return this; <ide> }; <ide> <del>// Emits a 'removeListener' event if and only if the listener was removed. <add>/** <add> * Removes the specified `listener` from the listeners array. <add> * @param {string | symbol} type <add> * @param {Function} listener <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.removeListener = <ide> function removeListener(type, listener) { <ide> checkListener(listener); <ide> EventEmitter.prototype.removeListener = <ide> <ide> EventEmitter.prototype.off = EventEmitter.prototype.removeListener; <ide> <add>/** <add> * Removes all listeners from the event emitter. (Only <add> * removes listeners for a specific event name if specified <add> * as `type`). <add> * @param {string | symbol} [type] <add> * @returns {EventEmitter} <add> */ <ide> EventEmitter.prototype.removeAllListeners = <ide> function removeAllListeners(type) { <ide> const events = this._events; <ide> function _listeners(target, type, unwrap) { <ide> unwrapListeners(evlistener) : arrayClone(evlistener); <ide> } <ide> <add>/** <add> * Returns a copy of the array of listeners for the event name <add> * specified as `type`. <add> * @param {string | symbol} type <add> * @returns {Function[]} <add> */ <ide> EventEmitter.prototype.listeners = function listeners(type) { <ide> return _listeners(this, type, true); <ide> }; <ide> <add>/** <add> * Returns a copy of the array of listeners and wrappers for <add> * the event name specified as `type`. <add> * @param {string | symbol} type <add> * @returns {Function[]} <add> */ <ide> EventEmitter.prototype.rawListeners = function rawListeners(type) { <ide> return _listeners(this, type, false); <ide> }; <ide> <add>/** <add> * Returns the number of listeners listening to the event name <add> * specified as `type`. <add> * @deprecated since v3.2.0 <add> * @param {EventEmitter} emitter <add> * @param {string | symbol} type <add> * @returns {number} <add> */ <ide> EventEmitter.listenerCount = function(emitter, type) { <ide> if (typeof emitter.listenerCount === 'function') { <ide> return emitter.listenerCount(type); <ide> EventEmitter.listenerCount = function(emitter, type) { <ide> }; <ide> <ide> EventEmitter.prototype.listenerCount = listenerCount; <add> <add>/** <add> * Returns the number of listeners listening to event name <add> * specified as `type`. <add> * @param {string | symbol} type <add> * @returns {number} <add> */ <ide> function listenerCount(type) { <ide> const events = this._events; <ide> <ide> function listenerCount(type) { <ide> return 0; <ide> } <ide> <add>/** <add> * Returns an array listing the events for which <add> * the emitter has registered listeners. <add> * @returns {any[]} <add> */ <ide> EventEmitter.prototype.eventNames = function eventNames() { <ide> return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; <ide> }; <ide> function unwrapListeners(arr) { <ide> return ret; <ide> } <ide> <add>/** <add> * Returns a copy of the array of listeners for the event name <add> * specified as `type`. <add> * @param {EventEmitter | EventTarget} emitterOrTarget <add> * @param {string | symbol} type <add> * @returns {Function[]} <add> */ <ide> function getEventListeners(emitterOrTarget, type) { <ide> // First check if EventEmitter <ide> if (typeof emitterOrTarget.listeners === 'function') { <ide> function getEventListeners(emitterOrTarget, type) { <ide> emitterOrTarget); <ide> } <ide> <add>/** <add> * Creates a `Promise` that is fulfilled when the emitter <add> * emits the given event. <add> * @param {EventEmitter} emitter <add> * @param {string} name <add> * @param {{ signal: AbortSignal; }} [options] <add> * @returns {Promise} <add> */ <ide> async function once(emitter, name, options = {}) { <ide> const signal = options?.signal; <ide> validateAbortSignal(signal, 'options.signal'); <ide> function eventTargetAgnosticAddListener(emitter, name, listener, flags) { <ide> } <ide> } <ide> <add>/** <add> * Returns an `AsyncIterator` that iterates `event` events. <add> * @param {EventEmitter} emitter <add> * @param {string | symbol} event <add> * @param {{ signal: AbortSignal; }} [options] <add> * @returns {AsyncIterator} <add> */ <ide> function on(emitter, event, options) { <ide> const signal = options?.signal; <ide> validateAbortSignal(signal, 'options.signal');
1
Ruby
Ruby
pull template check up to match existing behavior
ec8e0bc89ab71ed41b4e8d5234b5e09ba93480e9
<ide><path>actionview/lib/action_view/digestor.rb <ide> def compute_and_store_digest(cache_key, name, finder, options) # called under @@ <ide> end <ide> end <ide> <del> EMPTY = Class.new { <del> def name; 'missing'; end <del> def digest; ''; end <del> }.new <del> <ide> def self.tree(name, finder, partial = false, seen = {}) <ide> if obj = seen[name] <ide> obj <ide> else <ide> logical_name = name.gsub(%r|/_|, "/") <del> template = finder.disable_cache { finder.find(logical_name, [], partial) } <del> node = seen[name] = Node.new(name, logical_name, template, partial, []) <add> <add> if finder.disable_cache { finder.exists?(logical_name, [], partial) } <add> template = finder.disable_cache { finder.find(logical_name, [], partial) } <add> node = seen[name] = Node.new(name, logical_name, template, partial, []) <add> else <add> node = seen[name] = Missing.new(name, logical_name, nil, partial, []) <add> return node <add> end <add> <ide> deps = DependencyTracker.find_dependencies(name, template, finder.view_paths) <ide> deps.each do |dep_file| <del> l_name = dep_file.gsub(%r|/_|, "/") <del> if finder.disable_cache { finder.exists?(l_name, [], true) } <del> node.children << tree(dep_file, finder, true, seen) <del> else <del> node.children << Missing.new(dep_file, l_name, nil, true, []) <del> end <add> node.children << tree(dep_file, finder, true, seen) <ide> end <ide> node <ide> end <ide><path>actionview/test/template/digestor_test.rb <ide> def digest(template_name, options = {}) <ide> <ide> finder.variants = options.delete(:variants) || [] <ide> <del> ActionView::Digestor.digest({ name: template_name, finder: finder }.merge(options)) <add> node = ActionView::Digestor.tree template_name, finder <add> x = ActionView::Digestor.digest({ name: template_name, finder: finder }.merge(options)) <add> assert_equal x, node.digest <add> x <ide> end <ide> <ide> def dependencies(template_name)
2
PHP
PHP
add missing stub file
1a364bc8eb7121d595697435b2f5046d3e3856ec
<ide><path>tests/test_app/TestApp/Routing/Filter/AppendFilter.php <add><?php <add>namespace TestApp\Routing\Filter; <add> <add>use Cake\Event\Event; <add>use Cake\Network\Response; <add>use Cake\Routing\DispatcherFilter; <add> <add>class AppendFilter extends DispatcherFilter <add>{ <add> public function afterDispatch(Event $event) <add> { <add> $response = $event->data['response']; <add> $response->body($response->body() . ' appended content'); <add> } <add>}
1
Python
Python
show images from google query
152261765a93c2a12eb4af0abdd297652766d47d
<ide><path>web_programming/download_images_from_google_query.py <add>import json <add>import os <add>import re <add>import sys <add>import urllib.request <add> <add>import requests <add>from bs4 import BeautifulSoup <add> <add>headers = { <add> "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" <add> " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" <add>} <add> <add> <add>def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: <add> """Searches google using the provided query term and downloads the images in a folder. <add> <add> Args: <add> query : The image search term to be provided by the user. Defaults to <add> "dhaka". <add> image_numbers : [description]. Defaults to 5. <add> <add> Returns: <add> The number of images successfully downloaded. <add> <add> >>> download_images_from_google_query() <add> 5 <add> >>> download_images_from_google_query("potato") <add> 5 <add> """ <add> max_images = min(max_images, 50) # Prevent abuse! <add> params = { <add> "q": query, <add> "tbm": "isch", <add> "hl": "en", <add> "ijn": "0", <add> } <add> <add> html = requests.get("https://www.google.com/search", params=params, headers=headers) <add> soup = BeautifulSoup(html.text, "html.parser") <add> matched_images_data = "".join( <add> re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) <add> ) <add> <add> matched_images_data_fix = json.dumps(matched_images_data) <add> matched_images_data_json = json.loads(matched_images_data_fix) <add> <add> matched_google_image_data = re.findall( <add> r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", <add> matched_images_data_json, <add> ) <add> if not matched_google_image_data: <add> return 0 <add> <add> removed_matched_google_images_thumbnails = re.sub( <add> r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", <add> "", <add> str(matched_google_image_data), <add> ) <add> <add> matched_google_full_resolution_images = re.findall( <add> r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", <add> removed_matched_google_images_thumbnails, <add> ) <add> for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): <add> if index >= max_images: <add> return index <add> original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( <add> "unicode-escape" <add> ) <add> original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( <add> "unicode-escape" <add> ) <add> opener = urllib.request.build_opener() <add> opener.addheaders = [ <add> ( <add> "User-Agent", <add> "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" <add> " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", <add> ) <add> ] <add> urllib.request.install_opener(opener) <add> path_name = f"query_{query.replace(' ', '_')}" <add> if not os.path.exists(path_name): <add> os.makedirs(path_name) <add> urllib.request.urlretrieve( <add> original_size_img, f"{path_name}/original_size_img_{index}.jpg" <add> ) <add> return index <add> <add> <add>if __name__ == "__main__": <add> try: <add> image_count = download_images_from_google_query(sys.argv[1]) <add> print(f"{image_count} images were downloaded to disk.") <add> except IndexError: <add> print("Please provide a search term.") <add> raise
1
Python
Python
remove unused variable
5e32ad607e852ee2358352734c63fa6d7995a186
<ide><path>numpy/core/numerictypes.py <ide> def sctype2char(sctype): <ide> for key in _sctype2char_dict.keys(): <ide> cast[key] = lambda x, k=key : array(x, copy=False).astype(k) <ide> <del> <del>_unicodesize = array('u','U1').itemsize <del> <ide> # Create the typestring lookup dictionary <ide> _typestr = _typedict() <ide> for key in _sctype2char_dict.keys():
1
Python
Python
remove redundant setting of no_args_is_help
d23be563eb8ee4e72b9389e675a7e4dcb7140941
<ide><path>spacy/cli/project.py <ide> def project_update_dvc_cli( <ide> msg.info(f"No changes found in {CONFIG_FILE}, no update needed") <ide> <ide> <del>app.add_typer(project_cli, name="project", no_args_is_help=True) <add>app.add_typer(project_cli, name="project") <ide> <ide> <ide> #################
1
Python
Python
fix memory leak in tensorflow backend
80b72fa7b3ac69f821ea63a1e2a92412da188117
<ide><path>keras/backend/tensorflow_backend.py <ide> def clear_session(): <ide> reset_uids() <ide> _SESSION = None <ide> phase = tf.placeholder(dtype='bool', name='keras_learning_phase') <add> _GRAPH_LEARNING_PHASES = {} <ide> _GRAPH_LEARNING_PHASES[tf.get_default_graph()] = phase <ide> <ide>
1
PHP
PHP
fix wherenull short-cut
02920076c104b0318a6135e5e7fe230f81fc0ad9
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> // that method for convenience so the developer doesn't have to check. <ide> if (is_null($value)) <ide> { <del> return $this->whereNull($column, $boolean); <add> return $this->whereNull($column, $boolean, $operator != '='); <ide> } <ide> <ide> // Now that we are working with just a simple query we can put the elements
1
Text
Text
fix specifier example in `esm.md`
923f355855ac13545c5c61526c751eaae2975c1b
<ide><path>doc/api/esm.md <ide> This section was moved to [Modules: Packages](packages.md). <ide> ### Terminology <ide> <ide> The _specifier_ of an `import` statement is the string after the `from` keyword, <del>e.g. `'path'` in `import { sep } from 'node:path'`. Specifiers are also used in <del>`export from` statements, and as the argument to an `import()` expression. <add>e.g. `'node:path'` in `import { sep } from 'node:path'`. Specifiers are also <add>used in `export from` statements, and as the argument to an `import()` <add>expression. <ide> <ide> There are three types of specifiers: <ide>
1
Javascript
Javascript
add deprecation fixture
fce7c958ed42664923161c48bab36700631cefd2
<ide><path>test/fixtures/deprecated.js <add>require('util').p('This is deprecated');
1
Python
Python
add ukrainian unicode
402d133c906aad322e2aad2b9bcda209d4283b7e
<ide><path>spacy/lang/char_classes.py <ide> _tatar_upper = r"ӘӨҮҖҢҺ" <ide> _greek_lower = r"α-ωάέίόώήύ" <ide> _greek_upper = r"Α-ΩΆΈΊΌΏΉΎ" <add>_ukrainian_lower = r"а-щюяіїєґ" <add>_ukrainian_upper = r"А-ЩЮЯІЇЄҐ" <ide> <del>_upper = _latin_upper + _russian_upper + _tatar_upper + _greek_upper <del>_lower = _latin_lower + _russian_lower + _tatar_lower + _greek_lower <add>_upper = _latin_upper + _russian_upper + _tatar_upper + _greek_upper + _ukrainian_upper <add>_lower = _latin_lower + _russian_lower + _tatar_lower + _greek_lower + _ukrainian_lower <ide> _uncased = _bengali + _hebrew + _persian + _sinhala <ide> <ide> ALPHA = group_chars(_upper + _lower + _uncased) <ide> "кг г мг м/с км/ч кПа Па мбар Кб КБ кб Мб МБ мб Гб ГБ гб Тб ТБ тб" <ide> "كم كم² كم³ م م² م³ سم سم² سم³ مم مم² مم³ كم غرام جرام جم كغ ملغ كوب اكواب" <ide> ) <del>_currency = r"\$ £ € ¥ ฿ US\$ C\$ A\$ ₽ ﷼" <add>_currency = r"\$ £ € ¥ ฿ US\$ C\$ A\$ ₽ ﷼ ₴" <ide> <ide> # These expressions contain various unicode variations, including characters <ide> # used in Chinese (see #1333, #1340, #1351) – unless there are cross-language
1
Python
Python
authorize args when instantiating an automodel
ae6ce28f31974b64deb1c4d053704533ba8fed4b
<ide><path>src/transformers/models/auto/auto_factory.py <ide> class _BaseAutoModelClass: <ide> # Base class for auto models. <ide> _model_mapping = None <ide> <del> def __init__(self): <add> def __init__(self, *args, **kwargs): <ide> raise EnvironmentError( <ide> f"{self.__class__.__name__} is designed to be instantiated " <ide> f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
1
Ruby
Ruby
remove dead code
3e35aacbbb4f0bc9d8408aa401d5be530aa218a4
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> opoo e.message <ide> end <ide> <del> stdlibs = Keg.new(f.prefix).detect_cxx_stdlibs :skip_executables => true <ide> tab = Tab.for_keg f.prefix <ide> tab.poured_from_bottle = true <ide> tab.write
1
PHP
PHP
correct variable to unify it across the core
75473706191acfb6134bf72ed3f598cf96fe0d86
<ide><path>src/Controller/Component/Auth/CrudAuthorize.php <ide> class CrudAuthorize extends BaseAuthorize { <ide> * Sets up additional actionMap values that match the configured `Routing.prefixes`. <ide> * <ide> * @param ComponentRegistry $registry The component registry from the controller. <del> * @param array $configs An array of configs. This class does not use any configs. <add> * @param array $config An array of config. This class does not use any config. <ide> */ <del> public function __construct(ComponentRegistry $registry, $configs = array()) { <del> parent::__construct($registry, $configs); <add> public function __construct(ComponentRegistry $registry, $config = array()) { <add> parent::__construct($registry, $config); <ide> $this->_setPrefixMappings(); <ide> } <ide>
1
Python
Python
update minor version number to 9
4d5ac6936c980f8a283c44a622e414706215d269
<ide><path>setup.py <ide> AUTHOR_EMAIL = "[email protected]" <ide> PLATFORMS = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"] <ide> MAJOR = 1 <del>MINOR = 8 <add>MINOR = 9 <ide> MICRO = 0 <ide> ISRELEASED = False <ide> VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
1
Javascript
Javascript
extend timeouts for armv6
f9b226c1c1e5bfbf355f9fabe03e50333676cc05
<ide><path>test/common.js <ide> exports.platformTimeout = function(ms) { <ide> return ms; <ide> <ide> if (process.config.variables.arm_version === '6') <del> return 6 * ms; // ARMv6 <add> return 7 * ms; // ARMv6 <ide> <ide> return 2 * ms; // ARMv7 and up. <ide> }; <ide><path>test/parallel/test-child-process-fork-net2.js <ide> if (process.argv[2] === 'child') { <ide> }; <ide> <ide> var min = 190; <del> var max = common.platformTimeout(1500); <add> var max = common.platformTimeout(2000); <ide> process.on('exit', function() { <ide> assert.equal(disconnected, count); <ide> assert.equal(connected, count); <ide><path>test/parallel/test-debug-signal-cluster.js <ide> function onNoMoreLines() { <ide> <ide> setTimeout(function testTimedOut() { <ide> assert(false, 'test timed out.'); <del>}, common.platformTimeout(3000)).unref(); <add>}, common.platformTimeout(4000)).unref(); <ide> <ide> process.on('exit', function onExit() { <ide> // Kill processes in reverse order to avoid timing problems on Windows where <ide><path>test/sequential/test-next-tick-error-spin.js <ide> if (process.argv[2] !== 'child') { <ide> }); <ide> var timer = setTimeout(function() { <ide> throw new Error('child is hung'); <del> }, 3000); <add> }, common.platformTimeout(3000)); <ide> child.on('exit', function(code) { <ide> console.error('ok'); <ide> assert(!code);
4
Java
Java
fix typos in javadoc
2522fe029208b857e7b50c6621c12bfad1fd3dd0
<ide><path>spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DatabaseClient.java <ide> public interface DatabaseClient extends ConnectionAccessor { <ide> <ide> /** <ide> * Specify a {@link Supplier SQL supplier} that provides SQL to run. <del> * Contract for specifying a SQL call along with options leading to <add> * Contract for specifying an SQL call along with options leading to <ide> * the execution. The SQL string can contain either native parameter <ide> * bind markers or named parameters (e.g. {@literal :foo, :bar}) when <ide> * {@link NamedParameterExpander} is enabled. <ide> interface Builder { <ide> <ide> <ide> /** <del> * Contract for specifying a SQL call along with options leading to the execution. <add> * Contract for specifying an SQL call along with options leading to the execution. <ide> */ <ide> interface GenericExecuteSpec { <ide> <ide><path>spring-r2dbc/src/main/java/org/springframework/r2dbc/core/QueryOperation.java <ide> /** <ide> * Interface declaring a query operation that can be represented <ide> * with a query string. This interface is typically implemented <del> * by classes representing a SQL operation such as {@code SELECT}, <add> * by classes representing an SQL operation such as {@code SELECT}, <ide> * {@code INSERT}, and such. <ide> * <ide> * @author Mark Paluch
2
Javascript
Javascript
throw invalid argument errors
1f209129c7e6c3ec6628809821fc9a36deae7ec8
<ide><path>lib/_stream_writable.js <ide> Writable.prototype.write = function(chunk, encoding, cb) { <ide> cb = nop; <ide> } <ide> <del> let err; <del> if (state.ending) { <del> err = new ERR_STREAM_WRITE_AFTER_END(); <del> } else if (state.destroyed) { <del> err = new ERR_STREAM_DESTROYED('write'); <del> } else if (chunk === null) { <del> err = new ERR_STREAM_NULL_VALUES(); <add> if (chunk === null) { <add> throw new ERR_STREAM_NULL_VALUES(); <ide> } else if (!state.objectMode) { <ide> if (typeof chunk === 'string') { <ide> if (state.decodeStrings !== false) { <ide> Writable.prototype.write = function(chunk, encoding, cb) { <ide> chunk = Stream._uint8ArrayToBuffer(chunk); <ide> encoding = 'buffer'; <ide> } else { <del> err = new ERR_INVALID_ARG_TYPE( <add> throw new ERR_INVALID_ARG_TYPE( <ide> 'chunk', ['string', 'Buffer', 'Uint8Array'], chunk); <ide> } <ide> } <ide> <add> let err; <add> if (state.ending) { <add> err = new ERR_STREAM_WRITE_AFTER_END(); <add> } else if (state.destroyed) { <add> err = new ERR_STREAM_DESTROYED('write'); <add> } <add> <ide> if (err) { <ide> process.nextTick(cb, err); <ide> errorOrDestroy(this, err, true); <ide><path>test/parallel/test-fs-write-stream.js <ide> tmpdir.refresh(); <ide> // Throws if data is not of type Buffer. <ide> { <ide> const stream = fs.createWriteStream(file); <del> stream.on('error', common.expectsError({ <add> stream.on('error', common.mustNotCall()); <add> assert.throws(() => { <add> stream.write(42); <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <del> })); <del> stream.write(42, null, common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError' <del> })); <add> }); <ide> stream.destroy(); <ide> } <ide><path>test/parallel/test-net-socket-write-error.js <ide> <ide> const common = require('../common'); <ide> const net = require('net'); <add>const assert = require('assert'); <ide> <ide> const server = net.createServer().listen(0, connectToServer); <ide> <ide> function connectToServer() { <ide> const client = net.createConnection(this.address().port, () => { <del> client.write(1337, common.expectsError({ <add> client.on('error', common.mustNotCall()); <add> assert.throws(() => { <add> client.write(1337); <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <del> })); <del> client.on('error', common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError' <del> })); <add> }); <ide> <ide> client.destroy(); <ide> }) <ide><path>test/parallel/test-net-write-arguments.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const net = require('net'); <del> <add>const assert = require('assert'); <ide> const socket = net.Stream({ highWaterMark: 0 }); <ide> <ide> // Make sure that anything besides a buffer or a string throws. <del>socket.write(null, common.expectsError({ <add>socket.on('error', common.mustNotCall()); <add>assert.throws(() => { <add> socket.write(null); <add>}, { <ide> code: 'ERR_STREAM_NULL_VALUES', <ide> name: 'TypeError', <ide> message: 'May not write null values to stream' <del>})); <del>socket.on('error', common.expectsError({ <del> code: 'ERR_STREAM_NULL_VALUES', <del> name: 'TypeError', <del> message: 'May not write null values to stream' <del>})); <add>}); <ide> <ide> [ <ide> true, <ide> socket.on('error', common.expectsError({ <ide> ].forEach((value) => { <ide> // We need to check the callback since 'error' will only <ide> // be emitted once per instance. <del> socket.write(value, common.expectsError({ <add> assert.throws(() => { <add> socket.write(value); <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <ide> message: 'The "chunk" argument must be of type string or an instance of ' + <ide> `Buffer or Uint8Array.${common.invalidArgTypeHelper(value)}` <del> })); <add> }); <ide> }); <ide><path>test/parallel/test-stream-writable-invalid-chunk.js <ide> <ide> const common = require('../common'); <ide> const stream = require('stream'); <add>const assert = require('assert'); <ide> <ide> function testWriteType(val, objectMode, code) { <ide> const writable = new stream.Writable({ <ide> objectMode, <ide> write: () => {} <ide> }); <del> if (!code) { <del> writable.on('error', common.mustNotCall()); <add> writable.on('error', common.mustNotCall()); <add> if (code) { <add> assert.throws(() => { <add> writable.write(val); <add> }, { code }); <ide> } else { <del> writable.on('error', common.expectsError({ <del> code: code, <del> })); <add> writable.write(val); <ide> } <del> writable.write(val); <ide> } <ide> <ide> testWriteType([], false, 'ERR_INVALID_ARG_TYPE'); <ide><path>test/parallel/test-stream-writable-null.js <ide> class MyWritable extends stream.Writable { <ide> <ide> { <ide> const m = new MyWritable({ objectMode: true }); <del> m.write(null, (err) => assert.ok(err)); <del> m.on('error', common.expectsError({ <del> code: 'ERR_STREAM_NULL_VALUES', <del> name: 'TypeError', <del> message: 'May not write null values to stream' <del> })); <del>} <del> <del>{ // Should not throw. <del> const m = new MyWritable({ objectMode: true }).on('error', assert); <del> m.write(null, assert); <add> m.on('error', common.mustNotCall()); <add> assert.throws(() => { <add> m.write(null); <add> }, { <add> code: 'ERR_STREAM_NULL_VALUES' <add> }); <ide> } <ide> <ide> { <ide> const m = new MyWritable(); <del> m.write(false, (err) => assert.ok(err)); <del> m.on('error', common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError' <del> })); <del>} <del> <del>{ // Should not throw. <del> const m = new MyWritable().on('error', assert); <del> m.write(false, assert); <add> m.on('error', common.mustNotCall()); <add> assert.throws(() => { <add> m.write(false); <add> }, { <add> code: 'ERR_INVALID_ARG_TYPE' <add> }); <ide> } <ide> <ide> { // Should not throw. <ide><path>test/parallel/test-stream-writable-write-error.js <ide> const assert = require('assert'); <ide> <ide> const { Writable } = require('stream'); <ide> <del>function expectError(w, arg, code) { <del> let errorCalled = false; <del> let ticked = false; <del> w.write(arg, common.mustCall((err) => { <del> assert.strictEqual(ticked, true); <del> assert.strictEqual(errorCalled, false); <del> assert.strictEqual(err.code, code); <del> })); <del> ticked = true; <del> w.on('error', common.mustCall((err) => { <del> errorCalled = true; <del> assert.strictEqual(err.code, code); <del> })); <add>function expectError(w, arg, code, sync) { <add> if (sync) { <add> if (code) { <add> assert.throws(() => w.write(arg), { code }); <add> } else { <add> w.write(arg); <add> } <add> } else { <add> let errorCalled = false; <add> let ticked = false; <add> w.write(arg, common.mustCall((err) => { <add> assert.strictEqual(ticked, true); <add> assert.strictEqual(errorCalled, false); <add> assert.strictEqual(err.code, code); <add> })); <add> ticked = true; <add> w.on('error', common.mustCall((err) => { <add> errorCalled = true; <add> assert.strictEqual(err.code, code); <add> })); <add> } <ide> } <ide> <ide> function test(autoDestroy) { <ide> function test(autoDestroy) { <ide> autoDestroy, <ide> _write() {} <ide> }); <del> expectError(w, null, 'ERR_STREAM_NULL_VALUES'); <add> expectError(w, null, 'ERR_STREAM_NULL_VALUES', true); <ide> } <ide> <ide> { <ide> const w = new Writable({ <ide> autoDestroy, <ide> _write() {} <ide> }); <del> expectError(w, {}, 'ERR_INVALID_ARG_TYPE'); <add> expectError(w, {}, 'ERR_INVALID_ARG_TYPE', true); <ide> } <ide> } <ide> <ide><path>test/parallel/test-stream2-writable.js <ide> const helloWorldBuffer = Buffer.from('hello world'); <ide> { <ide> // Verify that error is only emitted once when failing in write. <ide> const w = new W(); <del> w.on('error', common.mustCall((err) => { <del> assert.strictEqual(w._writableState.errorEmitted, true); <del> assert.strictEqual(err.code, 'ERR_STREAM_NULL_VALUES'); <del> })); <del> w.write(null); <del> w.destroy(new Error()); <add> w.on('error', common.mustNotCall()); <add> assert.throws(() => { <add> w.write(null); <add> }, { <add> code: 'ERR_STREAM_NULL_VALUES' <add> }); <ide> } <ide> <ide> { <ide><path>test/parallel/test-zlib-invalid-input.js <ide> const unzips = [ <ide> ]; <ide> <ide> nonStringInputs.forEach(common.mustCall((input) => { <del> // zlib.gunzip should not throw an error when called with bad input. <del> zlib.gunzip(input, (err, buffer) => { <del> // zlib.gunzip should pass the error to the callback. <del> assert.ok(err); <add> assert.throws(() => { <add> zlib.gunzip(input); <add> }, { <add> name: 'TypeError', <add> code: 'ERR_INVALID_ARG_TYPE' <ide> }); <ide> }, nonStringInputs.length)); <ide> <ide><path>test/parallel/test-zlib-object-write.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>const assert = require('assert'); <ide> const { Gunzip } = require('zlib'); <ide> <ide> const gunzip = new Gunzip({ objectMode: true }); <del>gunzip.write({}, common.expectsError({ <del> name: 'TypeError' <del>})); <del>gunzip.on('error', common.expectsError({ <del> name: 'TypeError' <del>})); <add>gunzip.on('error', common.mustNotCall()); <add>assert.throws(() => { <add> gunzip.write({}); <add>}, { <add> name: 'TypeError', <add> code: 'ERR_INVALID_ARG_TYPE' <add>});
10
Python
Python
fix shapes in model docstrings
426b96230a71f3c6e4decabae131c6e4f8bf4f5c
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under <ide> returned tensors for more detail. <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> encoder_hidden_states (`torch.FloatTensor`): <del> cross attention input to the layer of shape *(batch, seq_len, embed_dim)* <add> cross attention input to the layer of shape `(batch, seq_len, embed_dim)` <ide> encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of <del> size *(decoder_attention_heads,)*. <add> size `(decoder_attention_heads,)`. <ide> past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under <ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under <ide> returned tensors for more detail. <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> encoder_hidden_states (`torch.FloatTensor`): <del> cross attention input to the layer of shape *(batch, seq_len, embed_dim)* <add> cross attention input to the layer of shape `(batch, seq_len, embed_dim)` <ide> encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of <del> size *(decoder_attention_heads,)*. <add> size `(decoder_attention_heads,)`. <ide> past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under <ide><path>src/transformers/models/marian/modeling_marian.py <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under <ide> returned tensors for more detail. <ide> def forward( <ide> ): <ide> """ <ide> Args: <del> hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)* <add> hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` <ide> attention_mask (`torch.FloatTensor`): attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> encoder_hidden_states (`torch.FloatTensor`): <del> cross attention input to the layer of shape *(batch, seq_len, embed_dim)* <add> cross attention input to the layer of shape `(batch, seq_len, embed_dim)` <ide> encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size <del> *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. <add> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <ide> layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size <del> *(encoder_attention_heads,)*. <add> `(encoder_attention_heads,)`. <ide> cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of <del> size *(decoder_attention_heads,)*. <add> size `(decoder_attention_heads,)`. <ide> past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (`bool`, *optional*): <ide> Whether or not to return the attentions tensors of all attention layers. See `attentions` under
3
Javascript
Javascript
add support for additional euler rotation orders
0825c1f612f9b77c6e6926ebb07aa839d92b9043
<ide><path>src/core/Matrix4.js <ide> THREE.Matrix4.prototype = { <ide> <ide> }, <ide> <del> setRotationFromEuler: function( v ) { <add> setRotationFromEuler: function( v, order ) { <ide> <ide> var x = v.x, y = v.y, z = v.z, <ide> a = Math.cos( x ), b = Math.sin( x ), <ide> c = Math.cos( y ), d = Math.sin( y ), <del> e = Math.cos( z ), f = Math.sin( z ), <del> ad = a * d, bd = b * d; <add> e = Math.cos( z ), f = Math.sin( z ); <ide> <del> this.n11 = c * e; <del> this.n12 = - c * f; <del> this.n13 = d; <add> switch ( order ) { <add> case 'YXZ': <add> var ce = c * e, cf = c * f, de = d * e, df = d * f; <ide> <del> this.n21 = bd * e + a * f; <del> this.n22 = - bd * f + a * e; <del> this.n23 = - b * c; <add> this.n11 = ce + df * b; <add> this.n12 = de * b - cf; <add> this.n13 = a * d; <ide> <del> this.n31 = - ad * e + b * f; <del> this.n32 = ad * f + b * e; <del> this.n33 = a * c; <add> this.n21 = a * f; <add> this.n22 = a * e; <add> this.n23 = - b; <add> <add> this.n31 = cf * b - de; <add> this.n32 = df + ce * b; <add> this.n33 = a * c; <add> break; <add> <add> case 'ZXY': <add> var ce = c * e, cf = c * f, de = d * e, df = d * f; <add> <add> this.n11 = ce - df * b; <add> this.n12 = - a * f; <add> this.n13 = de + cf * b; <add> <add> this.n21 = cf + de * b; <add> this.n22 = a * e; <add> this.n23 = df - ce * b; <add> <add> this.n31 = - a * d; <add> this.n32 = b; <add> this.n33 = a * c; <add> break; <add> <add> case 'ZYX': <add> var ae = a * e, af = a * f, be = b * e, bf = b * f; <add> <add> this.n11 = c * e; <add> this.n12 = be * d - af; <add> this.n13 = ae * d + bf; <add> <add> this.n21 = c * f; <add> this.n22 = bf * d + ae; <add> this.n23 = af * d - be; <add> <add> this.n31 = - d; <add> this.n32 = b * c; <add> this.n33 = a * c; <add> break; <add> <add> case 'YZX': <add> var ac = a * c, ad = a * d, bc = b * c, bd = b * d; <add> <add> this.n11 = c * e; <add> this.n12 = bd - ac * f; <add> this.n13 = bc * f + ad; <add> <add> this.n21 = f; <add> this.n22 = a * e; <add> this.n23 = - b * e; <add> <add> this.n31 = - d * e; <add> this.n32 = ad * f + bc; <add> this.n33 = ac - bd * f; <add> break; <add> <add> case 'XZY': <add> var ac = a * c, ad = a * d, bc = b * c, bd = b * d; <add> <add> this.n11 = c * e; <add> this.n12 = - f; <add> this.n13 = d * e; <add> <add> this.n21 = ac * f + bd; <add> this.n22 = a * e; <add> this.n23 = ad * f - bc; <add> <add> this.n31 = bc * f - ad; <add> this.n32 = b * e; <add> this.n33 = bd * f + ac; <add> break; <add> <add> default: // 'XYZ' <add> var ae = a * e, af = a * f, be = b * e, bf = b * f; <add> <add> this.n11 = c * e; <add> this.n12 = - c * f; <add> this.n13 = d; <add> <add> this.n21 = af + be * d; <add> this.n22 = ae - bf * d; <add> this.n23 = - b * c; <add> <add> this.n31 = bf - ae * d; <add> this.n32 = be + af * d; <add> this.n33 = a * c; <add> break; <add> } <ide> <ide> return this; <ide> <ide> }, <ide> <add> <ide> setRotationFromQuaternion: function( q ) { <ide> <ide> var x = q.x, y = q.y, z = q.z, w = q.w, <ide><path>src/core/Object3D.js <ide> THREE.Object3D = function() { <ide> <ide> this.position = new THREE.Vector3(); <ide> this.rotation = new THREE.Vector3(); <add> this.eulerOrder = 'XYZ'; <ide> this.scale = new THREE.Vector3( 1, 1, 1 ); <ide> <ide> this.dynamic = false; // when true it retains arrays so they can be updated with __dirty* <ide> THREE.Object3D.prototype = { <ide> <ide> } else { <ide> <del> this.matrix.setRotationFromEuler( this.rotation ); <add> this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder ); <ide> <ide> } <ide>
2
Text
Text
update the document error
edf0da968ca8d653a6e4c9333e55530305cb3625
<ide><path>experimental/vlan-networks.md <ide> <ide> The Macvlan and Ipvlan drivers are currently in experimental mode in order to incubate Docker users use cases and vet the implementation to ensure a hardened, production ready driver in a future release. Libnetwork now gives users total control over both IPv4 and IPv6 adressing. The VLAN drivers build on top of that in giving operators complete control of layer 2 VLAN tagging and even Ipvlan L3 routing for users interested in underlay network integration. For overlay deployments that abstract away physical constraints see the [multi-host overlay ](https://docs.docker.com/engine/userguide/networking/get-started-overlay/) driver. <ide> <del>Macvlan and Ipvlan are a new twist on the tried and true network virtualization technique. The Linux implementations are extremely lightweight because rather then using the traditional Linux bridge for isolation, they are simply associated to a Linux Ethernet interface or sub-interface to enforce seperation between networks and connectivty to the physical network. <add>Macvlan and Ipvlan are a new twist on the tried and true network virtualization technique. The Linux implementations are extremely lightweight because rather than using the traditional Linux bridge for isolation, they are simply associated to a Linux Ethernet interface or sub-interface to enforce seperation between networks and connectivity to the physical network. <ide> <ide> Macvlan and Ipvlan offer a number of unique features and plenty of room for further innovations with the various modes. Two high level advantages of these approaches are, the positive performance implications of bypassing the Linux bridge and the simplicity of having less moving parts. Removing the bridge that traditionally resides in between the Docker host NIC and container interface leaves a very simple setup consisting of container interfaces, attached directly to the Docker host interface. This result is easy access for external facing services as there is no port mappings in these scenarios. <ide>
1
Text
Text
fix mistakes in the custom server doc
a3925b5865f6959ed1334e2a707279437fcb3b89
<ide><path>docs/advanced-features/custom-server.md <ide> description: Start a Next.js app programmatically using a custom server. <ide> <ide> Typically you start your next server with `next start`. It's possible, however, to start a server 100% programmatically in order to use custom route patterns. <ide> <del>> Before deciding to use a custom a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like **serverless functions** and **[Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md).** <add>> Before deciding to use a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like **serverless functions** and **[Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md).** <ide> <ide> Take a look at the following example of a custom server: <ide> <ide> const app = next({}) <ide> <ide> The above `next` import is a function that receives an object with the following options: <ide> <del>- `dev`: `Boolean` - Whether or not to launch Next.js in dev mode. Defaults `false` <add>- `dev`: `Boolean` - Whether or not to launch Next.js in dev mode. Defaults to `false` <ide> - `dir`: `String` - Location of the Next.js project. Defaults to `'.'` <ide> - `quiet`: `Boolean` - Hide error messages containing server information. Defaults to `false` <ide> - `conf`: `object` - The same object you would use in [next.config.js](/docs/api-reference/next.config.js/introduction.md). Defaults to `{}` <ide> The returned `app` can then be used to let Next.js handle requests as required. <ide> <ide> By default, `Next` will serve each file in the `pages` folder under a pathname matching the filename. If your project uses a custom server, this behavior may result in the same content being served from multiple paths, which can present problems with SEO and UX. <ide> <del>To disable this behavior & prevent routing based on files in `pages`, open `next.config.js` and disable the `useFileSystemPublicRoutes` config: <add>To disable this behavior and prevent routing based on files in `pages`, open `next.config.js` and disable the `useFileSystemPublicRoutes` config: <ide> <ide> ```js <ide> module.exports = {
1
PHP
PHP
set default value for property
c93c821b5777c0008d8616ef54ce973e978e4948
<ide><path>src/Http/Runner.php <ide> class Runner implements RequestHandlerInterface <ide> * <ide> * @var int <ide> */ <del> protected $index; <add> protected $index = 0; <ide> <ide> /** <ide> * The middleware queue being run.
1
Ruby
Ruby
add comment for image-spec pin
ecc705803f0d78b5a702a313d247c59135016347
<ide><path>Library/Homebrew/github_packages.rb <ide> def load_schemas! <ide> end <ide> <ide> def schema_uri(basename, uris) <add> # The current `main` version has an invalid JSON schema. <add> # Going forward, this should probably be pinned to tags. <add> # We currently use features newer than the last one (v1.0.2). <ide> url = "https://raw.githubusercontent.com/opencontainers/image-spec/170393e57ed656f7f81c3070bfa8c3346eaa0a5a/schema/#{basename}.json" <ide> out, = curl_output(url) <ide> json = JSON.parse(out)
1
Go
Go
remove unused functions parameters
723f587b56b940ac5ea79e567b47da91270955b1
<ide><path>graph/graph.go <ide> func (graph *Graph) Register(img *image.Image, layerData io.Reader) (err error) <ide> // (FIXME: make that mandatory for drivers). <ide> graph.driver.Remove(img.ID) <ide> <del> tmp, err := graph.mktemp("") <add> tmp, err := graph.mktemp() <ide> defer os.RemoveAll(tmp) <ide> if err != nil { <ide> return fmt.Errorf("mktemp failed: %s", err) <ide> func (graph *Graph) TempLayerArchive(id string, sf *streamformatter.StreamFormat <ide> if err != nil { <ide> return nil, err <ide> } <del> tmp, err := graph.mktemp("") <add> tmp, err := graph.mktemp() <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (graph *Graph) TempLayerArchive(id string, sf *streamformatter.StreamFormat <ide> } <ide> <ide> // mktemp creates a temporary sub-directory inside the graph's filesystem. <del>func (graph *Graph) mktemp(id string) (string, error) { <add>func (graph *Graph) mktemp() (string, error) { <ide> dir := filepath.Join(graph.root, "_tmp", stringid.GenerateNonCryptoID()) <ide> if err := system.MkdirAll(dir, 0700); err != nil { <ide> return "", err <ide> func (graph *Graph) mktemp(id string) (string, error) { <ide> } <ide> <ide> func (graph *Graph) newTempFile() (*os.File, error) { <del> tmp, err := graph.mktemp("") <add> tmp, err := graph.mktemp() <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (graph *Graph) Delete(name string) error { <ide> if err != nil { <ide> return err <ide> } <del> tmp, err := graph.mktemp("") <add> tmp, err := graph.mktemp() <ide> graph.idIndex.Delete(id) <ide> if err == nil { <ide> if err := os.Rename(graph.imageRoot(id), tmp); err != nil { <ide><path>graph/pull_v1.go <ide> func (p *v1Puller) pullRepository(askedTag string) error { <ide> for _, ep := range p.repoInfo.Index.Mirrors { <ide> ep += "v1/" <ide> broadcaster.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) <del> if isDownloaded, err = p.pullImage(broadcaster, img.ID, ep, repoData.Tokens); err != nil { <add> if isDownloaded, err = p.pullImage(broadcaster, img.ID, ep); err != nil { <ide> // Don't report errors when pulling from mirrors. <ide> logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err) <ide> continue <ide> func (p *v1Puller) pullRepository(askedTag string) error { <ide> if !success { <ide> for _, ep := range repoData.Endpoints { <ide> broadcaster.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) <del> if isDownloaded, err = p.pullImage(broadcaster, img.ID, ep, repoData.Tokens); err != nil { <add> if isDownloaded, err = p.pullImage(broadcaster, img.ID, ep); err != nil { <ide> // It's not ideal that only the last error is returned, it would be better to concatenate the errors. <ide> // As the error is also given to the output stream the user will see the error. <ide> lastErr = err <ide> func (p *v1Puller) pullRepository(askedTag string) error { <ide> return nil <ide> } <ide> <del>func (p *v1Puller) pullImage(out io.Writer, imgID, endpoint string, token []string) (layersDownloaded bool, err error) { <add>func (p *v1Puller) pullImage(out io.Writer, imgID, endpoint string) (layersDownloaded bool, err error) { <ide> var history []string <ide> history, err = p.session.GetRemoteHistory(imgID, endpoint) <ide> if err != nil { <ide><path>graph/push_v1.go <ide> func (s *TagStore) createImageIndex(images []string, tags map[string][]string) [ <ide> type imagePushData struct { <ide> id string <ide> endpoint string <del> tokens []string <ide> } <ide> <ide> // lookupImageOnEndpoint checks the specified endpoint to see if an image exists <ide> func (p *v1Pusher) pushImageToEndpoint(endpoint string, imageIDs []string, tags <ide> imageData <- imagePushData{ <ide> id: id, <ide> endpoint: endpoint, <del> tokens: repo.Tokens, <ide> } <ide> } <ide> // close the channel to notify the workers that there will be no more images to check. <ide> func (p *v1Pusher) pushImageToEndpoint(endpoint string, imageIDs []string, tags <ide> // is very important that is why we are still iterating over the ordered list of imageIDs. <ide> for _, id := range imageIDs { <ide> if _, push := shouldPush[id]; push { <del> if _, err := p.pushImage(id, endpoint, repo.Tokens); err != nil { <add> if _, err := p.pushImage(id, endpoint); err != nil { <ide> // FIXME: Continue on error? <ide> return err <ide> } <ide> func (p *v1Pusher) pushRepository(tag string) error { <ide> return err <ide> } <ide> <del>func (p *v1Pusher) pushImage(imgID, ep string, token []string) (checksum string, err error) { <add>func (p *v1Pusher) pushImage(imgID, ep string) (checksum string, err error) { <ide> jsonRaw, err := p.graph.RawJSON(imgID) <ide> if err != nil { <ide> return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err)
3
Ruby
Ruby
restore connection pools after transactional tests
054e19d08638e64fa9eacc9be32fb7fde4e7415c
<ide><path>activerecord/lib/active_record/test_fixtures.rb <ide> def setup_fixtures(config = ActiveRecord::Base) <ide> <ide> # Load fixtures once and begin transaction. <ide> if run_in_transaction? <add> @legacy_saved_pool_configs = Hash.new { |hash, key| hash[key] = {} } <add> @saved_pool_configs = Hash.new { |hash, key| hash[key] = {} } <add> <ide> if @@already_loaded_fixtures[self.class] <ide> @loaded_fixtures = @@already_loaded_fixtures[self.class] <ide> else <ide> def teardown_fixtures <ide> connection.pool.lock_thread = false <ide> end <ide> @fixture_connections.clear <add> teardown_shared_connection_pool <ide> else <ide> ActiveRecord::FixtureSet.reset_cache <ide> end <ide> def setup_shared_connection_pool <ide> return unless writing_pool_manager <ide> <ide> pool_manager = handler.send(:owner_to_pool_manager)[name] <add> @legacy_saved_pool_configs[handler][name] ||= {} <ide> pool_manager.shard_names.each do |shard_name| <ide> writing_pool_config = writing_pool_manager.get_pool_config(nil, shard_name) <add> pool_config = pool_manager.get_pool_config(nil, shard_name) <add> next if pool_config == writing_pool_config <add> <add> @legacy_saved_pool_configs[handler][name][shard_name] = pool_config <ide> pool_manager.set_pool_config(nil, shard_name, writing_pool_config) <ide> end <ide> end <ide> def setup_shared_connection_pool <ide> pool_manager = handler.send(:owner_to_pool_manager)[name] <ide> pool_manager.shard_names.each do |shard_name| <ide> writing_pool_config = pool_manager.get_pool_config(ActiveRecord::Base.writing_role, shard_name) <add> @saved_pool_configs[name][shard_name] ||= {} <ide> pool_manager.role_names.each do |role| <del> next unless pool_manager.get_pool_config(role, shard_name) <add> next unless pool_config = pool_manager.get_pool_config(role, shard_name) <add> next if pool_config == writing_pool_config <add> <add> @saved_pool_configs[name][shard_name][role] = pool_config <ide> pool_manager.set_pool_config(role, shard_name, writing_pool_config) <ide> end <ide> end <ide> end <ide> end <ide> end <ide> <add> def teardown_shared_connection_pool <add> if ActiveRecord::Base.legacy_connection_handling <add> @legacy_saved_pool_configs.each_pair do |handler, names| <add> names.each_pair do |name, shards| <add> shards.each_pair do |shard_name, pool_config| <add> pool_manager = handler.send(:owner_to_pool_manager)[name] <add> pool_manager.set_pool_config(nil, shard_name, pool_config) <add> end <add> end <add> end <add> else <add> handler = ActiveRecord::Base.connection_handler <add> <add> @saved_pool_configs.each_pair do |name, shards| <add> pool_manager = handler.send(:owner_to_pool_manager)[name] <add> shards.each_pair do |shard_name, roles| <add> roles.each_pair do |role, pool_config| <add> next unless pool_manager.get_pool_config(role, shard_name) <add> <add> pool_manager.set_pool_config(role, shard_name, pool_config) <add> end <add> end <add> end <add> end <add> <add> @legacy_saved_pool_configs.clear <add> @saved_pool_configs.clear <add> end <add> <ide> def load_fixtures(config) <ide> ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config).index_by(&:name) <ide> end <ide><path>activerecord/test/cases/fixtures_test.rb <ide> def test_writing_and_reading_connections_are_the_same <ide> ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).connection <ide> <ide> assert_equal rw_conn, ro_conn <add> <add> teardown_shared_connection_pool <add> <add> rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing).connection <add> ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).connection <add> <add> assert_not_equal rw_conn, ro_conn <ide> end <ide> <ide> def test_writing_and_reading_connections_are_the_same_for_non_default_shards <ide> def test_writing_and_reading_connections_are_the_same_for_non_default_shards <ide> ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).connection <ide> <ide> assert_equal rw_conn, ro_conn <add> <add> teardown_shared_connection_pool <add> <add> rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing, shard: :two).connection <add> ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).connection <add> <add> assert_not_equal rw_conn, ro_conn <ide> end <ide> <ide> def test_only_existing_connections_are_replaced <ide> def test_only_existing_connections_are_replaced <ide> end <ide> end <ide> <add> def test_only_existing_connections_are_restored <add> clean_up_connection_handler <add> teardown_shared_connection_pool <add> <add> assert_raises(ActiveRecord::ConnectionNotEstablished) do <add> ActiveRecord::Base.connected_to(role: :reading) do <add> ActiveRecord::Base.retrieve_connection <add> end <add> end <add> end <add> <ide> private <ide> def config <ide> { "default" => default_config, "readonly" => readonly_config } <ide> def test_writing_and_reading_connections_are_the_same_with_legacy_handling <ide> ro_conn = reading.retrieve_connection_pool("ActiveRecord::Base").connection <ide> <ide> assert_equal rw_conn, ro_conn <add> <add> teardown_shared_connection_pool <add> <add> rw_conn = writing.retrieve_connection_pool("ActiveRecord::Base").connection <add> ro_conn = reading.retrieve_connection_pool("ActiveRecord::Base").connection <add> <add> assert_not_equal rw_conn, ro_conn <ide> end <ide> <ide> def test_writing_and_reading_connections_are_the_same_for_non_default_shards_with_legacy_handling <ide> def test_writing_and_reading_connections_are_the_same_for_non_default_shards_wit <ide> ro_conn = reading.retrieve_connection_pool("ActiveRecord::Base", shard: :two).connection <ide> <ide> assert_equal rw_conn, ro_conn <add> <add> teardown_shared_connection_pool <add> <add> rw_conn = writing.retrieve_connection_pool("ActiveRecord::Base", shard: :two).connection <add> ro_conn = reading.retrieve_connection_pool("ActiveRecord::Base", shard: :two).connection <add> <add> assert_not_equal rw_conn, ro_conn <ide> end <ide> <ide> def test_only_existing_connections_are_replaced <ide> def test_only_existing_connections_are_replaced <ide> end <ide> end <ide> <add> def test_only_existing_connections_are_restored <add> clean_up_legacy_connection_handlers <add> teardown_shared_connection_pool <add> <add> assert_raises(ActiveRecord::ConnectionNotEstablished) do <add> ActiveRecord::Base.connected_to(role: :reading) do <add> ActiveRecord::Base.retrieve_connection <add> end <add> end <add> end <add> <ide> private <ide> def config <ide> { "default" => default_config, "readonly" => readonly_config }
2
Javascript
Javascript
fix ember.setpath when used on ember.namespaces
7049d29b8abab8f72117e6b99739cda97f7d59fb
<ide><path>packages/ember-metal/lib/accessors.js <ide> Ember.getPath = function(root, path) { <ide> Ember.setPath = function(root, path, value, tolerant) { <ide> var keyName; <ide> <del> if (IS_GLOBAL.test(root)) { <add> if (typeof root === 'string' && IS_GLOBAL.test(root)) { <ide> value = path; <ide> path = root; <ide> root = null; <ide><path>packages/ember-metal/tests/accessors/setPath_test.js <ide> var obj, moduleOpts = { <ide> <ide> module('Ember.setPath', moduleOpts); <ide> <add>test('[Foo, bar] -> Foo.bar', function() { <add> window.Foo = {toString: function() { return 'Foo'; }}; // Behave like an Ember.Namespace <add> Ember.setPath(Foo, 'bar', 'baz'); <add> equal(Ember.getPath(Foo, 'bar'), 'baz'); <add> delete window.Foo; <add>}); <add> <ide> // .......................................................... <ide> // LOCAL PATHS <ide> //
2
Python
Python
add flax mbart in auto seq2seq lm
fc3551a6d72e4126068aa2adf6fc8cb1cf1941ce
<ide><path>src/transformers/models/auto/modeling_flax_auto.py <ide> [ <ide> # Model for Seq2Seq Causal LM mapping <ide> ("bart", "FlaxBartForConditionalGeneration"), <add> ("mbart", "FlaxMBartForConditionalGeneration"), <ide> ("t5", "FlaxT5ForConditionalGeneration"), <ide> ("mt5", "FlaxMT5ForConditionalGeneration"), <ide> ("marian", "FlaxMarianMTModel"),
1
Ruby
Ruby
enable deterministic archive generation
6337dbfac948e3c5fbfc25477fbe33d5b2b41703
<ide><path>Library/Homebrew/extend/os/mac/extend/ENV/super.rb <ide> def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_a <ide> # The tools in /usr/bin proxy to the active developer directory. <ide> # This means we can use them for any combination of CLT and Xcode. <ide> self["HOMEBREW_PREFER_CLT_PROXIES"] = "1" <add> <add> # Deterministic timestamping. <add> # This can work on older Xcode versions, but they contain some bugs. <add> # Notably, Xcode 10.2 fixes issues where ZERO_AR_DATE affected file mtimes. <add> # Xcode 11.0 contains fixes for lldb reading things built with ZERO_AR_DATE. <add> self["ZERO_AR_DATE"] = "1" if MacOS::Xcode.version >= "11.0" || MacOS::CLT.version >= "11.0" <ide> end <ide> <ide> def no_weak_imports
1
Python
Python
validate the return code of `test_full_reimport`
1ff314dc000cb0a7a1bb2823d3bc3ac4171f9d16
<ide><path>numpy/tests/test_reloading.py <ide> def test_full_reimport(): <ide> with warns(UserWarning): <ide> import numpy as np <ide> """) <del> p = subprocess.run([sys.executable, '-c', code]) <del> <add> p = subprocess.run([sys.executable, '-c', code], capture_output=True) <add> if p.returncode: <add> raise AssertionError( <add> f"Non-zero return code: {p.returncode!r}\n\n{p.stderr.decode()}" <add> )
1
Python
Python
replace filters with list comprehensions
9a73697c70e667c4655a01d3f76e5a9e850f1798
<ide><path>numpy/distutils/command/build_py.py <ide> def find_package_modules(self, package, package_dir): <ide> <ide> def find_modules(self): <ide> old_py_modules = self.py_modules[:] <del> new_py_modules = list(filter(is_string, self.py_modules)) <add> new_py_modules = [_m for _m in self.py_modules if is_string(_m)] <ide> self.py_modules[:] = new_py_modules <ide> modules = old_build_py.find_modules(self) <ide> self.py_modules[:] = old_py_modules <ide><path>numpy/distutils/misc_util.py <ide> def general_source_directories_files(top_path): <ide> def get_ext_source_files(ext): <ide> # Get sources and any include files in the same directory. <ide> filenames = [] <del> sources = list(filter(is_string, ext.sources)) <add> sources = [_m for _m in ext.sources if is_string(_m)] <ide> filenames.extend(sources) <ide> filenames.extend(get_dependencies(sources)) <ide> for d in ext.depends: <ide> def get_ext_source_files(ext): <ide> return filenames <ide> <ide> def get_script_files(scripts): <del> scripts = list(filter(is_string, scripts)) <add> scripts = [_m for _m in scripts if is_string(_m)] <ide> return scripts <ide> <ide> def get_lib_source_files(lib): <ide> filenames = [] <ide> sources = lib[1].get('sources',[]) <del> sources = list(filter(is_string, sources)) <add> sources = [_m for _m in sources if is_string(_m)] <ide> filenames.extend(sources) <ide> filenames.extend(get_dependencies(sources)) <ide> depends = lib[1].get('depends',[]) <ide> def _wildcard_get_subpackage(self, subpackage_name, <ide> caller_level = 1): <ide> l = subpackage_name.split('.') <ide> subpackage_path = njoin([self.local_path]+l) <del> dirs = list(filter(os.path.isdir,glob.glob(subpackage_path))) <add> dirs = [_m for _m in glob.glob(subpackage_path) if os.path.isdir(_m)] <ide> config_list = [] <ide> for d in dirs: <ide> if not os.path.isfile(njoin(d,'__init__.py')): <ide><path>numpy/distutils/system_info.py <ide> def libpaths(paths, bits): <ide> default_include_dirs.append(os.path.join(sys.prefix, 'include')) <ide> default_src_dirs.append(os.path.join(sys.prefix, 'src')) <ide> <del>default_lib_dirs = list(filter(os.path.isdir, default_lib_dirs)) <del>default_include_dirs = list(filter(os.path.isdir, default_include_dirs)) <del>default_src_dirs = list(filter(os.path.isdir, default_src_dirs)) <add>default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] <add>default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] <add>default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] <ide> <ide> so_ext = get_shared_lib_extension() <ide> <ide><path>numpy/f2py/f2py2e.py <ide> def run_compile(): <ide> remove_build_dir = 1 <ide> build_dir = os.path.join(tempfile.mktemp()) <ide> <del> sysinfo_flags = list(filter(re.compile(r'[-][-]link[-]').match,sys.argv[1:])) <del> sys.argv = list(filter(lambda a,flags=sysinfo_flags:a not in flags,sys.argv)) <add> sysinfo_flags = [_m for _m in sys.argv[1] if re.compile(r'[-][-]link[-]').match(_m)] <add> sys.argv = [_m for _m in sys.argv if not _m in sysinfo_flags] <ide> if sysinfo_flags: <ide> sysinfo_flags = [f[7:] for f in sysinfo_flags] <ide> <del> f2py_flags = list(filter(re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include').match,sys.argv[1:])) <del> sys.argv = list(filter(lambda a,flags=f2py_flags:a not in flags,sys.argv)) <add> f2py_flags = [_m for _m in sys.argv[1:] if <add> re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include').match(_m)] <add> sys.argv = [_m for _m in sys.argv if not _m in f2py_flags] <ide> f2py_flags2 = [] <ide> fl = 0 <ide> for a in sys.argv[1:]: <ide> def run_compile(): <ide> f2py_flags2.append(':') <ide> f2py_flags.extend(f2py_flags2) <ide> <del> sys.argv = list(filter(lambda a,flags=f2py_flags2:a not in flags,sys.argv)) <del> <del> flib_flags = list(filter(re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)').match,sys.argv[1:])) <del> sys.argv = list(filter(lambda a,flags=flib_flags:a not in flags,sys.argv)) <del> fc_flags = list(filter(re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))').match,sys.argv[1:])) <del> sys.argv = list(filter(lambda a,flags=fc_flags:a not in flags,sys.argv)) <add> sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] <add> flib_flags = [_m for _m in sys.argv[1:] if <add> re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)').match(_m)] <add> sys.argv = [_m for _m in sys.argv if not _m in flib_flags] <add> fc_flags = [_m for _m in sys.argv[1:] if <add> re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))').match(_m)] <add> sys.argv = [_m for _m in sys.argv if not _m in fc_flags] <ide> <ide> if 1: <ide> del_list = [] <ide> def run_compile(): <ide> i = flib_flags.index(s) <ide> del flib_flags[i] <ide> assert len(flib_flags)<=2,`flib_flags` <del> setup_flags = list(filter(re.compile(r'[-][-](verbose)').match,sys.argv[1:])) <del> sys.argv = list(filter(lambda a,flags=setup_flags:a not in flags,sys.argv)) <add> <add> setup_flags = [_m for _m in sys.argv[1:] if <add> re.compile(r'[-][-](verbose)').match(_m)] <add> sys.argv = [_m for _m in sys.argv if not _m in setup_flags] <add> <ide> if '--quiet' in f2py_flags: <ide> setup_flags.append('--quiet') <ide> <ide><path>numpy/testing/utils.py <ide> def decorate_methods(cls, decorator, testmatch=None): <ide> # delayed import to reduce startup time <ide> from inspect import isfunction <ide> <del> methods = list(filter(isfunction, cls_attr.values())) <add> methods = [_m for _m in cls_attr.values() if isfunction(_m)] <ide> for function in methods: <ide> try: <ide> if hasattr(function, 'compat_func_name'):
5
PHP
PHP
clarify description of method
d11cf5f86d90f40c5cb1837cb3820148005517a0
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function getCountForPagination($columns = ['*']) <ide> } <ide> <ide> /** <del> * Backup some fields for the pagination count. <add> * Backup then remove some fields for the pagination count. <ide> * <ide> * @return void <ide> */
1
Javascript
Javascript
remove unused flag
ed00d2c3d8e39c214bb749dc8a520a4a695c19fd
<ide><path>packages/shared/ReactFeatureFlags.js <ide> export const enableUseRefAccessWarning = false; <ide> <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <del> <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> <ide> export const enableLazyContextPropagation = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide> export const warnAboutCallbackRefReturningFunction = false; <ide> <del>export const enableRecursiveCommitTraversal = false; <ide> export const disableSchedulerTimeoutInWorkLoop = false; <ide> export const enableLazyContextPropagation = false; <ide> export const enableSyncDefaultUpdates = true; <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> // to the correct value. <ide> export const enableNewReconciler = __VARIANT__; <ide> <del>export const enableRecursiveCommitTraversal = false; <del> <ide> export const allowConcurrentByDefault = true; <ide> <ide> export const deletedTreeCleanUpLevel = 3;
9
Ruby
Ruby
add test case to test enum in has_many
eed8b23318c03feb403498fcdea40edeee0532dc
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> require "models/image" <ide> require "models/post" <ide> require "models/author" <add>require "models/book" <ide> require "models/essay" <ide> require "models/comment" <ide> require "models/person" <ide> def test_association_protect_foreign_key <ide> assert_equal invoice.id, line_item.invoice_id <ide> end <ide> <add> class SpecialAuthor < ActiveRecord::Base <add> self.table_name = "authors" <add> has_many :books, class_name: "SpecialBook", foreign_key: :author_id <add> end <add> <add> class SpecialBook < ActiveRecord::Base <add> self.table_name = "books" <add> <add> belongs_to :author <add> enum read_status: { unread: 0, reading: 2, read: 3, forgotten: nil } <add> end <add> <add> def test_association_enum_works_properly <add> author = SpecialAuthor.create!(name: "Test") <add> book = SpecialBook.create!(read_status: "reading") <add> author.books << book <add> <add> assert_equal "reading", book.read_status <add> assert_not_equal 0, SpecialAuthor.joins(:books).where(books: { read_status: "reading" }).count <add> end <add> <ide> # When creating objects on the association, we must not do it within a scope (even though it <ide> # would be convenient), because this would cause that scope to be applied to any callbacks etc. <ide> def test_build_and_create_should_not_happen_within_scope
1
Javascript
Javascript
improve the ng-view docs
7f6c1093f5691bee2fbddca63879d1660620bf2e
<ide><path>src/widgets.js <ide> var ngNonBindableDirective = ngDirective({ terminal: true }); <ide> * Every time the current route changes, the included view changes with it according to the <ide> * configuration of the `$route` service. <ide> * <del> * <add> * @scope <ide> * @example <ide> <doc:example module="ngView"> <ide> <doc:source> <ide> var ngNonBindableDirective = ngDirective({ terminal: true }); <ide> <ide> <script> <ide> angular.module('ngView', [], function($routeProvider, $locationProvider) { <del> $routeProvider.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl}); <del> $routeProvider.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl}); <add> $routeProvider.when('/Book/:bookId', { <add> template: 'examples/book.html', <add> controller: BookCntl <add> }); <add> $routeProvider.when('/Book/:bookId/ch/:chapterId', { <add> template: 'examples/chapter.html', <add> controller: ChapterCntl <add> }); <ide> <ide> // configure html5 to get links working on jsfiddle <ide> $locationProvider.html5Mode(true);
1
Python
Python
remove checks for presence of decimal module
4d686a1e44462c34b60de9049dd499aed60de643
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_broadcast2(self): <ide> A = np.choose(self.ind, (self.x, self.y2)) <ide> assert_equal(A, [[2, 2, 3], [2, 2, 3]]) <ide> <del>def can_use_decimal(): <del> try: <del> from decimal import Decimal <del> return True <del> except ImportError: <del> return False <ide> <ide> # TODO: test for multidimensional <ide> NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} <ide> def _test_simple2d(self, dt): <ide> def test_simple2d(self): <ide> self._test_simple2d(np.float) <ide> <del> @dec.skipif(not can_use_decimal(), <del> "Skip neighborhood iterator tests for decimal objects " \ <del> "(decimal module not available") <ide> def test_simple2d_object(self): <del> from decimal import Decimal <ide> self._test_simple2d(Decimal) <ide> <ide> def _test_mirror2d(self, dt): <ide> def _test_mirror2d(self, dt): <ide> def test_mirror2d(self): <ide> self._test_mirror2d(np.float) <ide> <del> @dec.skipif(not can_use_decimal(), <del> "Skip neighborhood iterator tests for decimal objects " \ <del> "(decimal module not available") <ide> def test_mirror2d_object(self): <del> from decimal import Decimal <ide> self._test_mirror2d(Decimal) <ide> <ide> # Simple, 1d tests <ide> def _test_simple(self, dt): <ide> def test_simple_float(self): <ide> self._test_simple(np.float) <ide> <del> @dec.skipif(not can_use_decimal(), <del> "Skip neighborhood iterator tests for decimal objects " \ <del> "(decimal module not available") <ide> def test_simple_object(self): <del> from decimal import Decimal <ide> self._test_simple(Decimal) <ide> <ide> # Test mirror modes <ide> def _test_mirror(self, dt): <ide> def test_mirror(self): <ide> self._test_mirror(np.float) <ide> <del> @dec.skipif(not can_use_decimal(), <del> "Skip neighborhood iterator tests for decimal objects " \ <del> "(decimal module not available") <ide> def test_mirror_object(self): <del> from decimal import Decimal <ide> self._test_mirror(Decimal) <ide> <ide> # Circular mode <ide> def _test_circular(self, dt): <ide> def test_circular(self): <ide> self._test_circular(np.float) <ide> <del> @dec.skipif(not can_use_decimal(), <del> "Skip neighborhood iterator tests for decimal objects " \ <del> "(decimal module not available") <ide> def test_circular_object(self): <del> from decimal import Decimal <ide> self._test_circular(Decimal) <ide> <ide> # Test stacking neighborhood iterators
1
Text
Text
fix typo in repl docs
287f21e31dafce2cf10fc7e349dbd26ebb392a08
<ide><path>doc/api/repl.md <ide> within the action function for commands registered using the <ide> added: v9.0.0 <ide> --> <ide> <del>The `replServer.clearBufferedComand()` method clears any command that has been <add>The `replServer.clearBufferedCommand()` method clears any command that has been <ide> buffered but not yet executed. This method is primarily intended to be <ide> called from within the action function for commands registered using the <ide> `replServer.defineCommand()` method.
1
PHP
PHP
fix syntax error
1302781959ae78229c4f402c21fbd6bd327c8121
<ide><path>src/Illuminate/Foundation/EventCache.php <ide> class EventCache { <ide> * <ide> * @var string <ide> */ <del> protected $stub = "$events->listen('{{event}}', '{{handler}}');"; <add> protected $stub = '$events->listen(\'{{event}}\', \'{{handler}}\');'; <ide> <ide> /** <ide> * Create a new event cache instance.
1
Python
Python
update code style for project euler problem 28
05616ca38eec9fba5a21544aa03dba96e6f6efc6
<ide><path>project_euler/problem_28/sol1.py <ide> """ <add>Problem 28 <add>Url: https://projecteuler.net/problem=28 <add>Statement: <ide> Starting with the number 1 and moving to the right in a clockwise direction a 5 <ide> by 5 spiral is formed as follows: <ide> <ide> from math import ceil <ide> <ide> <del>def diagonal_sum(n): <add>def solution(n: int = 1001) -> int: <ide> """Returns the sum of the numbers on the diagonals in a n by n spiral <ide> formed in the same way. <ide> <del> >>> diagonal_sum(1001) <add> >>> solution(1001) <ide> 669171001 <del> >>> diagonal_sum(500) <add> >>> solution(500) <ide> 82959497 <del> >>> diagonal_sum(100) <add> >>> solution(100) <ide> 651897 <del> >>> diagonal_sum(50) <add> >>> solution(50) <ide> 79697 <del> >>> diagonal_sum(10) <add> >>> solution(10) <ide> 537 <ide> """ <ide> total = 1 <ide> def diagonal_sum(n): <ide> import sys <ide> <ide> if len(sys.argv) == 1: <del> print(diagonal_sum(1001)) <add> print(solution()) <ide> else: <ide> try: <ide> n = int(sys.argv[1]) <del> print(diagonal_sum(n)) <add> print(solution(n)) <ide> except ValueError: <ide> print("Invalid entry - please enter a number")
1
Javascript
Javascript
move the rasterization logic into one single class
03506f25c0ca8fc81e36bfe584e9359e566b82db
<ide><path>test/driver.js <ide> const { <ide> GlobalWorkerOptions, <ide> PixelsPerInch, <ide> renderTextLayer, <add> shadow, <ide> XfaLayer, <ide> } = pdfjsLib; <ide> const { SimpleLinkService } = pdfjsViewer; <ide> const RENDER_TASK_ON_CONTINUE_DELAY = 5; // ms <ide> const SVG_NS = "http://www.w3.org/2000/svg"; <ide> <ide> function loadStyles(styles) { <del> styles = Object.values(styles); <del> if (styles.every(style => style.promise)) { <del> return Promise.all(styles.map(style => style.promise)); <del> } <add> const promises = []; <ide> <del> for (const style of styles) { <del> style.promise = new Promise(function (resolve, reject) { <del> const xhr = new XMLHttpRequest(); <del> xhr.open("GET", style.file); <del> xhr.onload = function () { <del> resolve(xhr.responseText); <del> }; <del> xhr.onerror = function (e) { <del> reject(new Error(`Error fetching style (${style.file}): ${e}`)); <del> }; <del> xhr.send(null); <del> }); <add> for (const file of styles) { <add> promises.push( <add> new Promise(function (resolve, reject) { <add> const xhr = new XMLHttpRequest(); <add> xhr.open("GET", file); <add> xhr.onload = function () { <add> resolve(xhr.responseText); <add> }; <add> xhr.onerror = function (e) { <add> reject(new Error(`Error fetching style (${file}): ${e}`)); <add> }; <add> xhr.send(null); <add> }) <add> ); <ide> } <ide> <del> return Promise.all(styles.map(style => style.promise)); <add> return Promise.all(promises); <ide> } <ide> <ide> function writeSVG(svgElement, ctx) { <ide> async function resolveImages(node, silentErrors = false) { <ide> await Promise.all(loadedPromises); <ide> } <ide> <del>/** <del> * @class <del> */ <del>const rasterizeTextLayer = (function rasterizeTextLayerClosure() { <del> const styles = { <del> common: { <del> file: "./text_layer_test.css", <del> promise: null, <del> }, <del> }; <del> <del> // eslint-disable-next-line no-shadow <del> async function rasterizeTextLayer( <del> ctx, <del> viewport, <del> textContent, <del> enhanceTextSelection <del> ) { <del> try { <del> // Building SVG with size of the viewport. <del> const svg = document.createElementNS(SVG_NS, "svg:svg"); <del> svg.setAttribute("width", viewport.width + "px"); <del> svg.setAttribute("height", viewport.height + "px"); <del> // items are transformed to have 1px font size <del> svg.setAttribute("font-size", 1); <del> <del> // Adding element to host our HTML (style + text layer div). <del> const foreignObject = document.createElementNS( <del> SVG_NS, <del> "svg:foreignObject" <del> ); <del> foreignObject.setAttribute("x", "0"); <del> foreignObject.setAttribute("y", "0"); <del> foreignObject.setAttribute("width", viewport.width + "px"); <del> foreignObject.setAttribute("height", viewport.height + "px"); <del> const style = document.createElement("style"); <del> const stylePromise = loadStyles(styles); <del> foreignObject.appendChild(style); <del> const div = document.createElement("div"); <del> div.className = "textLayer"; <del> foreignObject.appendChild(div); <del> <del> const [cssRules] = await stylePromise; <del> style.textContent = cssRules; <del> <del> // Rendering text layer as HTML. <del> const task = renderTextLayer({ <del> textContent, <del> container: div, <del> viewport, <del> enhanceTextSelection, <del> }); <del> await task.promise; <del> <del> task.expandTextDivs(true); <del> svg.appendChild(foreignObject); <del> <del> await writeSVG(svg, ctx); <del> } catch (reason) { <del> throw new Error(`rasterizeTextLayer: "${reason?.message}".`); <del> } <del> } <del> <del> return rasterizeTextLayer; <del>})(); <del> <del>/** <del> * @class <del> */ <del>const rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { <add>class Rasterize { <ide> /** <del> * For the reference tests, the entire annotation layer must be visible. To <del> * achieve this, we load the common styles as used by the viewer and extend <del> * them with a set of overrides to make all elements visible. <add> * For the reference tests, the full content of the various layers must be <add> * visible. To achieve this, we load the common styles as used by the viewer <add> * and extend them with a set of overrides to make all elements visible. <ide> * <ide> * Note that we cannot simply use `@import` to import the common styles in <ide> * the overrides file because the browser does not resolve that when the <ide> * styles are inserted via XHR. Therefore, we load and combine them here. <ide> */ <del> const styles = { <del> common: { <del> file: "../web/annotation_layer_builder.css", <del> promise: null, <del> }, <del> overrides: { <del> file: "./annotation_layer_builder_overrides.css", <del> promise: null, <del> }, <del> }; <del> <del> // eslint-disable-next-line no-shadow <del> async function rasterizeAnnotationLayer( <add> static get annotationStylePromise() { <add> const styles = [ <add> "../web/annotation_layer_builder.css", <add> "./annotation_layer_builder_overrides.css", <add> ]; <add> return shadow(this, "annotationStylePromise", loadStyles(styles)); <add> } <add> <add> static get textStylePromise() { <add> const styles = ["./text_layer_test.css"]; <add> return shadow(this, "textStylePromise", loadStyles(styles)); <add> } <add> <add> static get xfaStylePromise() { <add> const styles = [ <add> "../web/xfa_layer_builder.css", <add> "./xfa_layer_builder_overrides.css", <add> ]; <add> return shadow(this, "xfaStylePromise", loadStyles(styles)); <add> } <add> <add> static async annotationLayer( <ide> ctx, <ide> viewport, <ide> annotations, <ide> const rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { <ide> foreignObject.setAttribute("width", viewport.width + "px"); <ide> foreignObject.setAttribute("height", viewport.height + "px"); <ide> const style = document.createElement("style"); <del> const stylePromise = loadStyles(styles); <ide> foreignObject.appendChild(style); <ide> const div = document.createElement("div"); <ide> div.className = "annotationLayer"; <ide> <ide> // Rendering annotation layer as HTML. <del> const [common, overrides] = await stylePromise; <add> const [common, overrides] = await this.annotationStylePromise; <ide> style.textContent = common + "\n" + overrides; <ide> <ide> const annotation_viewport = viewport.clone({ dontFlip: true }); <ide> const rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { <ide> <ide> await writeSVG(svg, ctx); <ide> } catch (reason) { <del> throw new Error(`rasterizeAnnotationLayer: "${reason?.message}".`); <add> throw new Error(`Rasterize.annotationLayer: "${reason?.message}".`); <ide> } <ide> } <ide> <del> return rasterizeAnnotationLayer; <del>})(); <add> static async textLayer(ctx, viewport, textContent, enhanceTextSelection) { <add> try { <add> // Building SVG with size of the viewport. <add> const svg = document.createElementNS(SVG_NS, "svg:svg"); <add> svg.setAttribute("width", viewport.width + "px"); <add> svg.setAttribute("height", viewport.height + "px"); <add> // items are transformed to have 1px font size <add> svg.setAttribute("font-size", 1); <ide> <del>/** <del> * @class <del> */ <del>const rasterizeXfaLayer = (function rasterizeXfaLayerClosure() { <del> const styles = { <del> common: { <del> file: "../web/xfa_layer_builder.css", <del> promise: null, <del> }, <del> overrides: { <del> file: "./xfa_layer_builder_overrides.css", <del> promise: null, <del> }, <del> }; <del> <del> // eslint-disable-next-line no-shadow <del> async function rasterizeXfaLayer( <add> // Adding element to host our HTML (style + text layer div). <add> const foreignObject = document.createElementNS( <add> SVG_NS, <add> "svg:foreignObject" <add> ); <add> foreignObject.setAttribute("x", "0"); <add> foreignObject.setAttribute("y", "0"); <add> foreignObject.setAttribute("width", viewport.width + "px"); <add> foreignObject.setAttribute("height", viewport.height + "px"); <add> const style = document.createElement("style"); <add> foreignObject.appendChild(style); <add> const div = document.createElement("div"); <add> div.className = "textLayer"; <add> foreignObject.appendChild(div); <add> <add> const [cssRules] = await this.textStylePromise; <add> style.textContent = cssRules; <add> <add> // Rendering text layer as HTML. <add> const task = renderTextLayer({ <add> textContent, <add> container: div, <add> viewport, <add> enhanceTextSelection, <add> }); <add> await task.promise; <add> <add> task.expandTextDivs(true); <add> svg.appendChild(foreignObject); <add> <add> await writeSVG(svg, ctx); <add> } catch (reason) { <add> throw new Error(`Rasterize.textLayer: "${reason?.message}".`); <add> } <add> } <add> <add> static async xfaLayer( <ide> ctx, <ide> viewport, <ide> xfa, <ide> const rasterizeXfaLayer = (function rasterizeXfaLayerClosure() { <ide> foreignObject.setAttribute("width", viewport.width + "px"); <ide> foreignObject.setAttribute("height", viewport.height + "px"); <ide> const style = document.createElement("style"); <del> const stylePromise = loadStyles(styles); <ide> foreignObject.appendChild(style); <ide> const div = document.createElement("div"); <ide> foreignObject.appendChild(div); <ide> <del> const [common, overrides] = await stylePromise; <add> const [common, overrides] = await this.xfaStylePromise; <ide> style.textContent = fontRules + "\n" + common + "\n" + overrides; <ide> <ide> XfaLayer.render({ <ide> const rasterizeXfaLayer = (function rasterizeXfaLayerClosure() { <ide> <ide> await writeSVG(svg, ctx); <ide> } catch (reason) { <del> throw new Error(`rasterizeXfaLayer: "${reason?.message}".`); <add> throw new Error(`Rasterize.xfaLayer: "${reason?.message}".`); <ide> } <ide> } <del> <del> return rasterizeXfaLayer; <del>})(); <add>} <ide> <ide> /** <ide> * @typedef {Object} DriverOptions <ide> class Driver { <ide> includeMarkedContent: true, <ide> }) <ide> .then(function (textContent) { <del> return rasterizeTextLayer( <add> return Rasterize.textLayer( <ide> textLayerContext, <ide> viewport, <ide> textContent, <ide> class Driver { <ide> annotationCanvasMap = new Map(); <ide> } else { <ide> initPromise = page.getXfa().then(function (xfa) { <del> return rasterizeXfaLayer( <add> return Rasterize.xfaLayer( <ide> annotationLayerContext, <ide> viewport, <ide> xfa, <ide> class Driver { <ide> } <ide> return renderTask.promise.then(function () { <ide> if (annotationCanvasMap) { <del> rasterizeAnnotationLayer( <add> Rasterize.annotationLayer( <ide> annotationLayerContext, <ide> viewport, <ide> data,
1
Javascript
Javascript
improve unit test coverage for primitives
550a38f1bafd78d0caaa8d67c4b8b404c9b02e26
<ide><path>test/unit/primitives_spec.js <ide> import { <ide> Cmd, <ide> Dict, <add> EOF, <ide> isCmd, <ide> isDict, <add> isEOF, <ide> isName, <ide> isRef, <ide> isRefsEqual, <add> isStream, <ide> Name, <ide> Ref, <ide> RefSet, <ide> } from "../../src/core/primitives.js"; <add>import { StringStream } from "../../src/core/stream.js"; <ide> import { XRefMock } from "./test_utils.js"; <ide> <ide> describe("primitives", function () { <ide> describe("primitives", function () { <ide> emptyDict = dictWithSizeKey = dictWithManyKeys = null; <ide> }); <ide> <add> it("should allow assigning an XRef table after creation", function () { <add> const dict = new Dict(null); <add> expect(dict.xref).toEqual(null); <add> <add> const xref = new XRefMock([]); <add> dict.assignXref(xref); <add> expect(dict.xref).toEqual(xref); <add> }); <add> <ide> it("should return invalid values for unknown keys", function () { <ide> checkInvalidHasValues(emptyDict); <ide> checkInvalidKeyValues(emptyDict); <ide> describe("primitives", function () { <ide> }); <ide> <ide> describe("Ref", function () { <add> it("should get a string representation", function () { <add> const nonZeroRef = Ref.get(4, 2); <add> expect(nonZeroRef.toString()).toEqual("4R2"); <add> <add> // If the generation number is 0, a shorter representation is used. <add> const zeroRef = Ref.get(4, 0); <add> expect(zeroRef.toString()).toEqual("4R"); <add> }); <add> <ide> it("should retain the stored values", function () { <ide> const storedNum = 4; <ide> const storedGen = 2; <ide> const ref = Ref.get(storedNum, storedGen); <ide> expect(ref.num).toEqual(storedNum); <ide> expect(ref.gen).toEqual(storedGen); <ide> }); <add> <add> it("should create only one object for a reference and cache it", function () { <add> const firstRef = Ref.get(4, 2); <add> const secondRef = Ref.get(4, 2); <add> const firstOtherRef = Ref.get(5, 2); <add> const secondOtherRef = Ref.get(5, 2); <add> <add> expect(firstRef).toBe(secondRef); <add> expect(firstOtherRef).toBe(secondOtherRef); <add> expect(firstRef).not.toBe(firstOtherRef); <add> }); <ide> }); <ide> <ide> describe("RefSet", function () { <ide> describe("primitives", function () { <ide> }); <ide> }); <ide> <add> describe("isEOF", function () { <add> it("handles non-EOF", function () { <add> const nonEOF = "foo"; <add> expect(isEOF(nonEOF)).toEqual(false); <add> }); <add> <add> it("handles EOF", function () { <add> expect(isEOF(EOF)).toEqual(true); <add> }); <add> }); <add> <ide> describe("isName", function () { <ide> it("handles non-names", function () { <ide> const nonName = {}; <ide> describe("primitives", function () { <ide> expect(isRefsEqual(ref1, ref2)).toEqual(false); <ide> }); <ide> }); <add> <add> describe("isStream", function () { <add> it("handles non-streams", function () { <add> const nonStream = {}; <add> expect(isStream(nonStream)).toEqual(false); <add> }); <add> <add> it("handles streams", function () { <add> const stream = new StringStream("foo"); <add> expect(isStream(stream)).toEqual(true); <add> }); <add> }); <ide> });
1
Javascript
Javascript
outgoingmessage change writable after end
649d77bbf4e01e3dd3799ff8ca8d190641c9f4da
<ide><path>lib/_http_outgoing.js <ide> OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { <ide> this.connection.uncork(); <ide> <ide> this.finished = true; <add> this.writable = false; <ide> <ide> // There is the first message on the outgoing queue, and we've sent <ide> // everything to the socket. <ide><path>test/parallel/test-http-outgoing-finish-writable.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>// Verify that after calling end() on an `OutgoingMessage` (or a type that <add>// inherits from `OutgoingMessage`), its `writable` property is set to false. <add> <add>const server = http.createServer(common.mustCall(function(req, res) { <add> assert.strictEqual(res.writable, true); <add> assert.strictEqual(res.finished, false); <add> res.end(); <add> assert.strictEqual(res.writable, false); <add> assert.strictEqual(res.finished, true); <add> <add> server.close(); <add>})); <add> <add>server.listen(0); <add> <add>server.on('listening', common.mustCall(function() { <add> const clientRequest = http.request({ <add> port: server.address().port, <add> method: 'GET', <add> path: '/' <add> }); <add> <add> assert.strictEqual(clientRequest.writable, true); <add> clientRequest.end(); <add> assert.strictEqual(clientRequest.writable, false); <add>})); <ide><path>test/parallel/test-pipe-outgoing-message-data-emitted-after-ended.js <add>'use strict'; <add>const common = require('../common'); <add>const http = require('http'); <add>const util = require('util'); <add>const stream = require('stream'); <add> <add>// Verify that when piping a stream to an `OutgoingMessage` (or a type that <add>// inherits from `OutgoingMessage`), if data is emitted after the <add>// `OutgoingMessage` was closed - no `write after end` error is raised (this <add>// should be the case when piping - when writing data directly to the <add>// `OutgoingMessage` this error should be raised). <add> <add>function MyStream() { <add> stream.call(this); <add>} <add>util.inherits(MyStream, stream); <add> <add>const server = http.createServer(common.mustCall(function(req, res) { <add> const myStream = new MyStream(); <add> myStream.pipe(res); <add> <add> process.nextTick(common.mustCall(() => { <add> res.end(); <add> myStream.emit('data', 'some data'); <add> <add> // If we got here - 'write after end' wasn't raised and the test passed. <add> process.nextTick(common.mustCall(() => server.close())); <add> })); <add>})); <add> <add>server.listen(0); <add> <add>server.on('listening', common.mustCall(function() { <add> http.request({ <add> port: server.address().port, <add> method: 'GET', <add> path: '/' <add> }).end(); <add>}));
3
PHP
PHP
fix doc block
66dc497a5e9511b1de6539c4bbf9c1e83fe572f7
<ide><path>src/Http/Client/Adapter/Curl.php <ide> public function buildOptions(Request $request, array $options) <ide> * <ide> * @param resource $handle Curl handle <ide> * @param string $responseData string The response data from curl_exec <del> * @return \Cake\Http\Client\Response[] <add> * @return \Cake\Http\Client\Response <ide> */ <ide> protected function createResponse($handle, $responseData) <ide> {
1
Python
Python
fix double paste
982a5504d5879b3cfdb051f452f4573e35623fc3
<ide><path>research/audioset/mel_features.py <ide> def spectrogram_to_mel_matrix(num_mel_bins=20, <ide> ValueError: if frequency edges are incorrectly ordered. <ide> """ <ide> nyquist_hertz = audio_sample_rate / 2. <del> if upper_edge_hertz > nyquist_hertz: <del> raise ValueError("upper_edge_hertz %.1f is greater than Nyquist %.1f" % <del> (upper_edge_hertz, nyquist_hertz)) <add> if lower_edge_hertz < 0.0: <add> raise ValueError("lower_edge_hertz %.1f must be >= 0" % lower_edge_hertz) <ide> if lower_edge_hertz >= upper_edge_hertz: <ide> raise ValueError("lower_edge_hertz %.1f >= upper_edge_hertz %.1f" % <ide> (lower_edge_hertz, upper_edge_hertz))
1
Javascript
Javascript
improve swipeablelistview performance
c779e233b693233d614be4b24bd896cb10f1833c
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableListView.js <ide> const SwipeableListView = React.createClass({ <ide> _listViewRef: (null: ?string), <ide> <ide> propTypes: { <del> dataSource: PropTypes.object.isRequired, // SwipeableListViewDataSource <add> dataSource: PropTypes.instanceOf(SwipeableListViewDataSource).isRequired, <ide> maxSwipeDistance: PropTypes.number, <ide> // Callback method to render the swipeable view <ide> renderRow: PropTypes.func.isRequired, <ide> const SwipeableListView = React.createClass({ <ide> <ide> getInitialState(): Object { <ide> return { <del> dataSource: this.props.dataSource.getDataSource(), <add> dataSource: this.props.dataSource, <ide> }; <ide> }, <ide> <ide> componentWillReceiveProps(nextProps: Object): void { <del> if ('dataSource' in nextProps && this.state.dataSource !== nextProps.dataSource) { <add> if ( <add> this.state.dataSource.getDataSource() !== nextProps.dataSource.getDataSource() <add> ) { <ide> this.setState({ <del> dataSource: nextProps.dataSource.getDataSource(), <add> dataSource: nextProps.dataSource, <ide> }); <ide> } <ide> }, <ide> const SwipeableListView = React.createClass({ <ide> ref={(ref) => { <ide> this._listViewRef = ref; <ide> }} <del> dataSource={this.state.dataSource} <add> dataSource={this.state.dataSource.getDataSource()} <ide> renderRow={this._renderRow} <add> scrollEnabled={this.state.scrollEnabled} <ide> /> <ide> ); <ide> }, <ide> <add> /** <add> * This is a work-around to lock vertical `ListView` scrolling on iOS and <add> * mimic Android behaviour. Locking vertical scrolling when horizontal <add> * scrolling is active allows us to significantly improve framerates <add> * (from high 20s to almost consistently 60 fps) <add> */ <add> _setListViewScrollable(value: boolean): void { <add> if (this._listViewRef && this._listViewRef.setNativeProps) { <add> this._listViewRef.setNativeProps({ <add> scrollEnabled: value, <add> }); <add> } <add> }, <add> <ide> // Passing through ListView's getScrollResponder() function <ide> getScrollResponder(): ?Object { <ide> if (this._listViewRef && this._listViewRef.getScrollResponder) { <ide> const SwipeableListView = React.createClass({ <ide> isOpen={rowData.id === this.props.dataSource.getOpenRowID()} <ide> maxSwipeDistance={this.props.maxSwipeDistance} <ide> key={rowID} <del> onOpen={() => this._onOpen(rowData.id)}> <add> onOpen={() => this._onOpen(rowData.id)} <add> onSwipeEnd={() => this._setListViewScrollable(true)} <add> onSwipeStart={() => this._setListViewScrollable(false)}> <ide> {this.props.renderRow(rowData, sectionID, rowID)} <ide> </SwipeableRow> <ide> ); <ide> }, <ide> <ide> _onOpen(rowID: string): void { <ide> this.setState({ <del> dataSource: this.props.dataSource.setOpenRowID(rowID), <add> dataSource: this.state.dataSource.setOpenRowID(rowID), <ide> }); <ide> }, <ide> }); <ide><path>Libraries/Experimental/SwipeableRow/SwipeableListViewDataSource.js <ide> class SwipeableListViewDataSource { <ide> return this._openRowID; <ide> } <ide> <del> setOpenRowID(rowID: string): ListViewDataSource { <add> setOpenRowID(rowID: string): SwipeableListViewDataSource { <ide> this._previousOpenRowID = this._openRowID; <ide> this._openRowID = rowID; <ide> <del> return this._dataSource.cloneWithRowsAndSections( <add> this._dataSource = this._dataSource.cloneWithRowsAndSections( <ide> this._dataBlob, <ide> this.sectionIdentities, <ide> this.rowIdentities <ide> ); <add> <add> return this; <ide> } <ide> } <ide> <ide><path>Libraries/Experimental/SwipeableRow/SwipeableRow.js <ide> const View = require('View'); <ide> <ide> const {PropTypes} = React; <ide> <add>const emptyFunction = require('emptyFunction'); <add> <ide> // Position of the left of the swipable item when closed <ide> const CLOSED_LEFT_POSITION = 0; <ide> // Minimum swipe distance before we recognize it as such <ide> const HORIZONTAL_SWIPE_DISTANCE_THRESHOLD = 15; <ide> * on the item hidden behind the row <ide> */ <ide> const SwipeableRow = React.createClass({ <del> /** <del> * In order to render component A beneath component B, A must be rendered <del> * before B. However, this will cause "flickering", aka we see A briefly then <del> * B. To counter this, _isSwipeableViewRendered flag is used to set component <del> * A to be transparent until component B is loaded. <del> */ <del> _isSwipeableViewRendered: false, <ide> _panResponder: {}, <ide> _previousLeft: CLOSED_LEFT_POSITION, <ide> <ide> const SwipeableRow = React.createClass({ <ide> */ <ide> maxSwipeDistance: PropTypes.number, <ide> onOpen: PropTypes.func, <add> onSwipeEnd: PropTypes.func.isRequired, <add> onSwipeStart: PropTypes.func.isRequired, <ide> /** <ide> * A ReactElement that is unveiled when the user swipes <ide> */ <ide> const SwipeableRow = React.createClass({ <ide> getInitialState(): Object { <ide> return { <ide> currentLeft: new Animated.Value(this._previousLeft), <add> /** <add> * In order to render component A beneath component B, A must be rendered <add> * before B. However, this will cause "flickering", aka we see A briefly <add> * then B. To counter this, _isSwipeableViewRendered flag is used to set <add> * component A to be transparent until component B is loaded. <add> */ <add> isSwipeableViewRendered: false, <ide> /** <ide> * scrollViewWidth can change based on orientation, thus it's stored as a <ide> * state variable. This means all styles depending on it will be inline <ide> const SwipeableRow = React.createClass({ <ide> getDefaultProps(): Object { <ide> return { <ide> isOpen: false, <del> swipeThreshold: 50, <add> onSwipeEnd: emptyFunction, <add> onSwipeStart: emptyFunction, <add> swipeThreshold: 30, <ide> }; <ide> }, <ide> <ide> componentWillMount(): void { <ide> this._panResponder = PanResponder.create({ <del> onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder, <del> onStartShouldSetPanResponderCapture: this._handleStartShouldSetPanResponderCapture, <del> onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, <add> onStartShouldSetPanResponder: (event, gestureState) => true, <add> // Don't capture child's start events <add> onStartShouldSetPanResponderCapture: (event, gestureState) => false, <add> onMoveShouldSetPanResponder: (event, gestureState) => false, <ide> onMoveShouldSetPanResponderCapture: this._handleMoveShouldSetPanResponderCapture, <del> onPanResponderGrant: (event, gesture) => {}, <add> onPanResponderGrant: this._handlePanResponderGrant, <ide> onPanResponderMove: this._handlePanResponderMove, <ide> onPanResponderRelease: this._handlePanResponderEnd, <del> onPanResponderTerminationRequest: this._handlePanResponderTerminationRequest, <add> onPanResponderTerminationRequest: this._onPanResponderTerminationRequest, <ide> onPanResponderTerminate: this._handlePanResponderEnd, <ide> }); <ide> }, <ide> const SwipeableRow = React.createClass({ <ide> * handled internally by this component. <ide> */ <ide> if (this.props.isOpen && !nextProps.isOpen) { <del> this._animateClose(); <add> this._animateToClosedPosition(); <ide> } <ide> }, <ide> <ide> const SwipeableRow = React.createClass({ <ide> }, <ide> ]; <ide> if (Platform.OS === 'ios') { <del> slideoutStyle.push({opacity: this._isSwipeableViewRendered ? 1 : 0}); <add> slideoutStyle.push({opacity: this.state.isSwipeableViewRendered ? 1 : 0}); <ide> } <ide> <ide> // The view hidden behind the main view <ide> const SwipeableRow = React.createClass({ <ide> <Animated.View <ide> onLayout={this._onSwipeableViewLayout} <ide> style={{ <del> left: this.state.currentLeft, <add> transform: [{translateX: this.state.currentLeft}], <ide> width: this.state.scrollViewWidth, <ide> }}> <ide> {this.props.children} <ide> const SwipeableRow = React.createClass({ <ide> }, <ide> <ide> _onSwipeableViewLayout(event: Object): void { <del> if (!this._isSwipeableViewRendered) { <del> this._isSwipeableViewRendered = true; <add> if (!this._isSwipeableViewRendered && this.state.scrollViewWidth !== 0) { <add> this.setState({ <add> isSwipeableViewRendered: true, <add> }); <ide> } <ide> }, <ide> <del> _handlePanResponderTerminationRequest( <del> event: Object, <del> gestureState: Object, <del> ): boolean { <del> return false; <del> }, <del> <del> _handleStartShouldSetPanResponder( <del> event: Object, <del> gestureState: Object, <del> ): boolean { <del> return false; <del> }, <del> <del> _handleStartShouldSetPanResponderCapture( <del> event: Object, <del> gestureState: Object, <del> ): boolean { <del> return false; <del> }, <del> <del> _handleMoveShouldSetPanResponder( <del> event: Object, <del> gestureState: Object, <del> ): boolean { <del> return false; <del> }, <del> <ide> _handleMoveShouldSetPanResponderCapture( <ide> event: Object, <ide> gestureState: Object, <ide> ): boolean { <del> return this._isValidSwipe(gestureState); <del> }, <del> <del> /** <del> * User might move their finger slightly when tapping; let's ignore that <del> * unless we are sure they are swiping. <del> */ <del> _isValidSwipe(gestureState: Object): boolean { <del> return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD; <del> }, <del> <del> _shouldAllowSwipe(gestureState: Object): boolean { <del> return ( <del> this._isSwipeWithinOpenLimit(this._previousLeft + gestureState.dx) && <del> ( <del> this._isSwipingLeftFromClosed(gestureState) || <del> this._isSwipingFromSemiOpened(gestureState) <del> ) <del> ); <add> // Decides whether a swipe is responded to by this component or its child <add> return gestureState.dy < 10 && this._isValidSwipe(gestureState); <ide> }, <ide> <del> _isSwipingLeftFromClosed(gestureState: Object): boolean { <del> return this._previousLeft === CLOSED_LEFT_POSITION && gestureState.vx < 0; <del> }, <add> _handlePanResponderGrant(event: Object, gestureState: Object): void { <ide> <del> // User is swiping left/right from a state between fully open and fully closed <del> _isSwipingFromSemiOpened(gestureState: Object): boolean { <del> return ( <del> this._isSwipeableSomewhatOpen() && <del> this._isBoundedSwipe(gestureState) <del> ); <del> }, <del> <del> _isSwipeableSomewhatOpen(): boolean { <del> return this._previousLeft < CLOSED_LEFT_POSITION; <del> }, <del> <del> _isBoundedSwipe(gestureState: Object): boolean { <del> return ( <del> this._isBoundedLeftSwipe(gestureState) || <del> this._isBoundedRightSwipe(gestureState) <del> ); <del> }, <del> <del> _isBoundedLeftSwipe(gestureState: Object): boolean { <del> return ( <del> gestureState.dx < 0 && -this._previousLeft < this.state.scrollViewWidth <del> ); <del> }, <del> <del> _isBoundedRightSwipe(gestureState: Object): boolean { <del> const horizontalDistance = gestureState.dx; <del> <del> return ( <del> horizontalDistance > 0 && <del> this._previousLeft + horizontalDistance <= CLOSED_LEFT_POSITION <del> ); <del> }, <del> <del> _isSwipeWithinOpenLimit(distance: number): boolean { <del> const maxSwipeDistance = this.props.maxSwipeDistance; <del> <del> return maxSwipeDistance <del> ? Math.abs(distance) <= maxSwipeDistance <del> : true; <ide> }, <ide> <ide> _handlePanResponderMove(event: Object, gestureState: Object): void { <del> if (this._shouldAllowSwipe(gestureState)) { <del> this.setState({ <del> currentLeft: new Animated.Value(this._previousLeft + gestureState.dx), <del> }); <del> } <add> this.props.onSwipeStart(); <add> this.state.currentLeft.setValue(this._previousLeft + gestureState.dx); <ide> }, <ide> <del> // Animation for after a user lifts their finger after swiping <del> _postReleaseAnimate(horizontalDistance: number): void { <del> if (horizontalDistance < 0) { <del> if (horizontalDistance < -this.props.swipeThreshold) { <del> // Swiped left far enough, animate to fully opened state <del> this._animateOpen(); <del> return; <del> } <del> // Did not swipe left enough, animate to closed <del> this._animateClose(); <del> } else if (horizontalDistance > 0) { <del> if (horizontalDistance > this.props.swipeThreshold) { <del> // Swiped right far enough, animate to closed state <del> this._animateClose(); <del> return; <del> } <del> // Did not swipe right enough, animate to opened <del> this._animateOpen(); <del> } <add> _onPanResponderTerminationRequest(event: Object, gestureState: Object): boolean { <add> return false; <ide> }, <ide> <ide> _animateTo(toValue: number): void { <del> Animated.timing(this.state.currentLeft, {toValue: toValue}).start(() => { <add> Animated.timing( <add> this.state.currentLeft, <add> { <add> toValue: toValue, <add> }, <add> ).start(() => { <ide> this._previousLeft = toValue; <ide> }); <ide> }, <ide> <del> _animateOpen(): void { <del> this.props.onOpen && this.props.onOpen(); <del> <add> _animateToOpenPosition(): void { <ide> const toValue = this.props.maxSwipeDistance <ide> ? -this.props.maxSwipeDistance <ide> : -this.state.scrollViewWidth; <ide> this._animateTo(toValue); <ide> }, <ide> <del> _animateClose(): void { <add> _animateToClosedPosition(): void { <ide> this._animateTo(CLOSED_LEFT_POSITION); <ide> }, <ide> <add> // Ignore swipes due to user's finger moving slightly when tapping <add> _isValidSwipe(gestureState: Object): boolean { <add> return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD; <add> }, <add> <ide> _handlePanResponderEnd(event: Object, gestureState: Object): void { <ide> const horizontalDistance = gestureState.dx; <del> this._postReleaseAnimate(horizontalDistance); <del> <del> if (this._shouldAllowSwipe(gestureState)) { <del> this._previousLeft += horizontalDistance; <del> return; <del> } <ide> <del> if (this._previousLeft + horizontalDistance >= 0) { <del> // We are swiping back to close or somehow swiped past close <del> this._previousLeft = 0; <del> } else if ( <del> this.props.maxSwipeDistance && <del> !this._isSwipeWithinOpenLimit(this._previousLeft + horizontalDistance) <del> ) { <del> // We are swiping past the max swipe distance? <del> this._previousLeft = -this.props.maxSwipeDistance; <add> if (Math.abs(horizontalDistance) > this.props.swipeThreshold) { <add> if (horizontalDistance < 0) { <add> // Swiped left <add> this.props.onOpen && this.props.onOpen(); <add> this._animateToOpenPosition(); <add> } else { <add> // Swiped right <add> this._animateToClosedPosition(); <add> } <add> } else { <add> if (this._previousLeft === CLOSED_LEFT_POSITION) { <add> this._animateToClosedPosition(); <add> } else { <add> this._animateToOpenPosition(); <add> } <ide> } <ide> <del> this.setState({ <del> currentLeft: new Animated.Value(this._previousLeft), <del> }); <add> this.props.onSwipeEnd(); <ide> }, <ide> <ide> _onLayoutChange(event: Object): void {
3
PHP
PHP
use collection count() function
107fb475f35f0691fe08facb697eda47f6cc7f3b
<ide><path>src/Illuminate/Pagination/Paginator.php <ide> protected function setItems($items) <ide> { <ide> $this->items = $items instanceof Collection ? $items : Collection::make($items); <ide> <del> $this->hasMore = count($this->items) > ($this->perPage); <add> $this->hasMore = $this->items->count() > $this->perPage; <ide> <ide> $this->items = $this->items->slice(0, $this->perPage); <ide> }
1
Javascript
Javascript
move require.resolve into the module scope
e9e8e8b423c9c59f1a54db35d282ff20c825a949
<ide><path>packages/next/build/swc/options.js <ide> const nextDistPath = <ide> /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/ <ide> <add>const regeneratorRuntimePath = require.resolve('regenerator-runtime') <add> <ide> function getBaseSWCOptions({ <ide> filename, <ide> development, <ide> function getBaseSWCOptions({ <ide> }, <ide> }, <ide> regenerator: { <del> importPath: require.resolve('regenerator-runtime'), <add> importPath: regeneratorRuntimePath, <ide> }, <ide> }, <ide> },
1
Javascript
Javascript
fix reinjection check
1f703e120403d41d4f274ad9d30a9512788e5edc
<ide><path>lib/internal/http2/core.js <ide> function connect(authority, options, listener) { <ide> debug('Http2Session connect', options.createConnection); <ide> // Socket already has some buffered data - emulate receiving it <ide> // https://github.com/nodejs/node/issues/35475 <del> if (typeof options.createConnection === 'function') { <add> if (socket && socket.readableLength) { <ide> let buf; <ide> while ((buf = socket.read()) !== null) { <ide> debug(`Http2Session connect: injecting ${buf.length} already in buffer`);
1
Ruby
Ruby
remove unintentional api changes. []
d5921cdb7a00b393d0ba5f2f795da60a33b11cf1
<ide><path>activerecord/lib/active_record/associations/association_collection.rb <ide> def load_target <ide> end <ide> <ide> def method_missing(method, *args) <del> case method.to_s <del> when 'find_or_create' <del> return find(:first, :conditions => args.first) || create(args.first) <del> when /^find_or_create_by_(.*)$/ <del> rest = $1 <del> return send("find_by_#{rest}", *args) || <del> method_missing("create_by_#{rest}", *args) <del> when /^create_by_(.*)$/ <del> return create Hash[$1.split('_and_').zip(args)] <add> match = DynamicFinderMatch.match(method) <add> if match && match.creator? <add> attributes = match.attribute_names <add> return send(:"find_by_#{attributes.join('and')}", *args) || create(Hash[attributes.zip(args)]) <ide> end <ide> <ide> if @target.respond_to?(method) || ([email protected]_to?(method) && Class.respond_to?(method)) <ide><path>activerecord/lib/active_record/dynamic_finder_match.rb <ide> def instantiator? <ide> @finder == :first && [email protected]? <ide> end <ide> <add> def creator? <add> @finder == :first && @instantiator == :create <add> end <add> <ide> def bang? <ide> @bang <ide> end <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def setup <ide> Client.destroyed_client_ids.clear <ide> end <ide> <del> def test_create_by <del> person = Person.create! :first_name => 'tenderlove' <del> post = Post.find :first <add> def test_create_resets_cached_counters <add> person = Person.create!(:first_name => 'tenderlove') <add> post = Post.first <ide> <ide> assert_equal [], person.readers <del> assert_nil person.readers.find_by_post_id post.id <add> assert_nil person.readers.find_by_post_id(post.id) <ide> <del> reader = person.readers.create_by_post_id post.id <add> reader = person.readers.create(:post_id => post.id) <ide> <ide> assert_equal 1, person.readers.count <ide> assert_equal 1, person.readers.length <ide> assert_equal post, person.readers.first.post <ide> assert_equal person, person.readers.first.person <ide> end <ide> <del> def test_create_by_multi <add> def test_find_or_create_by_resets_cached_counters <ide> person = Person.create! :first_name => 'tenderlove' <del> post = Post.find :first <add> post = Post.first <ide> <ide> assert_equal [], person.readers <add> assert_nil person.readers.find_by_post_id(post.id) <ide> <del> reader = person.readers.create_by_post_id_and_skimmer post.id, false <add> reader = person.readers.find_or_create_by_post_id(post.id) <ide> <ide> assert_equal 1, person.readers.count <ide> assert_equal 1, person.readers.length <ide> assert_equal post, person.readers.first.post <ide> assert_equal person, person.readers.first.person <ide> end <ide> <del> def test_find_or_create_by <del> person = Person.create! :first_name => 'tenderlove' <del> post = Post.find :first <del> <del> assert_equal [], person.readers <del> assert_nil person.readers.find_by_post_id post.id <del> <del> reader = person.readers.find_or_create_by_post_id post.id <del> <del> assert_equal 1, person.readers.count <del> assert_equal 1, person.readers.length <del> assert_equal post, person.readers.first.post <del> assert_equal person, person.readers.first.person <del> end <del> <del> def test_find_or_create <del> person = Person.create! :first_name => 'tenderlove' <del> post = Post.find :first <del> <del> assert_equal [], person.readers <del> assert_nil person.readers.find(:first, :conditions => { <del> :post_id => post.id <del> }) <del> <del> reader = person.readers.find_or_create :post_id => post.id <del> <del> assert_equal 1, person.readers.count <del> assert_equal 1, person.readers.length <del> assert_equal post, person.readers.first.post <del> assert_equal person, person.readers.first.person <del> end <del> <del> <ide> def force_signal37_to_load_all_clients_of_firm <ide> companies(:first_firm).clients_of_firm.each {|f| } <ide> end
3
Python
Python
fix create_tokenizer when nlp is none
1f6c37c6f5bb733bea076ebd21d59e9ad62af2eb
<ide><path>spacy/language.py <ide> def create_tokenizer(cls, nlp=None): <ide> else: <ide> infix_finditer = None <ide> vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp) <del> return Tokenizer(nlp.vocab, rules=rules, <add> return Tokenizer(vocab, rules=rules, <ide> prefix_search=prefix_search, suffix_search=suffix_search, <ide> infix_finditer=infix_finditer) <ide>
1
Ruby
Ruby
push string handling to the builder object
3095f5ba38a7c230d5732af0128d9ddd7142ff7f
<ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb <ide> def polymorphic_url(record_or_hash_or_array, options = {}) <ide> method, args = builder.handle_model record, prefix, suffix <ide> <ide> when String, Symbol <del> method, args = handle_string record_or_hash_or_array, <del> prefix, <del> suffix, <del> inflection <add> method, args = builder.handle_string record_or_hash_or_array, <add> prefix, <add> suffix <ide> when Class <ide> method, args = builder.handle_class record_or_hash_or_array, <ide> prefix, <ide> def initialize(key_strategy) <ide> @key_strategy = key_strategy <ide> end <ide> <add> def handle_string(record, prefix, suffix) <add> method = prefix + "#{record}_#{suffix}" <add> [method, []] <add> end <add> <ide> def handle_class(klass, prefix, suffix) <ide> name = @key_strategy.call klass.model_name <ide> [prefix + "#{name}_#{suffix}", []] <ide> def handle_list(list, prefix, suffix, inflection) <ide> [named_route, args] <ide> end <ide> <del> def handle_string(record, prefix, suffix, inflection) <del> args = [] <del> method = prefix + "#{record}_#{suffix}" <del> [method, args] <del> end <del> <ide> def model_path_helper_call(record) <ide> handle_model record, ''.freeze, "path".freeze, ROUTE_KEY <ide> end
1
Python
Python
add tests for the `np.core.function_base` stubs
9677fad41873ee3b2bb6f2130c9cbd197903d0b1
<ide><path>numpy/tests/typing/fail/linspace.py <add>import numpy as np <add> <add>np.linspace(None, 'bob') # E: No overload variant <add>np.linspace(0, 2, num=10.0) # E: No overload variant <add>np.linspace(0, 2, endpoint='True') # E: No overload variant <add>np.linspace(0, 2, retstep=b'False') # E: No overload variant <add>np.linspace(0, 2, dtype=0) # E: No overload variant <add>np.linspace(0, 2, axis=None) # E: No overload variant <add> <add>np.logspace(None, 'bob') # E: Argument 1 <add>np.logspace(0, 2, base=None) # E: Argument "base" <add> <add>np.geomspace(None, 'bob') # E: Argument 1 <ide><path>numpy/tests/typing/pass/linspace.py <add>import numpy as np <add> <add>np.linspace(0, 2) <add>np.linspace(0.5, [0, 1, 2]) <add>np.linspace([0, 1, 2], 3) <add>np.linspace(0j, 2) <add>np.linspace(0, 2, num=10) <add>np.linspace(0, 2, endpoint=True) <add>np.linspace(0, 2, retstep=True) <add>np.linspace(0, 2, dtype=bool) <add>np.linspace([0, 1], [2, 3], axis=1) <add> <add>np.logspace(0, 2, base=2) <add>np.logspace(0, 2, base=2) <add>np.logspace(0, 2, base=[1j, 2j], num=2) <add> <add>np.geomspace(1, 2) <ide><path>numpy/tests/typing/reveal/linspace.py <add>import numpy as np <add> <add>reveal_type(np.linspace(0, 10)) # E: numpy.ndarray <add>reveal_type(np.linspace(0, 10, retstep=True)) # E: Tuple[numpy.ndarray, numpy.floating] <add>reveal_type(np.logspace(0, 10)) # E: numpy.ndarray <add>reveal_type(np.geomspace(1, 10)) # E: numpy.ndarray
3
Go
Go
remove log warning on task update
39c93cfb47783f2531ba44f062fd9a8b351d2224
<ide><path>daemon/cluster/executor/container/controller.go <ide> func (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, <ide> <ide> // Update tasks a recent task update and applies it to the container. <ide> func (r *controller) Update(ctx context.Context, t *api.Task) error { <del> log.G(ctx).Warnf("task updates not yet supported") <ide> // TODO(stevvooe): While assignment of tasks is idempotent, we do allow <ide> // updates of metadata, such as labelling, as well as any other properties <ide> // that make sense.
1
Ruby
Ruby
remove sqlite version support caveats [ci skip]
b608ee88e9c0d8058ee4964dcb6a603b85505d25
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def truncate_tables(*table_names) # :nodoc: <ide> # In order to get around this problem, #transaction will emulate the effect <ide> # of nested transactions, by using savepoints: <ide> # https://dev.mysql.com/doc/refman/5.7/en/savepoint.html <del> # Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8' <del> # supports savepoints. <ide> # <ide> # It is safe to call this method if a database transaction is already open, <ide> # i.e. if #transaction is called within another #transaction block. In case <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def rename_column(table_name, column_name, new_column_name) <ide> # <ide> # CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active <ide> # <del> # Note: Partial indexes are only supported for PostgreSQL and SQLite 3.8.0+. <add> # Note: Partial indexes are only supported for PostgreSQL and SQLite. <ide> # <ide> # ====== Creating an index with a specific method <ide> # <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def sqlite3_connection(config) <ide> end <ide> <ide> module ConnectionAdapters #:nodoc: <del> # The SQLite3 adapter works SQLite 3.6.16 or newer <del> # with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3). <add> # The SQLite3 adapter works with the sqlite3-ruby drivers <add> # (available as gem from https://rubygems.org/gems/sqlite3). <ide> # <ide> # Options: <ide> # <ide><path>activerecord/lib/active_record/transactions.rb <ide> module Transactions <ide> # end <ide> # end <ide> # <del> # only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it. <add> # only "Kotori" is created. <ide> # <ide> # Most databases don't support true nested transactions. At the time of <ide> # writing, the only database that we're aware of that supports true nested <ide> # transactions, is MS-SQL. Because of this, Active Record emulates nested <del> # transactions by using savepoints on MySQL and PostgreSQL. See <add> # transactions by using savepoints. See <ide> # https://dev.mysql.com/doc/refman/5.7/en/savepoint.html <ide> # for more information about savepoints. <ide> #
4
Javascript
Javascript
destroy instance before application
bff547d15646b3fba3a5700b5ca16f0adfc39f2c
<ide><path>blueprints/instance-initializer-test/qunit-rfc-232-files/__root__/__testType__/__path__/__name__-test.js <ide> module('<%= friendlyTestName %>', function(hooks) { <ide> this.instance = this.application.buildInstance(); <ide> }); <ide> hooks.afterEach(function() { <del> <% if (destroyAppExists) { %>destroyApp(this.application);<% } else { %>run(this.application, 'destroy');<% } %> <ide> <% if (destroyAppExists) { %>destroyApp(this.instance);<% } else { %>run(this.instance, 'destroy');<% } %> <add> <% if (destroyAppExists) { %>destroyApp(this.application);<% } else { %>run(this.application, 'destroy');<% } %> <ide> }); <ide> <ide> // Replace this with your real tests. <ide><path>node-tests/fixtures/instance-initializer-test/module-unification/rfc232.js <ide> module('Unit | Instance Initializer | foo', function(hooks) { <ide> this.instance = this.application.buildInstance(); <ide> }); <ide> hooks.afterEach(function() { <del> run(this.application, 'destroy'); <ide> run(this.instance, 'destroy'); <add> run(this.application, 'destroy'); <ide> }); <ide> <ide> // Replace this with your real tests. <ide><path>node-tests/fixtures/instance-initializer-test/rfc232.js <ide> module('Unit | Instance Initializer | foo', function(hooks) { <ide> this.instance = this.application.buildInstance(); <ide> }); <ide> hooks.afterEach(function() { <del> run(this.application, 'destroy'); <ide> run(this.instance, 'destroy'); <add> run(this.application, 'destroy'); <ide> }); <ide> <ide> // Replace this with your real tests.
3
Python
Python
fix typos of model name
2472278cabc5a276b3ddfda86d8287c7c3607a7b
<ide><path>official/keras_application_models/dataset.py <ide> from __future__ import print_function <ide> <ide> import tensorflow as tf <del> <ide> from official.utils.misc import model_helpers # pylint: disable=g-bad-import-order <ide> <ide> # Default values for dataset. <ide> def _get_default_image_size(model): <ide> """Provide default image size for each model.""" <ide> image_size = (224, 224) <del> if model in ["inception", "xception", "inceptionresnet"]: <add> if model in ["inceptionv3", "xception", "inceptionresnetv2"]: <ide> image_size = (299, 299) <ide> elif model in ["nasnetlarge"]: <ide> image_size = (331, 331) <ide> def generate_synthetic_input_dataset(model, batch_size): <ide> image_shape = (batch_size,) + image_size + (_NUM_CHANNELS,) <ide> label_shape = (batch_size, _NUM_CLASSES) <ide> <del> return model_helpers.generate_synthetic_data( <add> dataset = model_helpers.generate_synthetic_data( <ide> input_shape=tf.TensorShape(image_shape), <del> input_dtype=tf.float32, <ide> label_shape=tf.TensorShape(label_shape), <del> label_dtype=tf.float32) <add> ) <add> return dataset
1
Javascript
Javascript
set current url, if not defined or empty string
3171f215910255938c179d8243480fbaeebc77cf
<ide><path>src/service/httpBackend.js <ide> function createHttpBackend($browser, XHR, $browserDefer, callbacks, body, locati <ide> // TODO(vojta): fix the signature <ide> return function(method, url, post, callback, headers, timeout) { <ide> $browser.$$incOutstandingRequestCount(); <add> url = url || $browser.url(); <ide> <ide> if (lowercase(method) == 'jsonp') { <ide> var callbackId = '_' + (callbacks.counter++).toString(36); <ide><path>test/service/httpBackendSpec.js <ide> describe('$httpBackend', function() { <ide> }); <ide> <ide> <add> it('should set url to current location if not specified or empty string', function() { <add> $backend('JSONP', undefined, null, callback); <add> expect($browser.$$scripts[0].url).toBe($browser.url()); <add> $browser.$$scripts.shift(); <add> <add> $backend('JSONP', '', null, callback); <add> expect($browser.$$scripts[0].url).toBe($browser.url()); <add> $browser.$$scripts.shift(); <add> }); <add> <add> <ide> // TODO(vojta): test whether it fires "async-start" <ide> // TODO(vojta): test whether it fires "async-end" on both success and error <ide> });
2
Text
Text
fix typo in "readonly" flag in documentation
ac12696ff48aeb115e3d9ce3b13cfa54342b5aee
<ide><path>docs/reference/commandline/dockerd.md <ide> The following standard Docker features are currently incompatible when <ide> running a Docker daemon with user namespaces enabled: <ide> <ide> - sharing PID or NET namespaces with the host (`--pid=host` or `--net=host`) <del> - A `--readonly` container filesystem (this is a Linux kernel restriction against remounting with modified flags of a currently mounted filesystem when inside a user namespace) <add> - A `--read-only` container filesystem (this is a Linux kernel restriction against remounting with modified flags of a currently mounted filesystem when inside a user namespace) <ide> - external (volume or graph) drivers which are unaware/incapable of using daemon user mappings <ide> - Using `--privileged` mode flag on `docker run` (unless also specifying `--userns=host`) <ide>
1
PHP
PHP
add a method to get all subdirectories of a folder
a74d0567e4b3836ac9a4b7aecafb9bb5fefd1647
<ide><path>src/Filesystem/Folder.php <ide> public function chmod($path, $mode = false, $recursive = true, array $exceptions <ide> return false; <ide> } <ide> <add> /** <add> * Returns an array of subdirectories for the provided or current path. <add> * <add> * @param string|null $path The directory path to get subdirectories for. <add> * @param bool $fullPath Wheter to return the full path or only the directory name. <add> * @return array Array of subdirectories for the provided or current path. <add> */ <add> public function subdirectories($path = null, $fullPath = true) <add> { <add> if (!$path) { <add> $path = $this->path; <add> } <add> $subdirectories = []; <add> <add> try { <add> $iterator = new DirectoryIterator($path); <add> } catch (Exception $e) { <add> return []; <add> } <add> <add> foreach ($iterator as $item) { <add> if (!$item->isDir() || $item->isDot()) { <add> continue; <add> } <add> $subdirectories[] = $fullPath ? $item->getRealPath() : $item->getFilename(); <add> } <add> return $subdirectories; <add> } <add> <ide> /** <ide> * Returns an array of nested directories and files in each directory <ide> * <ide><path>tests/TestCase/Filesystem/FolderTest.php <ide> public function testFolderReadWithHiddenFiles() <ide> $this->assertEquals($expected, $result); <ide> } <ide> <add> /** <add> * testFolderSubdirectories method <add> * <add> * @return void <add> */ <add> public function testFolderSubdirectories() <add> { <add> $path = CAKE . 'Network'; <add> $folder = new Folder($path); <add> <add> $expected = [ <add> $path . DS . 'Exception', <add> $path . DS . 'Http', <add> $path . DS . 'Session' <add> ]; <add> $result = $folder->subdirectories(); <add> $this->assertEquals($expected, $result); <add> $result = $folder->subdirectories($path); <add> $this->assertEquals($expected, $result); <add> <add> $expected = [ <add> 'Exception', <add> 'Http', <add> 'Session' <add> ]; <add> $result = $folder->subdirectories(null, false); <add> $this->assertEquals($expected, $result); <add> $result = $folder->subdirectories($path, false); <add> $this->assertEquals($expected, $result); <add> <add> $expected = []; <add> $result = $folder->subdirectories('NonExistantPath'); <add> $this->assertEquals($expected, $result); <add> $result = $folder->subdirectories($path . DS . 'Exception'); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> /** <ide> * testFolderTree method <ide> * <ide> public function testMoveWithSkip() <ide> $Folder = new Folder($path); <ide> $Folder->delete(); <ide> } <del> <add> <ide> public function testMoveWithoutRecursive() <ide> { <ide> extract($this->_setupFilesystem());
2
Python
Python
modify centernet to output extracted features
d5ae12e1d4363f1b388390285ed40d3ac953d54a
<ide><path>research/object_detection/meta_architectures/center_net_meta_arch.py <ide> def predict(self, preprocessed_inputs, _): <ide> prediction_dict: a dictionary holding predicted tensors with <ide> 'preprocessed_inputs' - The input image after being resized and <ide> preprocessed by the feature extractor. <add> 'extracted_features' - The output of the feature extractor. <ide> 'object_center' - A list of size num_feature_outputs containing <ide> float tensors of size [batch_size, output_height, output_width, <ide> num_classes] representing the predicted object center heatmap logits. <ide> def predict(self, preprocessed_inputs, _): <ide> predictions[head_name] = [ <ide> head(feature) for (feature, head) in zip(features_list, heads) <ide> ] <add> predictions['extracted_features'] = features_list <ide> predictions['preprocessed_inputs'] = preprocessed_inputs <ide> <ide> self._batched_prediction_tensor_names = predictions.keys() <ide><path>research/object_detection/meta_architectures/center_net_meta_arch_tf2_test.py <ide> def test_outputs_with_correct_shape(self, stride): <ide> postprocess_output = arch.postprocess(predictions, true_shapes) <ide> losses_output = arch.loss(predictions, true_shapes) <ide> <add> self.assertIn('extracted_features', predictions) <ide> self.assertIn('%s/%s' % (cnma.LOSS_KEY_PREFIX, cnma.OBJECT_CENTER), <ide> losses_output) <ide> self.assertEqual((), losses_output['%s/%s' % (
2
Ruby
Ruby
hide the deprecated methods from the docs
72c51356c5e59c73710ee5f3feba57b52a38af81
<ide><path>actionpack/lib/action_controller/assertions.rb <ide> def assert_redirected_to(options = {}, message=nil) <ide> end <ide> end <ide> <del> # Asserts that the request was rendered with the appropriate template file <del> def assert_template(expected=nil, message=nil) <add> # Asserts that the request was rendered with the appropriate template file. <add> def assert_template(expected = nil, message=nil) <ide> rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file <ide> msg = build_message(message, "expecting <?> but rendering with <?>", expected, rendered) <ide> assert_block(msg) do <ide> def assert_template(expected=nil, message=nil) <ide> end <ide> end <ide> <del> alias_method :assert_rendered_file, :assert_template #:nodoc: <del> <del> # -- routing assertions -------------------------------------------------- <del> <ide> # Asserts that the routing of the given path is handled correctly and that the parsed options match. <ide> def assert_recognizes(expected_options, path, extras={}, message=nil) <ide> # Load routes.rb if it hasn't been loaded. <ide><path>actionpack/lib/action_controller/deprecated_assertions.rb <ide> <ide> module Test #:nodoc: <ide> module Unit #:nodoc: <del> module Assertions #:nodoc: <del> def assert_success(message=nil) <add> module Assertions <add> def assert_success(message=nil) #:nodoc: <ide> assert_response(:success, message) <ide> end <ide> <del> def assert_redirect(message=nil) <add> def assert_redirect(message=nil) #:nodoc: <ide> assert_response(:redirect, message) <ide> end <ide> <add> def assert_rendered_file(expected=nil, message=nil) #:nodoc: <add> assert_template(expected, message) <add> end <add> <ide> # ensure that the session has an object with the specified name <del> def assert_session_has(key=nil, message=nil) <add> def assert_session_has(key=nil, message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is not in the session <?>", key, @response.session) <ide> assert_block(msg) { @response.has_session_object?(key) } <ide> end <ide> <ide> # ensure that the session has no object with the specified name <del> def assert_session_has_no(key=nil, message=nil) <add> def assert_session_has_no(key=nil, message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is in the session <?>", key, @response.session) <ide> assert_block(msg) { [email protected]_session_object?(key) } <ide> end <ide> <del> def assert_session_equal(expected = nil, key = nil, message = nil) <add> def assert_session_equal(expected = nil, key = nil, message = nil) #:nodoc: <ide> msg = build_message(message, "<?> expected in session['?'] but was <?>", expected, key, @response.session[key]) <ide> assert_block(msg) { expected == @response.session[key] } <ide> end <ide> <ide> # -- cookie assertions --------------------------------------------------- <ide> <del> def assert_no_cookie(key = nil, message = nil) <add> def assert_no_cookie(key = nil, message = nil) #:nodoc: <ide> actual = @response.cookies[key] <ide> msg = build_message(message, "<?> not expected in cookies['?']", actual, key) <ide> assert_block(msg) { actual.nil? or actual.empty? } <ide> end <ide> <del> def assert_cookie_equal(expected = nil, key = nil, message = nil) <add> def assert_cookie_equal(expected = nil, key = nil, message = nil) #:nodoc: <ide> actual = @response.cookies[key] <ide> actual = actual.first if actual <ide> msg = build_message(message, "<?> expected in cookies['?'] but was <?>", expected, key, actual) <ide> def assert_cookie_equal(expected = nil, key = nil, message = nil) <ide> # -- flash assertions --------------------------------------------------- <ide> <ide> # ensure that the flash has an object with the specified name <del> def assert_flash_has(key=nil, message=nil) <add> def assert_flash_has(key=nil, message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is not in the flash <?>", key, @response.flash) <ide> assert_block(msg) { @response.has_flash_object?(key) } <ide> end <ide> <ide> # ensure that the flash has no object with the specified name <del> def assert_flash_has_no(key=nil, message=nil) <add> def assert_flash_has_no(key=nil, message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is in the flash <?>", key, @response.flash) <ide> assert_block(msg) { [email protected]_flash_object?(key) } <ide> end <ide> <ide> # ensure the flash exists <del> def assert_flash_exists(message=nil) <add> def assert_flash_exists(message=nil) #:nodoc: <ide> msg = build_message(message, "the flash does not exist <?>", @response.session['flash'] ) <ide> assert_block(msg) { @response.has_flash? } <ide> end <ide> <ide> # ensure the flash does not exist <del> def assert_flash_not_exists(message=nil) <add> def assert_flash_not_exists(message=nil) #:nodoc: <ide> msg = build_message(message, "the flash exists <?>", @response.flash) <ide> assert_block(msg) { [email protected]_flash? } <ide> end <ide> <ide> # ensure the flash is empty but existent <del> def assert_flash_empty(message=nil) <add> def assert_flash_empty(message=nil) #:nodoc: <ide> msg = build_message(message, "the flash is not empty <?>", @response.flash) <ide> assert_block(msg) { [email protected]_flash_with_contents? } <ide> end <ide> <ide> # ensure the flash is not empty <del> def assert_flash_not_empty(message=nil) <add> def assert_flash_not_empty(message=nil) #:nodoc: <ide> msg = build_message(message, "the flash is empty") <ide> assert_block(msg) { @response.has_flash_with_contents? } <ide> end <ide> <del> def assert_flash_equal(expected = nil, key = nil, message = nil) <add> def assert_flash_equal(expected = nil, key = nil, message = nil) #:nodoc: <ide> msg = build_message(message, "<?> expected in flash['?'] but was <?>", expected, key, @response.flash[key]) <ide> assert_block(msg) { expected == @response.flash[key] } <ide> end <ide> <ide> <ide> # ensure our redirection url is an exact match <del> def assert_redirect_url(url=nil, message=nil) <add> def assert_redirect_url(url=nil, message=nil) #:nodoc: <ide> assert_redirect(message) <ide> msg = build_message(message, "<?> is not the redirected location <?>", url, @response.redirect_url) <ide> assert_block(msg) { @response.redirect_url == url } <ide> end <ide> <ide> # ensure our redirection url matches a pattern <del> def assert_redirect_url_match(pattern=nil, message=nil) <add> def assert_redirect_url_match(pattern=nil, message=nil) #:nodoc: <ide> assert_redirect(message) <ide> msg = build_message(message, "<?> was not found in the location: <?>", pattern, @response.redirect_url) <ide> assert_block(msg) { @response.redirect_url_match?(pattern) } <ide> def assert_redirect_url_match(pattern=nil, message=nil) <ide> # -- template assertions ------------------------------------------------ <ide> <ide> # ensure that a template object with the given name exists <del> def assert_template_has(key=nil, message=nil) <add> def assert_template_has(key=nil, message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is not a template object", key ) <ide> assert_block(msg) { @response.has_template_object?(key) } <ide> end <ide> <ide> # ensure that a template object with the given name does not exist <del> def assert_template_has_no(key=nil,message=nil) <add> def assert_template_has_no(key=nil,message=nil) #:nodoc: <ide> msg = build_message(message, "<?> is a template object <?>", key, @response.template_objects[key]) <ide> assert_block(msg) { [email protected]_template_object?(key) } <ide> end <ide> <ide> # ensures that the object assigned to the template on +key+ is equal to +expected+ object. <del> def assert_template_equal(expected = nil, key = nil, message = nil) <add> def assert_template_equal(expected = nil, key = nil, message = nil) #:nodoc: <ide> msg = build_message(message, "<?> expected in assigns['?'] but was <?>", expected, key, @response.template.assigns[key.to_s]) <ide> assert_block(msg) { expected == @response.template.assigns[key.to_s] } <ide> end <ide> alias_method :assert_assigned_equal, :assert_template_equal <ide> <ide> # Asserts that the template returns the +expected+ string or array based on the XPath +expression+. <ide> # This will only work if the template rendered a valid XML document. <del> def assert_template_xpath_match(expression=nil, expected=nil, message=nil) <add> def assert_template_xpath_match(expression=nil, expected=nil, message=nil) #:nodoc: <ide> xml, matches = REXML::Document.new(@response.body), [] <ide> xml.elements.each(expression) { |e| matches << e.text } <ide> if matches.empty? then <ide> def assert_template_xpath_match(expression=nil, expected=nil, message=nil) <ide> end <ide> <ide> # Assert the template object with the given name is an Active Record descendant and is valid. <del> def assert_valid_record(key = nil, message = nil) <add> def assert_valid_record(key = nil, message = nil) #:nodoc: <ide> record = find_record_in_template(key) <ide> msg = build_message(message, "Active Record is invalid <?>)", record.errors.full_messages) <ide> assert_block(msg) { record.valid? } <ide> end <ide> <ide> # Assert the template object with the given name is an Active Record descendant and is invalid. <del> def assert_invalid_record(key = nil, message = nil) <add> def assert_invalid_record(key = nil, message = nil) #:nodoc: <ide> record = find_record_in_template(key) <ide> msg = build_message(message, "Active Record is valid)") <ide> assert_block(msg) { !record.valid? } <ide> end <ide> <ide> # Assert the template object with the given name is an Active Record descendant and the specified column(s) are valid. <del> def assert_valid_column_on_record(key = nil, columns = "", message = nil) <add> def assert_valid_column_on_record(key = nil, columns = "", message = nil) #:nodoc: <ide> record = find_record_in_template(key) <ide> record.send(:validate) <ide> <ide> def assert_valid_column_on_record(key = nil, columns = "", message = nil) <ide> end <ide> <ide> # Assert the template object with the given name is an Active Record descendant and the specified column(s) are invalid. <del> def assert_invalid_column_on_record(key = nil, columns = "", message = nil) <add> def assert_invalid_column_on_record(key = nil, columns = "", message = nil) #:nodoc: <ide> record = find_record_in_template(key) <ide> record.send(:validate) <ide>
2
Ruby
Ruby
add missing test cases for `attribute_method?`
1c4fa54eec0b49f19ba0107a2028c354d60a9033
<ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def some_method_that_is_not_on_super <ide> end <ide> end <ide> <add> def test_attribute_method? <add> assert @target.attribute_method?(:title) <add> assert @target.attribute_method?(:title=) <add> assert_not @target.attribute_method?(:wibble) <add> end <add> <add> def test_attribute_method_returns_false_if_table_does_not_exist <add> @target.table_name = 'wibble' <add> assert_not @target.attribute_method?(:title) <add> end <add> <ide> private <ide> <ide> def new_topic_like_ar_class(&block)
1
Python
Python
fix resize_token_embeddings for transformer-xl
e80d6c689bd62f805a5c8d77ec0cc3b09f240d14
<ide><path>src/transformers/modeling_transfo_xl.py <ide> <ide> <ide> import logging <add>from typing import Optional <ide> <ide> import torch <ide> import torch.nn as nn <ide> def _init_weights(self, m): <ide> if hasattr(m, "r_bias"): <ide> self._init_bias(m.r_bias) <ide> <add> def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1): <add> """ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. <add> Take care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. <add> <add> Arguments: <add> <add> new_num_tokens: (`optional`) int: <add> New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. <add> If not provided or None: does nothing and just returns a pointer to the input tokens ``torch.nn.Embeddings`` Module of the model. <add> layer: (`optional`) int: <add> Layer of the `AdaptiveEmbedding` where the resizing should be done. Per default the last layer will be resized. <add> Be aware that when resizing other than the last layer, you have to ensure that the new token(s) in the tokenizer are at the corresponding position. <add> <add> Return: ``torch.nn.Embeddings`` <add> Pointer to the input tokens Embeddings Module of the model <add> """ <add> base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed <add> <add> if new_num_tokens is None: <add> return self.get_input_embeddings() <add> <add> new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer) <add> assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less" <add> model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer) <add> <add> # Update base model and current model config <add> self.config.vocab_size = new_num_tokens <add> base_model.vocab_size = new_num_tokens <add> base_model.n_token = new_num_tokens <add> <add> new_embedding_shapes = self._get_embedding_shapes() <add> self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer) <add> <add> # Tie weights again if needed <add> self.tie_weights() <add> <add> return model_embeds <add> <add> def _get_new_num_tokens_layer(self, new_num_tokens, layer): <add> embeddings = self.get_input_embeddings() <add> if layer == -1: <add> layer = len(embeddings.emb_layers) - 1 <add> assert 0 <= layer <= len(embeddings.emb_layers) - 1 <add> <add> new_num_tokens_layer = ( <add> new_num_tokens <add> - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]]) <add> - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]]) <add> ) <add> return new_num_tokens_layer, layer <add> <add> def _get_embedding_shapes(self): <add> embeddings = self.get_input_embeddings() <add> return [emb.weight.shape[0] for emb in embeddings.emb_layers] <add> <add> def _resize_token_embeddings(self, new_num_tokens, layer=-1): <add> embeddings = self.get_input_embeddings() <add> if new_num_tokens is None: <add> return embeddings <add> new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens) <add> embeddings.emb_layers[layer] = new_embeddings_layer <add> <add> self.set_input_embeddings(embeddings) <add> <add> return self.get_input_embeddings() <add> <add> def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): <add> embeddings = self.get_input_embeddings() <add> <add> for i in range(layer, len(embeddings.cutoffs)): <add> embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1]) <add> <add> embeddings.cutoff_ends = [0] + embeddings.cutoffs <add> embeddings.n_token = new_num_tokens <add> <add> self.config.cutoffs = embeddings.cutoffs[:-1] <add> <add> return embeddings.cutoffs <add> <ide> <ide> TRANSFO_XL_START_DOCSTRING = r""" <ide> <ide> def prepare_inputs_for_generation(self, input_ids, past, **model_kwargs): <ide> inputs["mems"] = past <ide> <ide> return inputs <add> <add> def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): <add> new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer) <add> <add> self.crit.cutoffs = new_cutoffs <add> self.crit.cutoff_ends = [0] + new_cutoffs <add> self.crit.n_token = new_num_tokens <ide><path>tests/test_modeling_transfo_xl.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del> <del> <add>import copy <ide> import random <ide> import unittest <ide> <ide> class TransfoXLModelTest(ModelTesterMixin, unittest.TestCase): <ide> all_generative_model_classes = (TransfoXLLMHeadModel,) if is_torch_available() else () <ide> test_pruning = False <ide> test_torchscript = False <del> test_resize_embeddings = False <add> test_resize_embeddings = True <ide> <ide> class TransfoXLModelTester(object): <ide> def __init__( <ide> def prepare_config_and_inputs_for_common(self): <ide> inputs_dict = {"input_ids": input_ids_1} <ide> return config, inputs_dict <ide> <add> def check_cutoffs_and_n_token( <add> self, copied_cutoffs, layer, model_embed, model, model_class, resized_value, vocab_size <add> ): <add> # Check that the cutoffs were modified accordingly <add> for i in range(len(copied_cutoffs)): <add> if i < layer: <add> self.assertEqual(model_embed.cutoffs[i], copied_cutoffs[i]) <add> if model_class == TransfoXLLMHeadModel: <add> self.assertEqual(model.crit.cutoffs[i], copied_cutoffs[i]) <add> if i < len(model.config.cutoffs): <add> self.assertEqual(model.config.cutoffs[i], copied_cutoffs[i]) <add> else: <add> self.assertEqual(model_embed.cutoffs[i], copied_cutoffs[i] + resized_value) <add> if model_class == TransfoXLLMHeadModel: <add> self.assertEqual(model.crit.cutoffs[i], copied_cutoffs[i] + resized_value) <add> if i < len(model.config.cutoffs): <add> self.assertEqual(model.config.cutoffs[i], copied_cutoffs[i] + resized_value) <add> <add> self.assertEqual(model_embed.n_token, vocab_size + resized_value) <add> if model_class == TransfoXLLMHeadModel: <add> self.assertEqual(model.crit.n_token, vocab_size + resized_value) <add> <ide> def setUp(self): <ide> self.model_tester = TransfoXLModelTest.TransfoXLModelTester(self) <ide> self.config_tester = ConfigTester(self, config_class=TransfoXLConfig, d_embed=37) <ide> def test_model_from_pretrained(self): <ide> model = TransfoXLModel.from_pretrained(model_name) <ide> self.assertIsNotNone(model) <ide> <add> def test_resize_tokens_embeddings(self): <add> (original_config, inputs_dict) = self.model_tester.prepare_config_and_inputs_for_common() <add> if not self.test_resize_embeddings: <add> return <add> <add> for model_class in self.all_model_classes: <add> config = copy.deepcopy(original_config) <add> model = model_class(config) <add> model.to(torch_device) <add> <add> if self.model_tester.is_training is False: <add> model.eval() <add> <add> model_vocab_size = config.vocab_size <add> # Retrieve the embeddings and clone theme <add> model_embed = model.resize_token_embeddings(model_vocab_size) <add> cloned_embeddings = [emb.weight.clone() for emb in model_embed.emb_layers] <add> # Retrieve the cutoffs and copy them <add> copied_cutoffs = copy.copy(model_embed.cutoffs) <add> <add> test_layers = [x for x in range(config.div_val)] <add> for layer in test_layers: <add> # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size <add> model_embed = model.resize_token_embeddings(model_vocab_size + 10, layer) <add> self.assertEqual(model.config.vocab_size, model_vocab_size + 10) <add> # Check that it actually resizes the embeddings matrix <add> self.assertEqual(model_embed.emb_layers[layer].weight.shape[0], cloned_embeddings[layer].shape[0] + 10) <add> # Check that the cutoffs were modified accordingly <add> self.check_cutoffs_and_n_token( <add> copied_cutoffs, layer, model_embed, model, model_class, 10, model_vocab_size <add> ) <add> <add> # Check that the model can still do a forward pass successfully (every parameter should be resized) <add> model(**inputs_dict) <add> <add> # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size <add> model_embed = model.resize_token_embeddings(model_vocab_size - 5, layer) <add> self.assertEqual(model.config.vocab_size, model_vocab_size - 5) <add> # Check that it actually resizes the embeddings matrix <add> self.assertEqual(model_embed.emb_layers[layer].weight.shape[0], cloned_embeddings[layer].shape[0] - 5) <add> # Check that the cutoffs were modified accordingly <add> self.check_cutoffs_and_n_token( <add> copied_cutoffs, layer, model_embed, model, model_class, -5, model_vocab_size <add> ) <add> <add> # Check that the model can still do a forward pass successfully (every parameter should be resized) <add> # Input ids should be clamped to the maximum size of the vocabulary <add> inputs_dict["input_ids"].clamp_(max=model_vocab_size - 5 - 1) <add> model(**inputs_dict) <add> <add> # Check that adding and removing tokens has not modified the first part of the embedding matrix. <add> models_equal = True <add> for p1, p2 in zip(cloned_embeddings[layer], model_embed.emb_layers[layer].weight): <add> if p1.data.ne(p2.data).sum() > 0: <add> models_equal = False <add> <add> self.assertTrue(models_equal) <add> <add> # Reset model embeddings to original size <add> model.resize_token_embeddings(model_vocab_size, layer) <add> self.assertEqual(model_vocab_size, model.config.vocab_size) <add> self.assertEqual(model_embed.emb_layers[layer].weight.shape[0], cloned_embeddings[layer].shape[0]) <add> <ide> <ide> class TransfoXLModelLanguageGenerationTest(unittest.TestCase): <ide> @slow
2
Javascript
Javascript
update nativearray documentation
1fc88025c5427f120d7f46d2ebeced70a0484681
<ide><path>packages/ember-runtime/lib/system/native_array.js <ide> import copy from 'ember-runtime/copy'; <ide> Array support Ember.MutableArray and all of its dependent APIs. Unless you <ide> have `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Array` set to <ide> false, this will be applied automatically. Otherwise you can apply the mixin <del> at anytime by calling `Ember.NativeArray.activate`. <add> at anytime by calling `Ember.NativeArray.apply(Array.prototype)`. <ide> <ide> @class NativeArray <ide> @namespace Ember
1
Javascript
Javascript
change common.port to arbitrary port
4f5685d233d45be2c25f89e8cb2e3d0b30989b3e
<ide><path>test/sequential/test-child-process-fork-getconnections.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const fork = require('child_process').fork; <ide> const net = require('net'); <ide> if (process.argv[2] === 'child') { <ide> server.on('listening', function() { <ide> let j = count; <ide> while (j--) { <del> const client = net.connect(common.PORT, '127.0.0.1'); <add> const client = net.connect(server.address().port, '127.0.0.1'); <ide> client.on('close', function() { <ide> disconnected += 1; <ide> }); <ide> if (process.argv[2] === 'child') { <ide> closeEmitted = true; <ide> }); <ide> <del> server.listen(common.PORT, '127.0.0.1'); <add> server.listen(0, '127.0.0.1'); <ide> <ide> process.on('exit', function() { <ide> assert.strictEqual(sent, count);
1
PHP
PHP
fix return value
7ce43078c2a46f7fcfc7f6f5b90fd3ff7a32f391
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php <ide> protected function partitionDataAndAttributes($class, array $attributes) <ide> <ide> return collect($attributes)->partition(function ($value, $key) use ($parameterNames) { <ide> return in_array(Str::camel($key), $parameterNames); <del> }); <add> })->all(); <ide> } <ide> <ide> /**
1
Ruby
Ruby
add action cable test case and test helper
c11ca0996227ef6f3b6154e4742a9e03949557df
<ide><path>actioncable/lib/action_cable.rb <ide> module ActionCable <ide> autoload :Channel <ide> autoload :RemoteConnections <ide> autoload :SubscriptionAdapter <add> autoload :TestHelper <add> autoload :TestCase <ide> end <ide><path>actioncable/lib/action_cable/test_case.rb <add># frozen_string_literal: true <add> <add>require "active_support/test_case" <add> <add>module ActionCable <add> class TestCase < ActiveSupport::TestCase <add> include ActionCable::TestHelper <add> <add> ActiveSupport.run_load_hooks(:action_cable_test_case, self) <add> end <add>end <ide><path>actioncable/lib/action_cable/test_helper.rb <add># frozen_string_literal: true <add> <add>module ActionCable <add> # Provides helper methods for testing Action Cable broadcasting <add> module TestHelper <add> def before_setup # :nodoc: <add> server = ActionCable.server <add> test_adapter = ActionCable::SubscriptionAdapter::Test.new(server) <add> <add> @old_pubsub_adapter = server.pubsub <add> <add> server.instance_variable_set(:@pubsub, test_adapter) <add> super <add> end <add> <add> def after_teardown # :nodoc: <add> super <add> ActionCable.server.instance_variable_set(:@pubsub, @old_pubsub_adapter) <add> end <add> <add> # Asserts that the number of broadcasted messages to the stream matches the given number. <add> # <add> # def test_broadcasts <add> # assert_broadcasts 'messages', 0 <add> # ActionCable.server.broadcast 'messages', { text: 'hello' } <add> # assert_broadcasts 'messages', 1 <add> # ActionCable.server.broadcast 'messages', { text: 'world' } <add> # assert_broadcasts 'messages', 2 <add> # end <add> # <add> # If a block is passed, that block should cause the specified number of <add> # messages to be broadcasted. <add> # <add> # def test_broadcasts_again <add> # assert_broadcasts('messages', 1) do <add> # ActionCable.server.broadcast 'messages', { text: 'hello' } <add> # end <add> # <add> # assert_broadcasts('messages', 2) do <add> # ActionCable.server.broadcast 'messages', { text: 'hi' } <add> # ActionCable.server.broadcast 'messages', { text: 'how are you?' } <add> # end <add> # end <add> # <add> def assert_broadcasts(stream, number) <add> if block_given? <add> original_count = broadcasts_size(stream) <add> yield <add> new_count = broadcasts_size(stream) <add> assert_equal number, new_count - original_count, "#{number} broadcasts to #{stream} expected, but #{new_count - original_count} were sent" <add> else <add> actual_count = broadcasts_size(stream) <add> assert_equal number, actual_count, "#{number} broadcasts to #{stream} expected, but #{actual_count} were sent" <add> end <add> end <add> <add> # Asserts that no messages have been sent to the stream. <add> # <add> # def test_no_broadcasts <add> # assert_no_broadcasts 'messages' <add> # ActionCable.server.broadcast 'messages', { text: 'hi' } <add> # assert_broadcasts 'messages', 1 <add> # end <add> # <add> # If a block is passed, that block should not cause any message to be sent. <add> # <add> # def test_broadcasts_again <add> # assert_no_broadcasts 'messages' do <add> # # No job messages should be sent from this block <add> # end <add> # end <add> # <add> # Note: This assertion is simply a shortcut for: <add> # <add> # assert_broadcasts 'messages', 0, &block <add> # <add> def assert_no_broadcasts(stream, &block) <add> assert_broadcasts stream, 0, &block <add> end <add> <add> # Asserts that the specified message has been sent to the stream. <add> # <add> # def test_assert_transmited_message <add> # ActionCable.server.broadcast 'messages', text: 'hello' <add> # assert_broadcast_on('messages', text: 'hello') <add> # end <add> # <add> # If a block is passed, that block should cause a message with the specified data to be sent. <add> # <add> # def test_assert_broadcast_on_again <add> # assert_broadcast_on('messages', text: 'hello') do <add> # ActionCable.server.broadcast 'messages', text: 'hello' <add> # end <add> # end <add> # <add> def assert_broadcast_on(stream, data) <add> # Encode to JSON and back–we want to use this value to compare <add> # with decoded JSON. <add> # Comparing JSON strings doesn't work due to the order if the keys. <add> serialized_msg = <add> ActiveSupport::JSON.decode(ActiveSupport::JSON.encode(data)) <add> <add> new_messages = broadcasts(stream) <add> if block_given? <add> old_messages = new_messages <add> clear_messages(stream) <add> <add> yield <add> new_messages = broadcasts(stream) <add> clear_messages(stream) <add> <add> # Restore all sent messages <add> (old_messages + new_messages).each { |m| pubsub_adapter.broadcast(stream, m) } <add> end <add> <add> message = new_messages.find { |msg| ActiveSupport::JSON.decode(msg) == serialized_msg } <add> <add> assert message, "No messages sent with #{data} to #{stream}" <add> end <add> <add> def pubsub_adapter # :nodoc: <add> ActionCable.server.pubsub <add> end <add> <add> delegate :broadcasts, :clear_messages, to: :pubsub_adapter <add> <add> private <add> def broadcasts_size(channel) # :nodoc: <add> broadcasts(channel).size <add> end <add> end <add>end <ide><path>actioncable/test/test_helper.rb <ide> # Require all the stubs and models <ide> Dir[File.expand_path("stubs/*.rb", __dir__)].each { |file| require file } <ide> <add># Set test adapter and logger <add>ActionCable.server.config.cable = { "adapter" => "test" } <add>ActionCable.server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN } <add> <ide> class ActionCable::TestCase < ActiveSupport::TestCase <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <ide><path>actioncable/test/test_helper_test.rb <add># frozen_string_literal: true <add> <add>require "test_helper" <add> <add>class BroadcastChannel < ActionCable::Channel::Base <add>end <add> <add>class TransmissionsTest < ActionCable::TestCase <add> def test_assert_broadcasts <add> assert_nothing_raised do <add> assert_broadcasts("test", 1) do <add> ActionCable.server.broadcast "test", "message" <add> end <add> end <add> end <add> <add> def test_assert_broadcasts_with_no_block <add> assert_nothing_raised do <add> ActionCable.server.broadcast "test", "message" <add> assert_broadcasts "test", 1 <add> end <add> <add> assert_nothing_raised do <add> ActionCable.server.broadcast "test", "message 2" <add> ActionCable.server.broadcast "test", "message 3" <add> assert_broadcasts "test", 3 <add> end <add> end <add> <add> def test_assert_no_broadcasts_with_no_block <add> assert_nothing_raised do <add> assert_no_broadcasts "test" <add> end <add> end <add> <add> def test_assert_no_broadcasts <add> assert_nothing_raised do <add> assert_no_broadcasts("test") do <add> ActionCable.server.broadcast "test2", "message" <add> end <add> end <add> end <add> <add> def test_assert_broadcasts_message_too_few_sent <add> ActionCable.server.broadcast "test", "hello" <add> error = assert_raises Minitest::Assertion do <add> assert_broadcasts("test", 2) do <add> ActionCable.server.broadcast "test", "world" <add> end <add> end <add> <add> assert_match(/2 .* but 1/, error.message) <add> end <add> <add> def test_assert_broadcasts_message_too_many_sent <add> error = assert_raises Minitest::Assertion do <add> assert_broadcasts("test", 1) do <add> ActionCable.server.broadcast "test", "hello" <add> ActionCable.server.broadcast "test", "world" <add> end <add> end <add> <add> assert_match(/1 .* but 2/, error.message) <add> end <add>end <add> <add>class TransmitedDataTest < ActionCable::TestCase <add> include ActionCable::TestHelper <add> <add> def test_assert_broadcast_on <add> assert_nothing_raised do <add> assert_broadcast_on("test", "message") do <add> ActionCable.server.broadcast "test", "message" <add> end <add> end <add> end <add> <add> def test_assert_broadcast_on_with_hash <add> assert_nothing_raised do <add> assert_broadcast_on("test", text: "hello") do <add> ActionCable.server.broadcast "test", text: "hello" <add> end <add> end <add> end <add> <add> def test_assert_broadcast_on_with_no_block <add> assert_nothing_raised do <add> ActionCable.server.broadcast "test", "hello" <add> assert_broadcast_on "test", "hello" <add> end <add> <add> assert_nothing_raised do <add> ActionCable.server.broadcast "test", "world" <add> assert_broadcast_on "test", "world" <add> end <add> end <add> <add> def test_assert_broadcast_on_message <add> ActionCable.server.broadcast "test", "hello" <add> error = assert_raises Minitest::Assertion do <add> assert_broadcast_on("test", "world") <add> end <add> <add> assert_match(/No messages sent/, error.message) <add> end <add>end
5
Python
Python
fix redundant callbacks issue
0856266613bec67dc17b220136c3ccc079d68131
<ide><path>keras/callbacks.py <ide> <ide> class CallbackList(object): <ide> <del> def __init__(self, callbacks, queue_length=10): <del> self.callbacks = callbacks <add> def __init__(self, callbacks=[], queue_length=10): <add> self.callbacks = [c for c in callbacks] <ide> self.queue_length = queue_length <ide> <ide> def append(self, callback):
1