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
Java
Java
fix failing test
c01f45fa59db126e928affccad596eca45c8c202
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> package org.springframework.web.servlet.config.annotation; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> public HandlerMapping resourceHandlerMapping() { <ide> */ <ide> @Bean <ide> public ResourceUrlGenerator resourceUrlGenerator() { <del> SimpleUrlHandlerMapping hm = (SimpleUrlHandlerMapping) resourceHandlerMapping(); <del> return new ResourceUrlGenerator(hm.getUrlMap()); <add> Map<String, ?> handlerMap = Collections.<String, Object>emptyMap(); <add> if (resourceHandlerMapping() instanceof SimpleUrlHandlerMapping) { <add> handlerMap = ((SimpleUrlHandlerMapping) resourceHandlerMapping()).getUrlMap(); <add> } <add> return new ResourceUrlGenerator(handlerMap); <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlFilterTests.java <ide> package org.springframework.web.servlet.resource; <ide> <ide> import java.util.ArrayList; <del>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import javax.servlet.ServletException; <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> import org.junit.Test; <del>import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.mock.web.test.MockFilterChain; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; <ide> import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; <ide> import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; <del>import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> private void initFilterChain(Class<?> configClass) throws ServletException { <ide> @Configuration <ide> static class WebConfig extends WebMvcConfigurationSupport { <ide> <add> <ide> @Override <ide> public void addResourceHandlers(ResourceHandlerRegistry registry) { <ide> <ide> public void addResourceHandlers(ResourceHandlerRegistry registry) { <ide> .addResourceLocations("classpath:org/springframework/web/servlet/resource/test/") <ide> .setResourceResolvers(resourceResolvers); <ide> } <del> <del> @Bean <del> public ResourceUrlGenerator resourceUrlGenerator() { <del> ResourceUrlGenerator generator = new ResourceUrlGenerator(); <del> SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) resourceHandlerMapping(); <del> generator.setResourceHandlerMappings(Collections.singletonList(handlerMapping)); <del> return generator; <del> } <ide> } <ide> <ide> private static class TestServlet extends HttpServlet {
2
PHP
PHP
move method lower in class
d876eb34ff07ebd54fd48b0264135f795c0bad0c
<ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php <ide> public function transaction(callable $callback = null) <ide> : tap($transaction, $callback)->exec(); <ide> } <ide> <del> /** <del> * Execute a raw command. <del> * <del> * @param array $parameters <del> * @return mixed <del> */ <del> public function executeRaw(array $parameters) <del> { <del> return $this->command('rawCommand', $parameters); <del> } <del> <ide> /** <ide> * Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself. <ide> * <ide> public function createSubscription($channels, Closure $callback, $method = 'subs <ide> // <ide> } <ide> <add> /** <add> * Execute a raw command. <add> * <add> * @param array $parameters <add> * @return mixed <add> */ <add> public function executeRaw(array $parameters) <add> { <add> return $this->command('rawCommand', $parameters); <add> } <add> <ide> /** <ide> * Disconnects from the Redis instance. <ide> *
1
Ruby
Ruby
make homebrew_brew_file a pathname object
12a452557d7695dba69f488a95a77a2650d28251
<ide><path>Library/Homebrew/config.rb <ide> def mkpath <ide> # Where brews installed via URL are cached <ide> HOMEBREW_CACHE_FORMULA = HOMEBREW_CACHE+"Formula" <ide> <del>HOMEBREW_BREW_FILE = ENV["HOMEBREW_BREW_FILE"] <del>unless HOMEBREW_BREW_FILE <add>if ENV["HOMEBREW_BREW_FILE"] <add> HOMEBREW_BREW_FILE = Pathname.new(ENV["HOMEBREW_BREW_FILE"]) <add>else <ide> odie "HOMEBREW_BREW_FILE was not exported! Please call bin/brew directly!" <ide> end <ide> <ide><path>Library/Homebrew/extend/fileutils.rb <ide> def mktemp(prefix = name) <ide> # Reference from `man 2 open` <ide> # > When a new file is created, it is given the group of the directory which <ide> # contains it. <del> group_id = if File.grpowned? HOMEBREW_BREW_FILE <del> File.stat(HOMEBREW_BREW_FILE).gid <add> group_id = if HOMEBREW_BREW_FILE.grpowned? <add> HOMEBREW_BREW_FILE.stat.gid <ide> else <ide> Process.gid <ide> end <ide><path>Library/Homebrew/formula.rb <ide> def skip_clean?(path) <ide> # @private <ide> def link_overwrite?(path) <ide> # Don't overwrite files not created by Homebrew. <del> return false unless path.stat.uid == File.stat(HOMEBREW_BREW_FILE).uid <add> return false unless path.stat.uid == HOMEBREW_BREW_FILE.stat.uid <ide> # Don't overwrite files belong to other keg except when that <ide> # keg's formula is deleted. <ide> begin <ide><path>Library/Homebrew/test/lib/config.rb <ide> require "tmpdir" <ide> require "pathname" <ide> <del>HOMEBREW_BREW_FILE = ENV["HOMEBREW_BREW_FILE"] <add>HOMEBREW_BREW_FILE = Pathname.new(ENV["HOMEBREW_BREW_FILE"]) <ide> HOMEBREW_TEMP = Pathname.new(ENV["HOMEBREW_TEMP"] || Dir.tmpdir) <ide> <ide> TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") { |k| <ide><path>Library/brew.rb <ide> def require?(path) <ide> end <ide> <ide> if possible_tap && !possible_tap.installed? <del> brew_uid = File.stat(HOMEBREW_BREW_FILE).uid <add> brew_uid = HOMEBREW_BREW_FILE.stat.uid <ide> tap_commands = [] <ide> if Process.uid.zero? && !brew_uid.zero? <ide> tap_commands += %W[/usr/bin/sudo -u ##{brew_uid}]
5
PHP
PHP
add accessor method for view properties
c1a1a209af378c8b9e8ce380656b7090d61a7297
<ide><path>src/Controller/Controller.php <ide> public function __get($name) <ide> { <ide> if (in_array($name, ['layout', 'view', 'theme', 'autoLayout', 'viewPath', 'layoutPath'], true)) { <ide> trigger_error( <del> sprintf('Controller::$%s is deprecated. Use $this->getView()->%s instead.', $name, $name), <add> sprintf('Controller::$%s is deprecated. Use $this->getView()->%s() instead.', $name, $name), <ide> E_USER_DEPRECATED <ide> ); <del> return $this->getView()->{$name}; <add> return $this->getView()->{$name}(); <ide> } <ide> <ide> list($plugin, $class) = pluginSplit($this->modelClass, true); <ide> public function __set($name, $value) <ide> { <ide> if (in_array($name, ['layout', 'view', 'theme', 'autoLayout', 'viewPath', 'layoutPath'], true)) { <ide> trigger_error( <del> sprintf('Controller::$%s is deprecated. Use $this->getView()->%s instead.', $name, $name), <add> sprintf('Controller::$%s is deprecated. Use $this->getView()->%s() instead.', $name, $name), <ide> E_USER_DEPRECATED <ide> ); <del> $this->getView()->{$name} = $value; <add> $this->getView()->{$name}($value); <ide> return; <ide> } <ide> <ide> public function render($view = null, $layout = null) <ide> $this->_viewPath(); <ide> } <ide> } <add> <ide> $this->autoRender = false; <del> if ($this->_view->view === null) { <del> $this->_view->view = isset($this->request->params['action']) ? $this->request->params['action'] : null; <add> if ($this->_view->view() === null && <add> isset($this->request->params['action']) <add> ) { <add> $this->_view->view($this->request->params['action']); <ide> } <ide> <ide> $this->response->body($this->_view->render($view, $layout)); <ide><path>src/View/Cell.php <ide> public function render($template = null) <ide> } <ide> $this->_view = null; <ide> $this->View = $this->getView(); <del> $this->_view->layout = false; <add> $this->_view->layout(false); <ide> <ide> $cache = []; <ide> if ($this->_cache) { <ide><path>src/View/View.php <ide> public function autoLayout(bool $autoLayout = null) <ide> $this->layoutPath = $autoLayout; <ide> } <ide> <add> /** <add> * The view theme to use. <add> * <add> * @param string $theme Theme name. If null returns current theme. <add> * @return string|void <add> */ <add> public function theme($theme = null) <add> { <add> if ($theme === null) { <add> return $this->theme; <add> } <add> <add> $this->theme = $theme; <add> } <add> <add> /** <add> * Get/set the name of the view file to render. The name specified is the <add> * filename in /app/Template/<SubFolder> without the .ctp extension. <add> * <add> * @param string $name View file name to set. If null returns current name. <add> * @return string|void <add> */ <add> public function view($name = null) <add> { <add> if ($name === null) { <add> return $this->view; <add> } <add> <add> $this->view = $name; <add> } <add> <add> /** <add> * Get/set the name of the layout file to render the view inside of. <add> * The name specified is the filename of the layout in /app/Template/Layout <add> * without the .ctp extension. <add> * <add> * @param string $name Layout file name to set. If null returns current name. <add> * @return string|void <add> */ <add> public function layout($name = null) <add> { <add> if ($name === null) { <add> return $this->layout; <add> } <add> <add> $this->layout = $name; <add> } <add> <ide> /** <ide> * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string. <ide> *
3
Javascript
Javascript
fix responsive issue when the chart is recreated
3fe198c86098ae50d5d5e9b74d111d5f8fa74bf0
<ide><path>src/platforms/platform.dom.js <ide> function watchForRender(node, handler) { <ide> addEventListener(node, type, proxy); <ide> }); <ide> <add> // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class <add> // is removed then added back immediately (same animation frame?). Accessing the <add> // `offsetParent` property will force a reflow and re-evaluate the CSS animation. <add> // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics <add> // https://github.com/chartjs/Chart.js/issues/4737 <add> expando.reflow = !!node.offsetParent; <add> <ide> node.classList.add(CSS_RENDER_MONITOR); <ide> } <ide> <ide><path>test/jasmine.utils.js <ide> function acquireChart(config, options) { <ide> wrapper.appendChild(canvas); <ide> window.document.body.appendChild(wrapper); <ide> <del> chart = new Chart(canvas.getContext('2d'), config); <add> try { <add> chart = new Chart(canvas.getContext('2d'), config); <add> } catch (e) { <add> window.document.body.removeChild(wrapper); <add> throw e; <add> } <add> <ide> chart.$test = { <ide> persistent: options.persistent, <ide> wrapper: wrapper <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> }); <ide> }); <ide> }); <add> <add> // https://github.com/chartjs/Chart.js/issues/4737 <add> it('should resize the canvas when re-creating the chart', function(done) { <add> var chart = acquireChart({ <add> options: { <add> responsive: true <add> } <add> }, { <add> wrapper: { <add> style: 'width: 320px' <add> } <add> }); <add> <add> waitForResize(chart, function() { <add> var canvas = chart.canvas; <add> expect(chart).toBeChartOfSize({ <add> dw: 320, dh: 320, <add> rw: 320, rh: 320, <add> }); <add> <add> chart.destroy(); <add> chart = new Chart(canvas, { <add> type: 'line', <add> options: { <add> responsive: true <add> } <add> }); <add> <add> canvas.parentNode.style.width = '455px'; <add> waitForResize(chart, function() { <add> expect(chart).toBeChartOfSize({ <add> dw: 455, dh: 455, <add> rw: 455, rh: 455, <add> }); <add> <add> done(); <add> }); <add> }); <add> }); <ide> }); <ide> <ide> describe('config.options.responsive: true (maintainAspectRatio: true)', function() { <ide> describe('Chart', function() { <ide> }); <ide> }); <ide> <del> describe('config.options.devicePixelRatio 3', function() { <add> describe('config.options.devicePixelRatio', function() { <ide> beforeEach(function() { <ide> this.devicePixelRatio = window.devicePixelRatio; <ide> window.devicePixelRatio = 1;
3
PHP
PHP
extract duplicate code into a helper
4cafa1e36a28d8c88f041e04eb4ece2e0e86376a
<ide><path>src/Network/Response.php <ide> public function cors(Request $request, $allowedDomains = [], $allowedMethods = [ <ide> */ <ide> public function file($path, array $options = []) <ide> { <add> $file = $this->validateFile($path); <ide> $options += [ <ide> 'name' => null, <ide> 'download' => null <ide> ]; <ide> <del> if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) { <del> throw new NotFoundException('The requested file contains `..` and will not be read.'); <del> } <del> <del> if (!is_file($path)) { <del> $path = APP . $path; <del> } <del> <del> $file = new File($path); <del> if (!$file->exists() || !$file->readable()) { <del> if (Configure::read('debug')) { <del> throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path)); <del> } <del> throw new NotFoundException(__d('cake', 'The requested file was not found')); <del> } <del> <ide> $extension = strtolower($file->ext()); <ide> $download = $options['download']; <ide> if ((!$extension || $this->type($extension) === false) && $download === null) { <ide> public function file($path, array $options = []) <ide> <ide> public function withFile($path, array $options = []) <ide> { <del> // TODO move validation into a helper method. <del> if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) { <del> throw new NotFoundException('The requested file contains `..` and will not be read.'); <del> } <del> if (!is_file($path)) { <del> $path = APP . $path; <del> } <del> <del> $file = new File($path); <del> if (!$file->exists() || !$file->readable()) { <del> if (Configure::read('debug')) { <del> throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path)); <del> } <del> throw new NotFoundException(__d('cake', 'The requested file was not found')); <del> } <del> // end refactor. <add> $file = $this->validateFile($path); <ide> <ide> $options += [ <ide> 'name' => null, <ide> public function withFile($path, array $options = []) <ide> return $new; <ide> } <ide> <add> /** <add> * Validate a file path is a valid response body. <add> * <add> * @param string $path The path to the file. <add> * @throws \Cake\Network\Exception\NotFoundException <add> * @return \Cake\Filesystem\File <add> */ <add> protected function validateFile($path) <add> { <add> if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) { <add> throw new NotFoundException('The requested file contains `..` and will not be read.'); <add> } <add> if (!is_file($path)) { <add> $path = APP . $path; <add> } <add> <add> $file = new File($path); <add> if (!$file->exists() || !$file->readable()) { <add> if (Configure::read('debug')) { <add> throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path)); <add> } <add> throw new NotFoundException(__d('cake', 'The requested file was not found')); <add> } <add> <add> return $file; <add> } <add> <ide> /** <ide> * Get the current file if one exists. <ide> *
1
Ruby
Ruby
add test for root
8e48a5ef0ca488b2264acd2b38bdae14970c011f
<ide><path>actionpack/test/dispatch/routing_test.rb <ide> def self.matches?(request) <ide> scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do <ide> resources :rooms <ide> end <add> <add> root :to => 'projects#index' <ide> end <ide> end <ide> <ide> def test_access_token_rooms <ide> end <ide> end <ide> <add> def test_root <add> with_test_routes do <add> get '/' <add> assert_equal 'projects#index', @response.body <add> end <add> end <add> <ide> private <ide> def with_test_routes <ide> real_routes, temp_routes = ActionController::Routing::Routes, Routes
1
PHP
PHP
remove use of file in shell and extracttask
3fbf46e521f432431da3ead73b08e5ae9b75bb09
<ide><path>src/Console/Shell.php <ide> use Cake\Console\Exception\ConsoleException; <ide> use Cake\Console\Exception\StopException; <ide> use Cake\Core\App; <add>use Cake\Core\Exception\Exception; <ide> use Cake\Datasource\ModelAwareTrait; <del>use Cake\Filesystem\File; <add>use Cake\Filesystem\Filesystem; <ide> use Cake\Log\LogTrait; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <ide> use Cake\ORM\Locator\LocatorInterface; <ide> public function createFile(string $path, string $contents): bool <ide> $this->out(sprintf('Creating file %s', $path)); <ide> } <ide> <del> $File = new File($path, true); <del> <ide> try { <del> if ($File->exists() && $File->writable()) { <del> $File->write($contents); <del> $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path)); <del> <del> return true; <del> } <add> $fs = new Filesystem(); <add> $fs->dumpFile($path, $contents); <ide> <add> $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path)); <add> } catch (Exception $e) { <ide> $this->_io->err(sprintf('<error>Could not write to `%s`</error>.', $path), 2); <ide> <ide> return false; <del> } finally { <del> $File->close(); <ide> } <add> <add> return true; <ide> } <ide> <ide> /** <ide><path>src/Filesystem/Filesystem.php <ide> <ide> namespace Cake\Filesystem; <ide> <add>use Cake\Core\Exception\Exception; <ide> use CallbackFilterIterator; <ide> use FilesystemIterator; <ide> use RecursiveCallbackFilterIterator; <ide> function (SplFileInfo $current) { <ide> <ide> return new CallbackFilterIterator($flatten, $filter); <ide> } <add> <add> public function dumpFile(string $filename, string $content) <add> { <add> $dir = dirname($filename); <add> if (!is_dir($dir)) { <add> $this->mkdir($dir); <add> } <add> <add> // @codingStandardsIgnoreStart <add> $tmpFile = @tempnam($dir, basename($filename)); <add> if ($tmpFile === false || @file_put_contents($tmpFile, $content) === false) { <add> throw new Exception(sprintf('Failed to write file "%s"', $filename)); <add> } <add> <add> @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); <add> <add> if (@rename($tmpFile, $filename) === false) { <add> throw new Exception(sprintf('Failed to write file "%s"', $filename)); <add> } <add> // @codingStandardsIgnoreEnd <add> } <add> <add> public function mkdir(string $dir, int $mode = 0755): void <add> { <add> if (is_dir($dir)) { <add> return; <add> } <add> <add> $old = umask(0); <add> // @codingStandardsIgnoreLine <add> if (@mkdir($dir, $mode, true) === false) { <add> umask($old); <add> throw new Exception(sprintf('Failed to create directory "%s"', $dir)); <add> } <add> <add> umask($old); <add> } <ide> } <ide><path>src/Shell/Task/ExtractTask.php <ide> use Cake\Core\App; <ide> use Cake\Core\Exception\MissingPluginException; <ide> use Cake\Core\Plugin; <del>use Cake\Filesystem\File; <ide> use Cake\Filesystem\Filesystem; <ide> use Cake\Utility\Inflector; <ide> <ide> protected function _writeFiles(): void <ide> } <ide> <ide> $filename = str_replace('/', '_', $domain) . '.pot'; <del> $File = new File($this->_output . $filename); <ide> $response = ''; <del> while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') { <add> while ($overwriteAll === false <add> && file_exists($this->_output . $filename) <add> && strtoupper($response) !== 'Y' <add> ) { <ide> $this->out(); <ide> $response = $this->in( <ide> sprintf('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), <ide> protected function _writeFiles(): void <ide> $response = ''; <ide> while (!$response) { <ide> $response = $this->in('What would you like to name this file?', null, 'new_' . $filename); <del> $File = new File($this->_output . $response); <ide> $filename = $response; <ide> } <ide> } elseif (strtoupper($response) === 'A') { <ide> $overwriteAll = true; <ide> } <ide> } <del> $File->write($output); <del> $File->close(); <add> $fs = new Filesystem(); <add> $fs->dumpFile($this->_output . $filename, $output); <ide> } <ide> } <ide>
3
Javascript
Javascript
use duration object in relativetime
af40f1dc864279850f503d4cee24c846f4b9d21b
<ide><path>moment.js <ide> <ide> // default relative time thresholds <ide> relativeTimeThresholds = { <del> s: 45, //seconds to minutes <del> m: 45, //minutes to hours <del> h: 22, //hours to days <del> dd: 25, //days to month (month == 1) <del> dm: 45, //days to months (months > 1) <del> dy: 345 //days to year <add> s: 45, // seconds to minute <add> m: 45, // minutes to hour <add> h: 22, // hours to day <add> d: 26, // days to month <add> M: 11 // months to year <ide> }, <ide> <ide> // tokens to ordinalize and pad <ide> y : "a year", <ide> yy : "%d years" <ide> }, <add> <ide> relativeTime : function (number, withoutSuffix, string, isFuture) { <ide> var output = this._relativeTime[string]; <ide> return (typeof output === 'function') ? <ide> output(number, withoutSuffix, string, isFuture) : <ide> output.replace(/%d/i, number); <ide> }, <add> <ide> pastFuture : function (diff, output) { <ide> var format = this._relativeTime[diff > 0 ? 'future' : 'past']; <ide> return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); <ide> return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); <ide> } <ide> <del> function relativeTime(milliseconds, withoutSuffix, lang) { <del> var seconds = round(Math.abs(milliseconds) / 1000), <del> minutes = round(seconds / 60), <del> hours = round(minutes / 60), <del> days = round(hours / 24), <del> years = round(days / 365), <del> args = seconds < relativeTimeThresholds.s && ['s', seconds] || <add> function relativeTime(msOrDuration, withoutSuffix, lang) { <add> var duration = (typeof msOrDuration === "number" ? <add> moment.duration(Math.abs(msOrDuration)) : <add> moment.duration(msOrDuration).abs()), <add> seconds = round(duration.as('s')), <add> minutes = round(duration.as('m')), <add> hours = round(duration.as('h')), <add> days = round(duration.as('d')), <add> months = round(duration.as('M')), <add> years = round(duration.as('y')), <add> <add> args = seconds < relativeTimeThresholds.s && ['s', seconds] || <ide> minutes === 1 && ['m'] || <ide> minutes < relativeTimeThresholds.m && ['mm', minutes] || <ide> hours === 1 && ['h'] || <ide> hours < relativeTimeThresholds.h && ['hh', hours] || <ide> days === 1 && ['d'] || <del> days <= relativeTimeThresholds.dd && ['dd', days] || <del> days <= relativeTimeThresholds.dm && ['M'] || <del> days < relativeTimeThresholds.dy && ['MM', round(days / 30)] || <add> days < relativeTimeThresholds.d && ['dd', days] || <add> months === 1 && ['M'] || <add> months < relativeTimeThresholds.M && ['MM', months] || <ide> years === 1 && ['y'] || ['yy', years]; <add> <ide> args[2] = withoutSuffix; <del> args[3] = milliseconds > 0; <add> args[3] = +msOrDuration > 0; <ide> args[4] = lang; <ide> return substituteTimeAgo.apply({}, args); <ide> } <ide> }, <ide> <ide> from : function (time, withoutSuffix) { <del> return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); <add> return moment.duration({to: this, from: time}).lang(this.lang()._abbr).humanize(!withoutSuffix); <ide> }, <ide> <ide> fromNow : function (withoutSuffix) { <ide> ************************************/ <ide> <ide> <add> function daysToYears (days) { <add> // 400 years have 146097 days (taking into account leap year rules) <add> return days * 400 / 146097; <add> } <add> <add> function yearsToDays (years) { <add> // years * 365 + absRound(years / 4) - <add> // absRound(years / 100) + absRound(years / 400); <add> return years * 146097 / 400; <add> } <add> <ide> extend(moment.duration.fn = Duration.prototype, { <ide> <ide> _bubble : function () { <ide> days += absRound(hours / 24); <ide> <ide> // Accurately convert days to years, assume start from year 0. <del> years = absRound(days * 400 / 146097); <del> days -= years * 365 + absRound(years / 4) - <del> absRound(years / 100) + absRound(years / 400); <add> years = absRound(daysToYears(days)); <add> days -= absRound(yearsToDays(years)); <ide> <ide> // 30 days to a month <ide> // TODO (iskren): Use anchor date (like 1st Jan) to compute this. <ide> data.years = years; <ide> }, <ide> <add> abs : function () { <add> this._milliseconds = Math.abs(this._milliseconds); <add> this._days = Math.abs(this._days); <add> this._months = Math.abs(this._months); <add> <add> this._data.milliseconds = Math.abs(this._data.milliseconds); <add> this._data.seconds = Math.abs(this._data.seconds); <add> this._data.minutes = Math.abs(this._data.minutes); <add> this._data.hours = Math.abs(this._data.hours); <add> this._data.months = Math.abs(this._data.months); <add> this._data.years = Math.abs(this._data.years); <add> <add> return this; <add> }, <add> <ide> weeks : function () { <ide> return absRound(this.days() / 7); <ide> }, <ide> }, <ide> <ide> humanize : function (withSuffix) { <del> var difference = +this, <del> output = relativeTime(difference, !withSuffix, this.lang()); <add> var output = relativeTime(this, !withSuffix, this.lang()); <ide> <ide> if (withSuffix) { <del> output = this.lang().pastFuture(difference, output); <add> output = this.lang().pastFuture(+this, output); <ide> } <ide> <ide> return this.lang().postformat(output); <ide> }, <ide> <ide> as : function (units) { <add> var days, months; <ide> units = normalizeUnits(units); <del> return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); <add> <add> days = this._days + this._milliseconds / 864e5; <add> if (units === 'month' || units === 'year') { <add> months = this._months + daysToYears(days) * 12; <add> return units === 'month' ? months : months / 12; <add> } else { <add> days += yearsToDays(this._months / 12); <add> switch (units) { <add> case 'week': return days / 7; <add> case 'day': return days; <add> case 'hour': return days * 24; <add> case 'minute': return days * 24 * 60; <add> case 'second': return days * 24 * 60 * 60; <add> case 'millisecond': return days * 24 * 60 * 60 * 1000; <add> default: throw new Error("Unknown unit " + units); <add> } <add> } <ide> }, <ide> <ide> lang : moment.fn.lang, <ide> }; <ide> } <ide> <del> function makeDurationAsGetter(name, factor) { <del> moment.duration.fn['as' + name] = function () { <del> return +this / factor; <del> }; <del> } <del> <ide> for (i in unitMillisecondFactors) { <ide> if (unitMillisecondFactors.hasOwnProperty(i)) { <del> makeDurationAsGetter(i, unitMillisecondFactors[i]); <ide> makeDurationGetter(i.toLowerCase()); <ide> } <ide> } <ide> <del> makeDurationAsGetter('Weeks', 6048e5); <del> moment.duration.fn.asMonths = function () { <del> return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; <del> }; <del> <add> moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; <add> moment.duration.fn.asSeconds = function () { return this.as('s'); }; <add> moment.duration.fn.asMinutes = function () { return this.as('m'); }; <add> moment.duration.fn.asHours = function () { return this.as('h'); }; <add> moment.duration.fn.asDays = function () { return this.as('d'); }; <add> moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; <add> moment.duration.fn.asMonths = function () { return this.as('M'); }; <add> moment.duration.fn.asYears = function () { return this.as('Y'); }; <ide> <ide> /************************************ <ide> Default Lang <ide><path>test/moment/duration.js <ide> exports.duration = { <ide> test.equal(moment.duration({days: 25}).humanize(), "25 days", "25 days = 25 days"); <ide> test.equal(moment.duration({days: 26}).humanize(), "a month", "26 days = a month"); <ide> test.equal(moment.duration({days: 30}).humanize(), "a month", "30 days = a month"); <del> test.equal(moment.duration({days: 45}).humanize(), "a month", "45 days = a month"); <add> test.equal(moment.duration({days: 45}).humanize(), "2 months", "45 days = 2 months"); <ide> test.equal(moment.duration({days: 46}).humanize(), "2 months", "46 days = 2 months"); <ide> test.equal(moment.duration({days: 74}).humanize(), "2 months", "75 days = 2 months"); <ide> test.equal(moment.duration({days: 76}).humanize(), "3 months", "76 days = 3 months"); <ide> test.equal(moment.duration({months: 1}).humanize(), "a month", "1 month = a month"); <ide> test.equal(moment.duration({months: 5}).humanize(), "5 months", "5 months = 5 months"); <del> test.equal(moment.duration({days: 344}).humanize(), "11 months", "344 days = 11 months"); <add> test.equal(moment.duration({days: 344}).humanize(), "a year", "344 days = a year"); <ide> test.equal(moment.duration({days: 345}).humanize(), "a year", "345 days = a year"); <ide> test.equal(moment.duration({days: 547}).humanize(), "a year", "547 days = a year"); <ide> test.equal(moment.duration({days: 548}).humanize(), "2 years", "548 days = 2 years"); <ide><path>test/moment/lang.js <ide> exports.lang = { <ide> test.done(); <ide> }, <ide> <add> "from relative time future" : function (test) { <add> var start = moment([2007, 1, 28]); <add> <add> test.equal(start.from(moment([2007, 1, 28]).subtract({s: 44})), "in a few seconds", "44 seconds = a few seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({s: 45})), "in a minute", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({s: 89})), "in a minute", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({s: 90})), "in 2 minutes", "90 seconds = 2 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({m: 44})), "in 44 minutes", "44 minutes = 44 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({m: 45})), "in an hour", "45 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({m: 89})), "in an hour", "89 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({m: 90})), "in 2 hours", "90 minutes = 2 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({h: 5})), "in 5 hours", "5 hours = 5 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({h: 21})), "in 21 hours", "21 hours = 21 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({h: 22})), "in a day", "22 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({h: 35})), "in a day", "35 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({h: 36})), "in 2 days", "36 hours = 2 days"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 1})), "in a day", "1 day = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 5})), "in 5 days", "5 days = 5 days"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 25})), "in 25 days", "25 days = 25 days"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 26})), "in a month", "26 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 30})), "in a month", "30 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 45})), "in a month", "45 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 46})), "in 2 months", "46 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 74})), "in 2 months", "75 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 76})), "in 3 months", "76 days = 3 months"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({M: 1})), "in a month", "1 month = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({M: 5})), "in 5 months", "5 months = 5 months"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 344})), "in 11 months", "344 days = 11 months"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 345})), "in a year", "345 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 547})), "in a year", "547 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({d: 548})), "in a year", "548 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({y: 1})), "in a year", "1 year = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).subtract({y: 5})), "in 5 years", "5 years = 5 years"); <add> <add> test.done(); <add> }, <add> <add> "from relative time past" : function (test) { <add> var start = moment([2007, 1, 28]); <add> <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 44})), "a few seconds ago", "44 seconds = a few seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 45})), "a minute ago", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 89})), "a minute ago", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 90})), "2 minutes ago", "90 seconds = 2 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 44})), "44 minutes ago", "44 minutes = 44 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 45})), "an hour ago", "45 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 89})), "an hour ago", "89 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 90})), "2 hours ago", "90 minutes = 2 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 5})), "5 hours ago", "5 hours = 5 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 21})), "21 hours ago", "21 hours = 21 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 22})), "a day ago", "22 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 35})), "a day ago", "35 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 36})), "2 days ago", "36 hours = 2 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 1})), "a day ago", "1 day = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 5})), "5 days ago", "5 days = 5 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 25})), "25 days ago", "25 days = 25 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 26})), "a month ago", "26 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 30})), "a month ago", "30 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 45})), "2 months ago", "45 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 46})), "2 months ago", "46 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 74})), "2 months ago", "75 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 76})), "3 months ago", "76 days = 3 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 1})), "a month ago", "1 month = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 5})), "5 months ago", "5 months = 5 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 344})), "11 months ago", "344 days = 11 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 345})), "a year ago", "345 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 547})), "a year ago", "547 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 548})), "a year ago", "548 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 1})), "a year ago", "1 year = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 5})), "5 years ago", "5 years = 5 years"); <add> <add> test.done(); <add> }, <add> <ide> "instance lang used with from" : function (test) { <ide> test.expect(2); <ide> moment.lang('en');
3
Ruby
Ruby
make sure duplicates are remove from `path`
e70f2ec33233422b70db047338aa85d9e2088042
<ide><path>Library/Homebrew/PATH.rb <ide> def initialize(*paths) <ide> end <ide> <ide> def prepend(*paths) <del> @paths.unshift(*parse(*paths)) <add> @paths = parse(*paths, *@paths) <ide> self <ide> end <ide> <ide> def append(*paths) <del> @paths.concat(parse(*paths)) <add> @paths = parse(*@paths, *paths) <ide> self <ide> end <ide> <ide><path>Library/Homebrew/test/PATH_spec.rb <ide> it "splits an existing PATH" do <ide> expect(described_class.new("/path1:/path2")).to eq(["/path1", "/path2"]) <ide> end <add> <add> it "removes duplicates" do <add> expect(described_class.new("/path1", "/path1")).to eq("/path1") <add> end <ide> end <ide> <ide> describe "#to_ary" do <ide> it "prepends a path to a PATH" do <ide> expect(described_class.new("/path1").prepend("/path2").to_str).to eq("/path2:/path1") <ide> end <add> <add> it "removes duplicates" do <add> expect(described_class.new("/path1").prepend("/path1").to_str).to eq("/path1") <add> end <ide> end <ide> <ide> describe "#append" do <ide> it "prepends a path to a PATH" do <ide> expect(described_class.new("/path1").append("/path2").to_str).to eq("/path1:/path2") <ide> end <add> <add> it "removes duplicates" do <add> expect(described_class.new("/path1").append("/path1").to_str).to eq("/path1") <add> end <ide> end <ide> <ide> describe "#validate" do
2
Python
Python
restore data test
322def29f7d88e67ee9bdcb715c58a3b2801fab4
<ide><path>official/recommendation/data_test.py <ide> def _test_fresh_randomness(self, constructor_type): <ide> <ide> self.assertLess(deviation, 0.2) <ide> <del> # def test_end_to_end_materialized(self): <del> # self._test_end_to_end("materialized") <del> # <del> # def test_end_to_end_bisection(self): <del> # self._test_end_to_end("bisection") <add> def test_end_to_end_materialized(self): <add> self._test_end_to_end("materialized") <ide> <del> # def test_fresh_randomness_materialized(self): <del> # self._test_fresh_randomness("materialized") <del> # <del> # def test_fresh_randomness_bisection(self): <del> # self._test_fresh_randomness("bisection") <add> def test_end_to_end_bisection(self): <add> self._test_end_to_end("bisection") <add> <add> def test_fresh_randomness_materialized(self): <add> self._test_fresh_randomness("materialized") <add> <add> def test_fresh_randomness_bisection(self): <add> self._test_fresh_randomness("bisection") <ide> <ide> <ide> if __name__ == "__main__": <ide> tf.logging.set_verbosity(tf.logging.INFO) <del> # tf.test.main() <add> tf.test.main()
1
Text
Text
remove cluster.setupmaster() myth
779091ffdb5ea6d93e81f8dd732699fb8836bb0b
<ide><path>doc/api/cluster.md <ide> values are `"rr"` and `"none"`. <ide> After calling `.setupMaster()` (or `.fork()`) this settings object will contain <ide> the settings, including the default values. <ide> <del>It is effectively frozen after being set, because `.setupMaster()` can <del>only be called once. <del> <ide> This object is not supposed to be changed or set manually, by you. <ide> <ide> ## cluster.setupMaster([settings])
1
Text
Text
fix merge conflict
e2047576c483a419f02ac0a2a5e77cd52c075699
<ide><path>website/docs/api/cli.md <ide> All output files generated by this command are compatible with <ide> | `conll`, `conllu`, `conllubio` | Universal Dependencies `.conllu` or `.conll` format. | <ide> | `ner` | NER with IOB/IOB2 tags, one token per line with columns separated by whitespace. The first column is the token and the final column is the IOB tag. Sentences are separated by blank lines and documents are separated by the line `-DOCSTART- -X- O O`. Supports CoNLL 2003 NER format. See [sample data](https://github.com/explosion/spaCy/tree/master/examples/training/ner_example_data). | <ide> | `iob` | NER with IOB/IOB2 tags, one sentence per line with tokens separated by whitespace and annotation separated by `|`, either `word|B-ENT` or `word|POS|B-ENT`. See [sample data](https://github.com/explosion/spaCy/tree/master/examples/training/ner_example_data). | <del><<<<<<< HEAD <del> <ide> ## Debug data {#debug-data new="2.2"} <ide> <ide> Analyze, debug and validate your training and development data, get useful <ide> will not be available. <ide> ``` <ide> <ide> </Accordion> <del>======= <del>>>>>>>> master <ide> <ide> ## Train {#train} <ide>
1
Go
Go
delete the logging code
e7c0587d541cd9f224df622b2f97c918e68cfb05
<ide><path>pkg/tarsum/tarsum.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <del> <del> log "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> const ( <ide> func (ts *tarSum) Sum(extra []byte) string { <ide> h.Write(extra) <ide> } <ide> for _, fis := range ts.sums { <del> log.Debugf("-->%s<--", fis.Sum()) <ide> h.Write([]byte(fis.Sum())) <ide> } <ide> checksum := ts.Version().String() + "+" + ts.tHash.Name() + ":" + hex.EncodeToString(h.Sum(nil)) <del> log.Debugf("checksum processed: %s", checksum) <ide> return checksum <ide> } <ide>
1
Ruby
Ruby
add tests for interrupting transactions
9cdf93a05ca8c86913ee7fe430a3aac68795f5e8
<ide><path>activerecord/test/cases/adapters/postgresql/transaction_test.rb <ide> class Sample < ActiveRecord::Base <ide> end <ide> end <ide> <add> test "raises Interrupt when canceling statement via interrupt" do <add> start_time = Time.now <add> thread = Thread.new do <add> Sample.transaction do <add> Sample.connection.execute("SELECT pg_sleep(10)") <add> end <add> rescue Exception => e <add> e <add> end <add> <add> sleep(0.5) <add> thread.raise Interrupt <add> thread.join <add> duration = Time.now - start_time <add> <add> assert_instance_of Interrupt, thread.value <add> assert_operator duration, :<, 5 <add> end <add> <ide> private <ide> def with_warning_suppression <ide> log_level = ActiveRecord::Base.connection.client_min_messages
1
Python
Python
fix nightly runs
72eaaf6d55e0a9a35dfcdef91dd23661a26f5da0
<ide><path>.circleci/create_circleci_config.py <ide> def create_circleci_config(folder=None): <ide> <ide> if len(jobs) > 0: <ide> config = {"version": "2.1"} <del> config["parameters"] = {"tests_to_run": {"type": "string", "default": test_list}} <add> config["parameters"] = { <add> # Only used to accept the parameters from the trigger <add> "nightly": {"type": "boolean", "default": False}, <add> "tests_to_run": {"type": "string", "default": test_list}, <add> } <ide> config["jobs"] = {j.job_name: j.to_dict() for j in jobs} <ide> config["workflows"] = {"version": 2, "run_tests": {"jobs": [j.job_name for j in jobs]}} <ide> with open(os.path.join(folder, "generated_config.yml"), "w") as f:
1
Javascript
Javascript
improve hasher to always use 31bit ints
6e270ddb4c03a295499cc087ab6ea173f55e94fd
<ide><path>dist/Immutable.dev.js <ide> function hashValue(o) { <ide> var type = typeof o; <ide> if (type === 'number') { <ide> if ((o | 0) === o) { <del> return o % HASH_MAX_VAL; <add> return o & HASH_MAX_VAL; <ide> } <ide> o = '' + o; <ide> type = 'string'; <ide> function cachedHashString(string) { <ide> function hashString(string) { <ide> var hash = 0; <ide> for (var ii = 0; ii < string.length; ii++) { <del> hash = (31 * hash + string.charCodeAt(ii)) % HASH_MAX_VAL; <add> hash = (31 * hash + string.charCodeAt(ii)) & HASH_MAX_VAL; <ide> } <ide> return hash; <ide> } <del>var HASH_MAX_VAL = 0x100000000; <add>var HASH_MAX_VAL = 0x7FFFFFFF; <ide> var STRING_HASH_CACHE_MIN_STRLEN = 16; <ide> var STRING_HASH_CACHE_MAX_SIZE = 255; <ide> var STRING_HASH_CACHE_SIZE = 0; <ide><path>dist/Immutable.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <ide> function t(){function t(t,e,r,n){var i;if(n){var u=n.prototype;i=re.create(u)}else i=t.prototype;return re.keys(e).forEach(function(t){i[t]=e[t]}),re.keys(r).forEach(function(e){t[e]=r[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,r,n){return re.getPrototypeOf(e)[r].apply(t,n)}function r(t,r,n){e(t,r,"constructor",n)}function n(){return Object.create(se)}function i(t){var e=Object.create(oe);return e.__reversedIndices=t?t.__reversedIndices:!1,e}function u(t,e,r,n){var i=t.get?t.get(e[n],me):me;return i===me?r:++n===e.length?i:u(i,e,r,n)}function s(t,e,r){return(0===t||null!=r&&-r>=t)&&(null==e||null!=r&&e>=r)}function a(t,e){return 0>t?Math.max(0,e+t):e?Math.min(e,t):t}function h(t,e){return null==t?e:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function o(t){return t}function c(t,e){return[e,t]}function f(){return!0}function l(){return this}function _(t){return(t||0)+1}function v(t,e,r,n,i){var u=t.__makeSequence();return u.__iterateUncached=function(u,s,a){var h=0,o=t.__iterate(function(t,i,s){if(e.call(r,t,i,s)){if(u(t,n?i:h,s)===!1)return!1;h++}},s,a);return i?o:h},u}function g(t){return function(){return!t.apply(this,arguments)}}function p(t){return"string"==typeof t?JSON.stringify(t):t}function m(t,e){for(var r="";e;)1&e&&(r+=t),(e>>=1)&&(t+=t);return r}function d(t,e){return t>e?1:e>t?-1:0}function y(t){I(1/0!==t,"Cannot perform this action with an infinite sequence.")}function w(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof ie?t.equals(e):!1}function I(t,e){if(!t)throw Error(e)}function D(t,e,r){var n=t._rootData.updateIn(t._keyPath,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,n,t._rootData,r?i.concat(r):i),new le(n,t._keyPath,t._onChange)}function O(){}function b(t){for(var e=t.length,r=Array(e),n=0;e>n;n++)r[n]=t[n];return r}function M(t){return Ce.value=t,Ce}function k(t,e,r){var n=Object.create(we);return n.length=t,n._root=e,n.__ownerID=r,n}function S(t,e,r){var n=M(),i=x(t._root,t.__ownerID,0,L(e),e,r,n),u=t.length+(n.value?r===me?-1:1:0);return t.__ownerID?(t.length=u,t._root=i,t):i?i===t._root?t:k(u,i):de.empty() <del>}function x(t,e,r,n,i,u,s){return t?t.update(e,r,n,i,u,s):u===me?t:(s&&(s.value=!0),new Se(e,n,[i,u]))}function E(t){return t.constructor===Se||t.constructor===Me}function C(t,e,r,n,i){if(t.hash===n)return new Me(e,n,[t.entry,i]);var u,s=t.hash>>>r&pe,a=n>>>r&pe,h=s===a?[C(t,e,r+ve,n,i)]:(u=new Se(e,n,i),a>s?[t,u]:[u,t]);return new Ie(e,1<<s|1<<a,h)}function A(t,e,r,n){for(var i=0,u=0,s=Array(r),a=0,h=1,o=e.length;o>a;a++,h<<=1){var c=e[a];null!=c&&a!==n&&(i|=h,s[u++]=c)}return new Ie(t,i,s)}function q(t,e,r,n,i){for(var u=0,s=[],a=0;0!==r;a++,r>>>=1)1&r&&(s[a]=e[u++]);return s[n]=i,new Oe(t,u+1,s)}function j(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u&&n.push(Array.isArray(u)?ie(u).fromEntries():ie(u))}return U(t,e,n)}function P(t){return function(e,r){return e&&e.mergeDeepWith?e.mergeDeepWith(t,r):t?t(e,r):r}}function U(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){var i=t.get(n,me);t.set(n,i===me?r:e(i,r))}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)})}function z(t,e,r,n){var i=e[n],u=t.get?t.get(i,me):me;return u===me&&(u=de.empty()),I(t.set,"updateIn with invalid keyPath"),t.set(i,++n===e.length?r(u):z(u,e,r,n))}function R(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function W(t,e,r,n){var i=n?t:b(t);return i[e]=r,i}function J(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),s=0,a=0;i>a;a++)a===e?(u[a]=r,s=-1):u[a]=t[a+s];return u}function B(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,s=0;n>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function L(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t%Ae;t=""+t,e="string"}if("string"===e)return t.length>qe?V(t):K(t);if(t.hashCode&&"function"==typeof t.hashCode)return t.hashCode();throw Error("Unable to hash: "+t)}function V(t){var e=Ue[t];return null==e&&(e=K(t),Pe===je&&(Pe=0,Ue={}),Pe++,Ue[t]=e),e}function K(t){for(var e=0,r=0;t.length>r;r++)e=(31*e+t.charCodeAt(r))%Ae; <add>}function x(t,e,r,n,i,u,s){return t?t.update(e,r,n,i,u,s):u===me?t:(s&&(s.value=!0),new Se(e,n,[i,u]))}function E(t){return t.constructor===Se||t.constructor===Me}function C(t,e,r,n,i){if(t.hash===n)return new Me(e,n,[t.entry,i]);var u,s=t.hash>>>r&pe,a=n>>>r&pe,h=s===a?[C(t,e,r+ve,n,i)]:(u=new Se(e,n,i),a>s?[t,u]:[u,t]);return new Ie(e,1<<s|1<<a,h)}function A(t,e,r,n){for(var i=0,u=0,s=Array(r),a=0,h=1,o=e.length;o>a;a++,h<<=1){var c=e[a];null!=c&&a!==n&&(i|=h,s[u++]=c)}return new Ie(t,i,s)}function q(t,e,r,n,i){for(var u=0,s=[],a=0;0!==r;a++,r>>>=1)1&r&&(s[a]=e[u++]);return s[n]=i,new Oe(t,u+1,s)}function j(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u&&n.push(Array.isArray(u)?ie(u).fromEntries():ie(u))}return U(t,e,n)}function P(t){return function(e,r){return e&&e.mergeDeepWith?e.mergeDeepWith(t,r):t?t(e,r):r}}function U(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){var i=t.get(n,me);t.set(n,i===me?r:e(i,r))}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)})}function z(t,e,r,n){var i=e[n],u=t.get?t.get(i,me):me;return u===me&&(u=de.empty()),I(t.set,"updateIn with invalid keyPath"),t.set(i,++n===e.length?r(u):z(u,e,r,n))}function R(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function W(t,e,r,n){var i=n?t:b(t);return i[e]=r,i}function J(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),s=0,a=0;i>a;a++)a===e?(u[a]=r,s=-1):u[a]=t[a+s];return u}function B(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,s=0;n>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function L(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Ae;t=""+t,e="string"}if("string"===e)return t.length>qe?V(t):K(t);if(t.hashCode&&"function"==typeof t.hashCode)return t.hashCode();throw Error("Unable to hash: "+t)}function V(t){var e=Ue[t];return null==e&&(e=K(t),Pe===je&&(Pe=0,Ue={}),Pe++,Ue[t]=e),e}function K(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)&Ae; <ide> return e}function N(t,e,r,n,i,u){var s=Object.create(Be);return s.length=e-t,s._origin=t,s._size=e,s._level=r,s._root=n,s._tail=i,s.__ownerID=u,s}function F(t,e){if(e>=T(t._size))return t._tail;if(1<<t._level+ve>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&pe],n-=ve;return r}}function G(t,e,r){var n=t.__ownerID||new O,i=t._origin,u=t._size,s=i+e,a=null==r?u:0>r?u+r:i+r;if(s===i&&a===u)return t;if(s>=a)return t.clear();for(var h=t._level,o=t._root,c=0;0>s+c;)o=new Le(o.array.length?[,o]:[],n),h+=ve,c+=1<<h;c&&(s+=c,i+=c,a+=c,u+=c);for(var f=T(u),l=T(a);l>=1<<h+ve;)o=new Le(o.array.length?[o]:[],n),h+=ve;var _=t._tail,v=f>l?F(t,a-1):l>f?new Le([],n):_;if(l>f&&u>s&&_.array.length){o=o.ensureOwner(n);for(var g=o,p=h;p>ve;p-=ve){var m=f>>>p&pe;g=g.array[m]=g.array[m]?g.array[m].ensureOwner(n):new Le([],n)}g.array[f>>>ve&pe]=_}if(u>a&&(v=v.removeAfter(n,0,a)),s>=l)s-=l,a-=l,h=ve,o=Fe,v=v.removeBefore(n,0,s);else if(s>i||f>l){var d,y;c=0;do d=s>>>h&pe,y=l-1>>>h&pe,d===y&&(d&&(c+=(1<<h)*d),h-=ve,o=o&&o.array[d]);while(o&&d===y);o&&s>i&&(o=o.removeBefore(n,h,s-c)),o&&f>l&&(o=o.removeAfter(n,h,l-c)),c&&(s-=c,a-=c),o=o||Fe}return t.__ownerID?(t.length=a-s,t._origin=s,t._size=a,t._level=h,t._root=o,t._tail=v,t):N(s,a,h,o,v)}function H(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i];u&&n.push(u.forEach?u:ie(u))}var s=Math.max.apply(null,n.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),U(t,e,n)}function Q(t,e){return I(t>=0,"Index out of bounds"),t+e}function T(t){return ge>t?0:t-1>>>ve<<ve}function X(t,e){var r=Object.create(Qe);return r.length=t?t.length:0,r._map=t,r.__ownerID=e,r}function Y(t,e,r){var n=Object.create(Xe.prototype);return n.length=t?t.length:0,n._map=t,n._vector=e,n.__ownerID=r,n}function Z(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function $(t,e){return e?te(e,t,"",{"":t}):ee(t)}function te(t,e,r,n){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(n,r,ie(e).map(function(r,n){return te(t,r,n,e)})):e}function ee(t){if(t){if(Array.isArray(t))return ie(t).map(ee).toVector(); <ide> if(t.constructor===Object)return ie(t).map(ee).toMap()}return t}var re=Object,ne={};ne.createClass=t,ne.superCall=e,ne.defaultSuperCall=r;var ie=function(t){return ue.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},ue=ie;ne.createClass(ie,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+p(t)},toJS:function(){return this.map(function(t){return t instanceof ue?t.toJS():t}).__toJS()},toArray:function(){y(this.length);var t=Array(this.length||0);return this.values().forEach(function(e,r){t[r]=e}),t},toObject:function(){y(this.length);var t={};return this.forEach(function(e,r){t[r]=e}),t},toVector:function(){return y(this.length),We.from(this)},toMap:function(){return y(this.length),de.from(this)},toOrderedMap:function(){return y(this.length),Xe.from(this)},toSet:function(){return y(this.length),Ge.from(this)},equals:function(t){if(this===t)return!0;if(!(t instanceof ue))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entries().toArray(),r=0;return t.every(function(t,n){var i=e[r++];return w(n,i[0])&&w(t,i[1])})},join:function(t){t=t||",";var e="",r=!0;return this.forEach(function(n){r?(r=!1,e+=n):e+=t+n}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(f)),this.length)},countBy:function(t){var e=this;return Xe.empty().withMutations(function(r){e.forEach(function(e,n,i){r.update(t(e,n,i),_)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var r=[this].concat(t.map(function(t){return ue(t)})),n=this.__makeSequence();return n.length=r.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),n.__iterateUncached=function(t,e){for(var n,i=0,u=r.length-1,s=0;u>=s&&!n;s++){var a=r[e?u-s:s];i+=a.__iterate(function(e,r,i){return t(e,r,i)===!1?(n=!0,!1):void 0 <ide> },e)}return i},n},reverse:function(){var t=this,e=t.__makeSequence();return e.length=t.length,e.__iterateUncached=function(e,r){return t.__iterate(e,!r)},e.reverse=function(){return t},e},keys:function(){return this.flip().values()},values:function(){var t=this,e=i(t);return e.length=t.length,e.values=l,e.__iterateUncached=function(e,r,n){if(n&&null==this.length)return this.cacheResult().__iterate(e,r,n);var i,u=0;return n?(u=this.length-1,i=function(t,r,n){return e(t,u--,n)!==!1}):i=function(t,r,n){return e(t,u++,n)!==!1},t.__iterate(i,r),n?this.length:u},e},entries:function(){var t=this;if(t._cache)return ue(t._cache);var e=t.map(c).values();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,r){var n=e;return this.forEach(function(e,i,u){n=t.call(r,n,e,i,u)}),n},reduceRight:function(t,e,r){return this.reverse(!0).reduce(t,e,r)},every:function(t,e){var r=!0;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?void 0:(r=!1,!1)}),r},some:function(t,e){return!this.every(g(t),e)},first:function(){return this.find(f)},last:function(){return this.findLast(f)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,me)!==me},get:function(t,e){return this.find(function(e,r){return w(r,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?u(this,t,e,0):this},contains:function(t){return this.find(function(e){return w(e,t)},null,me)!==me},find:function(t,e,r){var n=r;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=r,!1):void 0}),n},findKey:function(t,e){var r;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLast:function(t,e,r){return this.reverse(!0).find(t,e,r)},findLastKey:function(t,e){return this.reverse(!0).findKey(t,e)},flip:function(){var t=this,e=n();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,r){return t.__iterate(function(t,r,n){return e(r,t,n)!==!1},r)},e},map:function(t,e){var r=this,n=r.__makeSequence(); <ide> return n.length=r.length,n.__iterateUncached=function(n,i){return r.__iterate(fu <ide> return r.length=e.length,r.__reversedIndices=!!(t^e.__reversedIndices),r.__iterateUncached=function(r,n,i){return e.__iterate(r,!n,i^t)},r.reverse=function(r){return t===r?e:oe.reverse.call(this,r)},r},values:function(){var t=ne.superCall(this,he.prototype,"values",[]);return t.length=void 0,t},filter:function(t,e,r){var n=v(this,t,e,r,r);return r&&(n.length=this.length),n},indexOf:function(t){return this.findIndex(function(e){return w(e,t)})},lastIndexOf:function(t){return this.reverse(!0).indexOf(t)},findIndex:function(t,e){var r=this.findKey(t,e);return null==r?-1:r},findLastIndex:function(t,e){return this.reverse(!0).findIndex(t,e)},slice:function(t,e,r){var n=this;if(s(t,e,n.length))return n;var i=n.__makeSequence(),u=a(t,n.length),o=h(e,n.length);return i.length=n.length&&(r?n.length:o-u),i.__reversedIndices=n.__reversedIndices,i.__iterateUncached=function(i,s,c){if(s)return this.cacheResult().__iterate(i,s,c);var f=this.__reversedIndices^c;if(u!==u||o!==o||f&&null==n.length){var l=n.count();u=a(t,l),o=h(e,l)}var _=f?n.length-o:u,v=f?n.length-u:o,g=n.__iterate(function(t,e,n){return f?null!=v&&e>=v||e>=_&&i(t,r?e:e-_,n)!==!1:_>e||(null==v||v>e)&&i(t,r?e:e-_,n)!==!1},s,c);return null!=this.length?this.length:r?g:Math.max(0,g-_)},i},splice:function(t,e){for(var r=[],n=2;arguments.length>n;n++)r[n-2]=arguments[n];return 0===e&&0===r.length?this:this.slice(0,t).concat(r,this.slice(t+e))},takeWhile:function(t,e,r){var n=this,i=n.__makeSequence();return i.__iterateUncached=function(u,s,a){if(s)return this.cacheResult().__iterate(u,s,a);var h=0,o=!0,c=n.__iterate(function(r,n,i){return t.call(e,r,n,i)&&u(r,n,i)!==!1?void(h=n):(o=!1,!1)},s,a);return r?i.length:o?c:h+1},r&&(i.length=this.length),i},skipWhile:function(t,e,r){var n=this,i=n.__makeSequence();return r&&(i.length=this.length),i.__iterateUncached=function(i,u,s){if(u)return this.cacheResult().__iterate(i,u,s);var a=n.__reversedIndices^s,h=!0,o=0,c=n.__iterate(function(n,u,a){return h&&(h=t.call(e,n,u,a),h||(o=u)),h||i(n,s||r?u:u-o,a)!==!1},u,s);return r?c:a?o+1:c-o <ide> },i},groupBy:function(t,e,r){var n=this,i=Xe.empty().withMutations(function(e){n.forEach(function(i,u,s){var a=t(i,u,s),h=e.get(a,me);h===me&&(h=Array(r?n.length:0),e.set(a,h)),r?h[u]=i:h.push(i)})});return i.map(function(t){return ie(t)})},sortBy:function(t,e,r){var n=ne.superCall(this,he.prototype,"sortBy",[t,e]);return r||(n=n.values()),n.length=this.length,n},__makeSequence:function(){return i(this)}},{},ie);var oe=ae.prototype;oe.__toJS=oe.toArray,oe.__toStringMapper=p;var ce=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};ne.createClass(ce,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var s=e?i-u:u;if(t(r[n[s]],n[s],r)===!1)break}return u}},{},ie);var fe=function(t){this._array=t,this.length=t.length};ne.createClass(fe,{toArray:function(){return this._array},__iterate:function(t,e,r){var n=this._array,i=n.length-1,u=-1;if(e){for(var s=i;s>=0;s--){if(n.hasOwnProperty(s)&&t(n[s],r?s:i-s,n)===!1)return u+1;u=s}return n.length}var a=n.every(function(e,s){return t(e,r?i-s:s,n)===!1?!1:(u=s,!0)});return a?n.length:u+1}},{},ae),fe.prototype.get=ce.prototype.get,fe.prototype.has=ce.prototype.has;var le=function(t,e,r){this._rootData=t,this._keyPath=e,this._onChange=r},_e=le;ne.createClass(le,{get:function(t,e){var r=this._rootData.getIn(this._keyPath,de.empty());return t?r.get(t,e):r},set:function(t,e){return D(this,function(r){return r.set(t,e)},t)},"delete":function(t){return D(this,function(e){return e.delete(t)},t)},update:function(t,e){var r;return"function"==typeof t?(r=t,t=void 0):r=function(r){return r.update(t,e)},D(this,r,t)},cursor:function(t){return t&&!Array.isArray(t)&&(t=[t]),t&&0!==t.length?new _e(this._rootData,this._keyPath?this._keyPath.concat(t):t,this._onChange):this}},{});var ve=5,ge=1<<ve,pe=ge-1,me={},de=function(t){var e=ye.empty();return t?t.constructor===ye?t:e.merge(t):e <ide> },ye=de;ne.createClass(de,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,L(t),t,e):e},set:function(t,e){return S(this,t,e)},"delete":function(t){return S(this,t,me)},update:function(t,e){return this.set(t,e(this.get(t)))},clear:function(){return this.__ownerID?(this.length=0,this._root=null,this):ye.empty()},merge:function(){return j(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return j(this,t,e)},mergeDeep:function(){return j(this,P(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return j(this,P(t),e)},updateIn:function(t,e){return t&&0!==t.length?z(this,t,e,0):e(this)},cursor:function(t,e){return e||"function"!=typeof t||(e=t,t=null),t&&!Array.isArray(t)&&(t=[t]),new le(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.__ensureOwner(this.__ownerID)},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new O)},asImmutable:function(){return this.__ensureOwner()},__iterate:function(t,e){var r=this;if(!r._root)return 0;var n=0;return this._root.iterate(function(e){return t(e[1],e[0],r)===!1?!1:void n++},e),n},__deepEqual:function(t){var e=this;return t.every(function(t,r){return w(e.get(r,me),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?k(this.length,this._root,t):(this.__ownerID=t,this)}},{empty:function(){return Ee||(Ee=k(0))}},ie);var we=de.prototype;de.from=de;var Ie=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},De=Ie;ne.createClass(Ie,{get:function(t,e,r,n){var i=1<<(e>>>t&pe),u=this.bitmap;return 0===(u&i)?n:this.nodes[R(u&i-1)].get(t+ve,e,r,n)},update:function(t,e,r,n,i,u){var s=r>>>e&pe,a=1<<s,h=this.bitmap,o=0!==(h&a);if(!o&&i===me)return this;var c=R(h&a-1),f=this.nodes,l=o?f[c]:null,_=x(l,t,e+ve,r,n,i,u);if(_===l)return this;if(!o&&_&&f.length>=ze)return q(t,f,h,c,_);if(o&&!_&&2===f.length&&E(f[1^c]))return f[1^c];if(o&&_&&1===f.length&&E(_))return _;var v=t&&t===this.ownerID,g=o?_?h:h^a:h|a,p=o?_?W(f,c,_,v):B(f,c,v):J(f,c,_,v); <del>return v?(this.bitmap=g,this.nodes=p,this):new De(t,g,p)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var Oe=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},be=Oe;ne.createClass(Oe,{get:function(t,e,r,n){var i=e>>>t&pe,u=this.nodes[i];return u?u.get(t+ve,e,r,n):n},update:function(t,e,r,n,i,u){var s=r>>>e&pe,a=i===me,h=this.nodes,o=h[s];if(a&&!o)return this;var c=x(o,t,e+ve,r,n,i,u);if(c===o)return this;var f=this.count;if(o){if(!c&&(f--,Re>f))return A(t,h,f,s)}else f++;var l=t&&t===this.ownerID,_=W(h,s,c,l);return l?(this.count=f,this.nodes=_,this):new be(t,f,_)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Me=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},ke=Me;ne.createClass(Me,{get:function(t,e,r,n){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(w(r,i[u][0]))return i[u][1];return n},update:function(t,e,r,n,i,u){var s=i===me;if(r!==this.hash)return s?this:(u&&(u.value=!0),C(this,t,e,r,[n,i]));for(var a=this.entries,h=0,o=a.length;o>h&&!w(n,a[h][0]);h++);var c=o>h;if(s&&!c)return this;if((s||!c)&&u&&(u.value=!0),s&&2===o)return new Se(t,this.hash,a[1^h]);var f=t&&t===this.ownerID,l=f?a:b(a);return c?s?h===o-1?l.pop():l[h]=l.pop():l[h]=[n,i]:l.push([n,i]),f?(this.entries=l,this):new ke(t,this.hash,l)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var Se=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},xe=Se;ne.createClass(Se,{get:function(t,e,r,n){return w(r,this.entry[0])?this.entry[1]:n},update:function(t,e,r,n,i,u){var s=w(n,this.entry[0]);return i===me?(s&&u&&(u.value=!0),s?null:this):s?i===this.entry[1]?this:t&&t===this.ownerID?(this.entry[1]=i,this):new xe(t,r,[n,i]):(u&&(u.value=!0),C(this,t,e,r,[n,i]))},iterate:function(t){return t(this.entry)}},{});var Ee,Ce={value:!1},Ae=4294967296,qe=16,je=255,Pe=0,Ue={},ze=ge/2,Re=ge/4,We=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e]; <add>return v?(this.bitmap=g,this.nodes=p,this):new De(t,g,p)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var Oe=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},be=Oe;ne.createClass(Oe,{get:function(t,e,r,n){var i=e>>>t&pe,u=this.nodes[i];return u?u.get(t+ve,e,r,n):n},update:function(t,e,r,n,i,u){var s=r>>>e&pe,a=i===me,h=this.nodes,o=h[s];if(a&&!o)return this;var c=x(o,t,e+ve,r,n,i,u);if(c===o)return this;var f=this.count;if(o){if(!c&&(f--,Re>f))return A(t,h,f,s)}else f++;var l=t&&t===this.ownerID,_=W(h,s,c,l);return l?(this.count=f,this.nodes=_,this):new be(t,f,_)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Me=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},ke=Me;ne.createClass(Me,{get:function(t,e,r,n){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(w(r,i[u][0]))return i[u][1];return n},update:function(t,e,r,n,i,u){var s=i===me;if(r!==this.hash)return s?this:(u&&(u.value=!0),C(this,t,e,r,[n,i]));for(var a=this.entries,h=0,o=a.length;o>h&&!w(n,a[h][0]);h++);var c=o>h;if(s&&!c)return this;if((s||!c)&&u&&(u.value=!0),s&&2===o)return new Se(t,this.hash,a[1^h]);var f=t&&t===this.ownerID,l=f?a:b(a);return c?s?h===o-1?l.pop():l[h]=l.pop():l[h]=[n,i]:l.push([n,i]),f?(this.entries=l,this):new ke(t,this.hash,l)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var Se=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},xe=Se;ne.createClass(Se,{get:function(t,e,r,n){return w(r,this.entry[0])?this.entry[1]:n},update:function(t,e,r,n,i,u){var s=w(n,this.entry[0]);return i===me?(s&&u&&(u.value=!0),s?null:this):s?i===this.entry[1]?this:t&&t===this.ownerID?(this.entry[1]=i,this):new xe(t,r,[n,i]):(u&&(u.value=!0),C(this,t,e,r,[n,i]))},iterate:function(t){return t(this.entry)}},{});var Ee,Ce={value:!1},Ae=2147483647,qe=16,je=255,Pe=0,Ue={},ze=ge/2,Re=ge/4,We=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e]; <ide> return Je.from(t)},Je=We;ne.createClass(We,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=Q(t,this._origin),t>=this._size)return e;var r=F(this,t),n=t&pe;return r&&(void 0===e||r.array.hasOwnProperty(n))?r.array[n]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){var r=T(this._size);if(t>=this.length)return this.withMutations(function(r){return G(r,0,t+1).set(t,e)});if(this.get(t,me)===e)return this;if(t=Q(t,this._origin),t>=r){var n=this._tail.ensureOwner(this.__ownerID);n.array[t&pe]=e;var i=t>=this._size?t+1:this._size;return this.__ownerID?(this.length=i-this._origin,this._size=i,this._tail=n,this):N(this._origin,i,this._level,this._root,n)}for(var u=this._root.ensureOwner(this.__ownerID),s=u,a=this._level;a>0;a-=ve){var h=t>>>a&pe;s=s.array[h]=s.array[h]?s.array[h].ensureOwner(this.__ownerID):new Le([],this.__ownerID)}return s.array[t&pe]=e,this.__ownerID?(this._root=u,this):N(this._origin,this._size,this._level,u,this._tail)},"delete":function(t){if(!this.has(t))return this;var e=T(this._size);if(t=Q(t,this._origin),t>=e){var r=this._tail.ensureOwner(this.__ownerID);return delete r.array[t&pe],this.__ownerID?(this._tail=r,this):N(this._origin,this._size,this._level,this._root,r)}for(var n=this._root.ensureOwner(this.__ownerID),i=n,u=this._level;u>0;u-=ve){var s=t>>>u&pe;i=i.array[s]=i.array[s].ensureOwner(this.__ownerID)}return delete i.array[t&pe],this.__ownerID?(this._root=n,this):N(this._origin,this._size,this._level,n,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=ve,this._root=this._tail=Fe,this):Je.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){G(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return G(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){G(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return G(this,1) <ide> },merge:function(){return H(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return H(this,t,e)},mergeDeep:function(){return H(this,P(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return H(this,P(t),e)},setLength:function(t){return G(this,0,t)},slice:function(t,e,r){var n=ne.superCall(this,Je.prototype,"slice",[t,e,r]);if(!r&&n!==this){var i=this,u=i.length;n.toVector=function(){return G(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e)}}return n},iterator:function(){return new Ke(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,r){var n=this,i=0,u=n.length-1;r^=e;var s,a=function(e,s){return t(e,r?u-s:s,n)===!1?!1:(i=s,!0)},h=T(this._size);return s=e?this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e)&&this._root.iterate(this._level,-this._origin,h-this._origin,a,e):this._root.iterate(this._level,-this._origin,h-this._origin,a,e)&&this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.iterator();return t.every(function(t,r){var n=e.next().value;return n&&r===n[0]&&w(t,n[1])})},__ensureOwner:function(t){return t===this.__ownerID?this:t?N(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return Ne||(Ne=N(0,0,ve,Fe,Fe))},from:function(t){if(!t||0===t.length)return Je.empty();if(t.constructor===Je)return t;var e=Array.isArray(t);return t.length>0&&ge>t.length?N(0,t.length,ve,Fe,new Le(e?b(t):ie(t).toArray())):(e||(t=ie(t),t instanceof ae||(t=t.values())),Je.empty().merge(t))}},ae);var Be=We.prototype;Be["@@iterator"]=Be.__iterator__,Be.update=we.update,Be.updateIn=we.updateIn,Be.cursor=we.cursor,Be.withMutations=we.withMutations,Be.asMutable=we.asMutable,Be.asImmutable=we.asImmutable;var Le=function(t,e){this.array=t,this.ownerID=e},Ve=Le;ne.createClass(Le,{ensureOwner:function(t){return t&&t===this.ownerID?this:new Ve(this.array.slice(),t) <ide> },removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&pe;if(n>=this.array.length)return new Ve([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();if(!u)for(var h=0;n>h;h++)delete a.array[h];return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&pe;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();return u||(a.array.length=n+1),i&&(a.array[n]=i),a},iterate:function(t,e,r,n,i){if(0===t){if(i){for(var u=this.array.length-1;u>=0;u--)if(this.array.hasOwnProperty(u)){var s=u+e;if(s>=0&&r>s&&n(this.array[u],s)===!1)return!1}return!0}return this.array.every(function(t,i){var u=i+e;return 0>u||u>=r||n(t,u)!==!1})}var a=1<<t,h=t-ve;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*a;if(r>c&&c+a>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(h,c,r,n,i))return!1}return!0}return this.array.every(function(t,u){var s=e+u*a;return s>=r||0>=s+a||t.iterate(h,s,r,n,i)})}},{});var Ke=function(t,e,r,n,i,u){var s=T(r);this._stack={node:i.array,level:n,offset:-e,max:s-e,__prev:{node:u.array,level:0,offset:s-e,max:r-e}}};ne.createClass(Ke,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var r=t.node[t.rawIndex];return t.rawIndex++,{value:[e,r],done:!0}}t.rawIndex++}else{var n=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*n;if(i+n>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var u=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:u,level:t.level-ve,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var Ne,Fe=new Le([]),Ge=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e]; <ide><path>src/Map.js <ide> function hashValue(o) { <ide> var type = typeof o; <ide> if (type === 'number') { <ide> if ((o | 0) === o) { <del> return o % HASH_MAX_VAL; <add> return o & HASH_MAX_VAL; <ide> } <ide> o = '' + o; <ide> type = 'string'; <ide> function hashString(string) { <ide> // The hash code for a string is computed as <ide> // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], <ide> // where s[i] is the ith character of the string and n is the length of <del> // the string. We mod the result to make it between 0 (inclusive) and 2^32 <del> // (exclusive). <add> // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 <add> // (exclusive) by dropping high bits. <ide> var hash = 0; <ide> for (var ii = 0; ii < string.length; ii++) { <del> hash = (31 * hash + string.charCodeAt(ii)) % HASH_MAX_VAL; <add> hash = (31 * hash + string.charCodeAt(ii)) & HASH_MAX_VAL; <ide> } <ide> return hash; <ide> } <ide> <del>var HASH_MAX_VAL = 0x100000000; // 2^32 <add>var HASH_MAX_VAL = 0x7FFFFFFF; // 2^31 - 1 <ide> var STRING_HASH_CACHE_MIN_STRLEN = 16; <ide> var STRING_HASH_CACHE_MAX_SIZE = 255; <ide> var STRING_HASH_CACHE_SIZE = 0;
3
Java
Java
avoid accidental usage of junit 4 assumptions
5d5f9aceca7e953fa8c783e9730478205f7d3e2a
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/AbstractHttpHandlerIntegrationTests.java <ide> protected void startServer(HttpServer httpServer) throws Exception { <ide> <ide> @AfterEach <ide> void stopServer() { <del> this.server.stop(); <del> this.port = 0; <add> if (this.server != null) { <add> this.server.stop(); <add> this.port = 0; <add> } <ide> } <ide> <ide> <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java <ide> import org.springframework.web.client.RestTemplate; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <del>import static org.junit.Assume.assumeTrue; <add>import static org.junit.jupiter.api.Assumptions.assumeTrue; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide> protected HttpHandler createHttpHandler() { <ide> <ide> @ParameterizedHttpServerTest <ide> public void zeroCopy(HttpServer httpServer) throws Exception { <del> startServer(httpServer); <add> assumeTrue(httpServer instanceof ReactorHttpServer || httpServer instanceof UndertowHttpServer, <add> "Zero-copy only does not support servlet"); <ide> <del> // Zero-copy only does not support servlet <del> assumeTrue(server instanceof ReactorHttpServer || server instanceof UndertowHttpServer); <add> startServer(httpServer); <ide> <ide> URI url = new URI("http://localhost:" + port); <ide> RequestEntity<?> request = RequestEntity.get(url).build(); <ide><path>spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <del>import static org.junit.Assume.assumeFalse; <add>import static org.junit.jupiter.api.Assumptions.assumeFalse; <ide> import static org.springframework.http.HttpMethod.POST; <ide> import static org.springframework.http.MediaType.MULTIPART_MIXED; <ide> <ide> void postForObject(ClientHttpRequestFactory clientHttpRequestFactory) throws Exc <ide> <ide> @ParameterizedRestTemplateTest <ide> void patchForObject(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception { <del> setUpClient(clientHttpRequestFactory); <add> assumeFalse(clientHttpRequestFactory instanceof SimpleClientHttpRequestFactory, <add> "JDK client does not support the PATCH method"); <ide> <del> // JDK client does not support the PATCH method <del> assumeFalse(this.clientHttpRequestFactory instanceof SimpleClientHttpRequestFactory); <add> setUpClient(clientHttpRequestFactory); <ide> <ide> String s = template.patchForObject(baseUrl + "/{method}", helloWorld, String.class, "patch"); <ide> assertThat(s).as("Invalid content").isEqualTo(helloWorld); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java <ide> void sseAsPerson(HttpServer httpServer, ClientHttpConnector connector) throws Ex <ide> <ide> @ParameterizedSseTest <ide> void sseAsEvent(HttpServer httpServer, ClientHttpConnector connector) throws Exception { <del> startServer(httpServer, connector); <add> assumeTrue(httpServer instanceof JettyHttpServer); <ide> <del> assumeTrue(super.server instanceof JettyHttpServer); <add> startServer(httpServer, connector); <ide> <ide> Flux<ServerSentEvent<Person>> result = this.webClient.get() <ide> .uri("/event") <ide> private void verifyPersonEvents(Flux<ServerSentEvent<Person>> result) { <ide> @ParameterizedSseTest // SPR-16494 <ide> @Disabled // https://github.com/reactor/reactor-netty/issues/283 <ide> void serverDetectsClientDisconnect(HttpServer httpServer, ClientHttpConnector connector) throws Exception { <del> startServer(httpServer, connector); <add> assumeTrue(httpServer instanceof ReactorHttpServer); <ide> <del> assumeTrue(super.server instanceof ReactorHttpServer); <add> startServer(httpServer, connector); <ide> <ide> Flux<String> result = this.webClient.get() <ide> .uri("/infinite")
4
Javascript
Javascript
fix windows mispotionning issue
2e7df014592624b62b1aec74345c016713e52afa
<ide><path>fonts.js <ide> var Font = (function () { <ide> string16(properties.ascent) + // Typographic Ascent <ide> string16(properties.descent) + // Typographic Descent <ide> "\x00\x00" + // Line Gap <del> "\x00\xFF" + // advanceWidthMax <add> "\xFF\xFF" + // advanceWidthMax <ide> "\x00\x00" + // minLeftSidebearing <ide> "\x00\x00" + // minRightSidebearing <ide> "\x00\x00" + // xMaxExtent
1
Javascript
Javascript
fix error in treesitterhighlightiterator.seek
e09ee1c1fa8ac10dbec10a0fc47253bb51c7bbd7
<ide><path>spec/tree-sitter-language-mode-spec.js <ide> describe('TreeSitterLanguageMode', () => { <ide> <ide> buffer.setLanguageMode(new TreeSitterLanguageMode({buffer, grammar})) <ide> buffer.setText('aa.bbb = cc(d.eee());') <del> expectTokensToEqual(editor, [ <add> expectTokensToEqual(editor, [[ <ide> {text: 'aa.', scopes: ['source']}, <ide> {text: 'bbb', scopes: ['source', 'property']}, <ide> {text: ' = ', scopes: ['source']}, <ide> {text: 'cc', scopes: ['source', 'function']}, <ide> {text: '(d.', scopes: ['source']}, <ide> {text: 'eee', scopes: ['source', 'method']}, <ide> {text: '());', scopes: ['source']} <del> ]) <add> ]]) <ide> }) <ide> <ide> it('can start or end multiple scopes at the same position', () => { <ide> describe('TreeSitterLanguageMode', () => { <ide> <ide> buffer.setLanguageMode(new TreeSitterLanguageMode({buffer, grammar})) <ide> buffer.setText('a = bb.ccc();') <del> expectTokensToEqual(editor, [ <add> expectTokensToEqual(editor, [[ <ide> {text: 'a', scopes: ['source', 'variable']}, <ide> {text: ' = ', scopes: ['source']}, <ide> {text: 'bb', scopes: ['source', 'call', 'member', 'variable']}, <ide> {text: '.ccc', scopes: ['source', 'call', 'member']}, <ide> {text: '(', scopes: ['source', 'call', 'open-paren']}, <ide> {text: ')', scopes: ['source', 'call', 'close-paren']}, <ide> {text: ';', scopes: ['source']} <add> ]]) <add> }) <add> <add> it('can resume highlighting on a line that starts with whitespace', () => { <add> const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, { <add> parser: 'tree-sitter-javascript', <add> scopes: { <add> 'call_expression > member_expression > property_identifier': 'function', <add> 'property_identifier': 'member', <add> 'identifier': 'variable' <add> } <add> }) <add> <add> buffer.setLanguageMode(new TreeSitterLanguageMode({buffer, grammar})) <add> buffer.setText('a\n .b();') <add> expectTokensToEqual(editor, [ <add> [ <add> {text: 'a', scopes: ['variable']}, <add> ], <add> [ <add> {text: ' ', scopes: ['whitespace']}, <add> {text: '.', scopes: []}, <add> {text: 'b', scopes: ['function']}, <add> {text: '();', scopes: []} <add> ] <ide> ]) <ide> }) <ide> }) <ide> function getDisplayText (editor) { <ide> return editor.displayLayer.getText() <ide> } <ide> <del>function expectTokensToEqual (editor, expectedTokens) { <del> const tokens = [] <del> for (let row = 0, lastRow = editor.getLastScreenRow(); row <= lastRow; row++) { <del> tokens.push( <del> ...editor.tokensForScreenRow(row).map(({text, scopes}) => ({ <add>function expectTokensToEqual (editor, expectedTokenLines) { <add> const lastRow = editor.getLastScreenRow() <add> <add> // Assert that the correct tokens are returned regardless of which row <add> // the highlighting iterator starts on. <add> for (let startRow = 0; startRow <= lastRow; startRow++) { <add> editor.displayLayer.clearSpatialIndex() <add> editor.displayLayer.getScreenLines(startRow, Infinity) <add> <add> const tokenLines = [] <add> for (let row = startRow; row <= lastRow; row++) { <add> tokenLines[row] = editor.tokensForScreenRow(row).map(({text, scopes}) => ({ <ide> text, <ide> scopes: scopes.map(scope => scope <ide> .split(' ') <ide> .map(className => className.slice('syntax--'.length)) <ide> .join(' ')) <ide> })) <del> ) <del> } <add> } <add> <add> for (let row = startRow; row <= lastRow; row++) { <add> const tokenLine = tokenLines[row] <add> const expectedTokenLine = expectedTokenLines[row] <ide> <del> expect(tokens.length).toEqual(expectedTokens.length) <del> for (let i = 0; i < tokens.length; i++) { <del> expect(tokens[i]).toEqual(expectedTokens[i], `Token ${i}`) <add> expect(tokenLine.length).toEqual(expectedTokenLine.length) <add> for (let i = 0; i < tokenLine.length; i++) { <add> expect(tokenLine[i]).toEqual(expectedTokenLine[i], `Token ${i}, startRow: ${startRow}`) <add> } <add> } <ide> } <ide> } <ide><path>src/tree-sitter-language-mode.js <ide> class TreeSitterHighlightIterator { <ide> do { <ide> this.currentNode = node <ide> this.currentChildIndex = childIndex <add> if (!nodeContainsTarget) break <ide> this.containingNodeTypes.push(node.type) <ide> this.containingNodeChildIndices.push(childIndex) <del> if (!nodeContainsTarget) break <ide> <ide> const scopeName = this.currentScopeName() <ide> if (scopeName) {
2
Java
Java
fix issue with parsing x-forwarded-host header
1e90d029735e809a8ddb1c60f35e76083b1fe084
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java <ide> public static ServletUriComponentsBuilder fromRequestUri(HttpServletRequest requ <ide> public static ServletUriComponentsBuilder fromRequest(HttpServletRequest request) { <ide> String scheme = request.getScheme(); <ide> int port = request.getServerPort(); <del> <del> String header = request.getHeader("X-Forwarded-Host"); <del> String host = StringUtils.hasText(header) ? header: request.getServerName(); <add> String host = request.getServerName(); <add> <add> String xForwardedHostHeader = request.getHeader("X-Forwarded-Host"); <add> <add> if (StringUtils.hasText(xForwardedHostHeader)) { <add> if (StringUtils.countOccurrencesOf(xForwardedHostHeader, ":") == 1) { <add> String[] hostAndPort = StringUtils.split(xForwardedHostHeader, ":"); <add> host = hostAndPort[0]; <add> port = Integer.parseInt(hostAndPort[1]); <add> } <add> else { <add> host = xForwardedHostHeader; <add> } <add> } <ide> <ide> ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder(); <ide> builder.scheme(scheme); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java <ide> <ide> package org.springframework.web.servlet.support; <ide> <del>import static org.junit.Assert.assertEquals; <del> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <add>import org.springframework.web.util.UriComponents; <add> <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> public void fromRequestWithForwardedHostHeader() { <ide> assertEquals("http://anotherHost/mvc-showcase/data/param?foo=123", result); <ide> } <ide> <add> // SPR-10701 <add> <add> @Test <add> public void fromRequestWithForwardedHostAndPortHeader() { <add> request.addHeader("X-Forwarded-Host", "webtest.foo.bar.com:443"); <add> request.setRequestURI("/mvc-showcase/data/param"); <add> request.setQueryString("foo=123"); <add> UriComponents result = ServletUriComponentsBuilder.fromRequest(request).build(); <add> <add> assertEquals("webtest.foo.bar.com", result.getHost()); <add> assertEquals(443, result.getPort()); <add> } <add> <ide> @Test <ide> public void fromContextPath() { <ide> request.setRequestURI("/mvc-showcase/data/param");
2
Python
Python
add xfailing test for
231bc7bb7bd7e373d4b4c9a3e33d6539d0637828
<ide><path>spacy/tests/regression/test_issue3345.py <add>"""Test interaction between preset entities and sentence boundaries in NER.""" <add>import spacy <add>from spacy.tokens import Doc <add>from spacy.pipeline import EntityRuler, EntityRecognizer <add> <add> <add>@pytest.mark.xfail <add>def test_issue3345(): <add> """Test case where preset entity crosses sentence boundary.""" <add> nlp = spacy.blank("en") <add> doc = Doc(nlp.vocab, words=["I", "live", "in", "New", "York"]) <add> doc[4].is_sent_start = True <add> <add> ruler = EntityRuler(nlp, patterns=[{"label": "GPE", "pattern": "New York"}]) <add> ner = EntityRecognizer(doc.vocab) <add> # Add the OUT action. I wouldn't have thought this would be necessary... <add> ner.moves.add_action(5, "") <add> ner.add_label("GPE") <add> <add> doc = ruler(doc) <add> # Get into the state just before "New" <add> state = ner.moves.init_batch([doc])[0] <add> ner.moves.apply_transition(state, "O") <add> ner.moves.apply_transition(state, "O") <add> ner.moves.apply_transition(state, "O") <add> # Check that B-GPE is valid. <add> assert ner.moves.is_valid(state, "B-GPE")
1
Go
Go
remove events package
d487ca03e6e897e4bb5f9ba28b268450f059fc0d
<ide><path>events/events.go <del>package events <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "fmt" <del> "io" <del> "strings" <del> "sync" <del> "time" <del> <del> "github.com/docker/docker/engine" <del> "github.com/docker/docker/pkg/jsonmessage" <del> "github.com/docker/docker/pkg/parsers/filters" <del>) <del> <del>const eventsLimit = 64 <del> <del>type listener chan<- *jsonmessage.JSONMessage <del> <del>type Events struct { <del> mu sync.RWMutex <del> events []*jsonmessage.JSONMessage <del> subscribers []listener <del>} <del> <del>func New() *Events { <del> return &Events{ <del> events: make([]*jsonmessage.JSONMessage, 0, eventsLimit), <del> } <del>} <del> <del>// Install installs events public api in docker engine <del>func (e *Events) Install(eng *engine.Engine) error { <del> // Here you should describe public interface <del> jobs := map[string]engine.Handler{ <del> "events": e.Get, <del> "log": e.Log, <del> "subscribers_count": e.SubscribersCount, <del> } <del> for name, job := range jobs { <del> if err := eng.Register(name, job); err != nil { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>func (e *Events) Get(job *engine.Job) error { <del> var ( <del> since = job.GetenvInt64("since") <del> until = job.GetenvInt64("until") <del> timeout = time.NewTimer(time.Unix(until, 0).Sub(time.Now())) <del> ) <del> <del> eventFilters, err := filters.FromParam(job.Getenv("filters")) <del> if err != nil { <del> return err <del> } <del> <del> // If no until, disable timeout <del> if job.Getenv("until") == "" { <del> timeout.Stop() <del> } <del> <del> listener := make(chan *jsonmessage.JSONMessage) <del> e.subscribe(listener) <del> defer e.unsubscribe(listener) <del> <del> job.Stdout.Write(nil) <del> <del> // Resend every event in the [since, until] time interval. <del> if job.Getenv("since") != "" { <del> if err := e.writeCurrent(job, since, until, eventFilters); err != nil { <del> return err <del> } <del> } <del> <del> for { <del> select { <del> case event, ok := <-listener: <del> if !ok { <del> return nil <del> } <del> if err := writeEvent(job, event, eventFilters); err != nil { <del> return err <del> } <del> case <-timeout.C: <del> return nil <del> } <del> } <del>} <del> <del>func (e *Events) Log(job *engine.Job) error { <del> if len(job.Args) != 3 { <del> return fmt.Errorf("usage: %s ACTION ID FROM", job.Name) <del> } <del> // not waiting for receivers <del> go e.log(job.Args[0], job.Args[1], job.Args[2]) <del> return nil <del>} <del> <del>func (e *Events) SubscribersCount(job *engine.Job) error { <del> ret := &engine.Env{} <del> ret.SetInt("count", e.subscribersCount()) <del> ret.WriteTo(job.Stdout) <del> return nil <del>} <del> <del>func writeEvent(job *engine.Job, event *jsonmessage.JSONMessage, eventFilters filters.Args) error { <del> isFiltered := func(field string, filter []string) bool { <del> if len(filter) == 0 { <del> return false <del> } <del> for _, v := range filter { <del> if v == field { <del> return false <del> } <del> if strings.Contains(field, ":") { <del> image := strings.Split(field, ":") <del> if image[0] == v { <del> return false <del> } <del> } <del> } <del> return true <del> } <del> <del> //incoming container filter can be name,id or partial id, convert and replace as a full container id <del> for i, cn := range eventFilters["container"] { <del> eventFilters["container"][i] = GetContainerId(job.Eng, cn) <del> } <del> <del> if isFiltered(event.Status, eventFilters["event"]) || isFiltered(event.From, eventFilters["image"]) || <del> isFiltered(event.ID, eventFilters["container"]) { <del> return nil <del> } <del> <del> // When sending an event JSON serialization errors are ignored, but all <del> // other errors lead to the eviction of the listener. <del> if b, err := json.Marshal(event); err == nil { <del> if _, err = job.Stdout.Write(b); err != nil { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>func (e *Events) writeCurrent(job *engine.Job, since, until int64, eventFilters filters.Args) error { <del> e.mu.RLock() <del> for _, event := range e.events { <del> if event.Time >= since && (event.Time <= until || until == 0) { <del> if err := writeEvent(job, event, eventFilters); err != nil { <del> e.mu.RUnlock() <del> return err <del> } <del> } <del> } <del> e.mu.RUnlock() <del> return nil <del>} <del> <del>func (e *Events) subscribersCount() int { <del> e.mu.RLock() <del> c := len(e.subscribers) <del> e.mu.RUnlock() <del> return c <del>} <del> <del>func (e *Events) log(action, id, from string) { <del> e.mu.Lock() <del> now := time.Now().UTC().Unix() <del> jm := &jsonmessage.JSONMessage{Status: action, ID: id, From: from, Time: now} <del> if len(e.events) == cap(e.events) { <del> // discard oldest event <del> copy(e.events, e.events[1:]) <del> e.events[len(e.events)-1] = jm <del> } else { <del> e.events = append(e.events, jm) <del> } <del> for _, s := range e.subscribers { <del> // We give each subscriber a 100ms time window to receive the event, <del> // after which we move to the next. <del> select { <del> case s <- jm: <del> case <-time.After(100 * time.Millisecond): <del> } <del> } <del> e.mu.Unlock() <del>} <del> <del>func (e *Events) subscribe(l listener) { <del> e.mu.Lock() <del> e.subscribers = append(e.subscribers, l) <del> e.mu.Unlock() <del>} <del> <del>// unsubscribe closes and removes the specified listener from the list of <del>// previously registed ones. <del>// It returns a boolean value indicating if the listener was successfully <del>// found, closed and unregistered. <del>func (e *Events) unsubscribe(l listener) bool { <del> e.mu.Lock() <del> for i, subscriber := range e.subscribers { <del> if subscriber == l { <del> close(l) <del> e.subscribers = append(e.subscribers[:i], e.subscribers[i+1:]...) <del> e.mu.Unlock() <del> return true <del> } <del> } <del> e.mu.Unlock() <del> return false <del>} <del> <del>func GetContainerId(eng *engine.Engine, name string) string { <del> var buf bytes.Buffer <del> job := eng.Job("container_inspect", name) <del> <del> var outStream io.Writer <del> <del> outStream = &buf <del> job.Stdout.Set(outStream) <del> <del> if err := job.Run(); err != nil { <del> return "" <del> } <del> var out struct{ ID string } <del> json.NewDecoder(&buf).Decode(&out) <del> return out.ID <del>} <ide><path>events/events_test.go <del>package events <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "fmt" <del> "io" <del> "testing" <del> "time" <del> <del> "github.com/docker/docker/engine" <del> "github.com/docker/docker/pkg/jsonmessage" <del>) <del> <del>func TestEventsPublish(t *testing.T) { <del> e := New() <del> l1 := make(chan *jsonmessage.JSONMessage) <del> l2 := make(chan *jsonmessage.JSONMessage) <del> e.subscribe(l1) <del> e.subscribe(l2) <del> count := e.subscribersCount() <del> if count != 2 { <del> t.Fatalf("Must be 2 subscribers, got %d", count) <del> } <del> go e.log("test", "cont", "image") <del> select { <del> case msg := <-l1: <del> if len(e.events) != 1 { <del> t.Fatalf("Must be only one event, got %d", len(e.events)) <del> } <del> if msg.Status != "test" { <del> t.Fatalf("Status should be test, got %s", msg.Status) <del> } <del> if msg.ID != "cont" { <del> t.Fatalf("ID should be cont, got %s", msg.ID) <del> } <del> if msg.From != "image" { <del> t.Fatalf("From should be image, got %s", msg.From) <del> } <del> case <-time.After(1 * time.Second): <del> t.Fatal("Timeout waiting for broadcasted message") <del> } <del> select { <del> case msg := <-l2: <del> if len(e.events) != 1 { <del> t.Fatalf("Must be only one event, got %d", len(e.events)) <del> } <del> if msg.Status != "test" { <del> t.Fatalf("Status should be test, got %s", msg.Status) <del> } <del> if msg.ID != "cont" { <del> t.Fatalf("ID should be cont, got %s", msg.ID) <del> } <del> if msg.From != "image" { <del> t.Fatalf("From should be image, got %s", msg.From) <del> } <del> case <-time.After(1 * time.Second): <del> t.Fatal("Timeout waiting for broadcasted message") <del> } <del>} <del> <del>func TestEventsPublishTimeout(t *testing.T) { <del> e := New() <del> l := make(chan *jsonmessage.JSONMessage) <del> e.subscribe(l) <del> <del> c := make(chan struct{}) <del> go func() { <del> e.log("test", "cont", "image") <del> close(c) <del> }() <del> <del> select { <del> case <-c: <del> case <-time.After(time.Second): <del> t.Fatal("Timeout publishing message") <del> } <del>} <del> <del>func TestLogEvents(t *testing.T) { <del> e := New() <del> eng := engine.New() <del> if err := e.Install(eng); err != nil { <del> t.Fatal(err) <del> } <del> <del> for i := 0; i < eventsLimit+16; i++ { <del> action := fmt.Sprintf("action_%d", i) <del> id := fmt.Sprintf("cont_%d", i) <del> from := fmt.Sprintf("image_%d", i) <del> job := eng.Job("log", action, id, from) <del> if err := job.Run(); err != nil { <del> t.Fatal(err) <del> } <del> } <del> time.Sleep(50 * time.Millisecond) <del> if len(e.events) != eventsLimit { <del> t.Fatalf("Must be %d events, got %d", eventsLimit, len(e.events)) <del> } <del> <del> job := eng.Job("events") <del> job.SetenvInt64("since", 1) <del> job.SetenvInt64("until", time.Now().Unix()) <del> buf := bytes.NewBuffer(nil) <del> job.Stdout.Add(buf) <del> if err := job.Run(); err != nil { <del> t.Fatal(err) <del> } <del> buf = bytes.NewBuffer(buf.Bytes()) <del> dec := json.NewDecoder(buf) <del> var msgs []jsonmessage.JSONMessage <del> for { <del> var jm jsonmessage.JSONMessage <del> if err := dec.Decode(&jm); err != nil { <del> if err == io.EOF { <del> break <del> } <del> t.Fatal(err) <del> } <del> msgs = append(msgs, jm) <del> } <del> if len(msgs) != eventsLimit { <del> t.Fatalf("Must be %d events, got %d", eventsLimit, len(msgs)) <del> } <del> first := msgs[0] <del> if first.Status != "action_16" { <del> t.Fatalf("First action is %s, must be action_15", first.Status) <del> } <del> last := msgs[len(msgs)-1] <del> if last.Status != "action_79" { <del> t.Fatalf("First action is %s, must be action_79", first.Status) <del> } <del>} <del> <del>func TestEventsCountJob(t *testing.T) { <del> e := New() <del> eng := engine.New() <del> if err := e.Install(eng); err != nil { <del> t.Fatal(err) <del> } <del> l1 := make(chan *jsonmessage.JSONMessage) <del> l2 := make(chan *jsonmessage.JSONMessage) <del> e.subscribe(l1) <del> e.subscribe(l2) <del> job := eng.Job("subscribers_count") <del> env, _ := job.Stdout.AddEnv() <del> if err := job.Run(); err != nil { <del> t.Fatal(err) <del> } <del> count := env.GetInt("count") <del> if count != 2 { <del> t.Fatalf("There must be 2 subscribers, got %d", count) <del> } <del>}
2
PHP
PHP
remove unused import
de04ffe9626850cc69d2150eb4f2c06a36f6f01e
<ide><path>src/Core/Plugin.php <ide> */ <ide> namespace Cake\Core; <ide> <del>use ArgumentCountError; <ide> use DirectoryIterator; <ide> <ide> /**
1
Javascript
Javascript
implement challenge schema
c754880476d09b17d48f9c5d687c7891ac7915a4
<ide><path>index.js <ide> const utils = require('../server/utils'); <ide> const getChallenges = require('./getChallenges'); <ide> const app = require('../server/server'); <ide> const createDebugger = require('debug'); <add>const { validateChallenge } = require('./schema/challengeSchema'); <ide> <ide> const log = createDebugger('fcc:seed'); <ide> // force logger to always output <ide> Observable.combineLatest( <ide> challenge.order = order; <ide> challenge.suborder = index + 1; <ide> challenge.block = dasherize(blockName); <del> challenge.blockId = block.id; <add> challenge.blockId = '' + block.id; <ide> challenge.isBeta = challenge.isBeta || isBeta; <ide> challenge.isComingSoon = challenge.isComingSoon || isComingSoon; <ide> challenge.isLocked = challenge.isLocked || isLocked; <ide> Observable.combineLatest( <ide> .join(' '); <ide> challenge.required = (challenge.required || []).concat(required); <ide> challenge.template = challenge.template || template; <del> <del> return challenge; <add> return _.omit( <add> challenge, <add> [ <add> 'betaSolutions', <add> 'betaTests', <add> 'hints', <add> 'MDNlinks', <add> 'null', <add> 'rawSolutions', <add> 'react', <add> 'reactRedux', <add> 'redux', <add> 'releasedOn', <add> 'translations', <add> 'type' <add> ] <add> ); <ide> }); <ide> }) <del> .flatMap(challenges => createChallenges(challenges)); <add> .flatMap(challenges => { <add> challenges.forEach(challenge => { <add> const result = validateChallenge(challenge); <add> if (result.error) { <add> console.log(result.value); <add> throw new Error(result.error); <add> } <add> }); <add> return createChallenges(challenges); <add> }); <ide> }) <ide> .subscribe( <ide> function(challenges) { <ide><path>schema/challengeSchema.js <add>const Joi = require('joi'); <add>Joi.objectId = require('joi-objectid')(Joi); <add> <add>const schema = Joi.object().keys({ <add> block: Joi.string(), <add> blockId: Joi.objectId(), <add> challengeSeed: Joi.array().items( <add> Joi.string().allow('') <add> ), <add> challengeType: Joi.number().min(0).max(9).required(), <add> checksum: Joi.number(), <add> dashedName: Joi.string(), <add> description: Joi.array().items( <add> <add> // classic/modern challenges <add> Joi.string().allow(''), <add> <add> // step challenges <add> Joi.array().items( <add> Joi.string().allow('') <add> ).length(4), <add> <add> // quiz challenges <add> Joi.object().keys({ <add> subtitle: Joi.string(), <add> question: Joi.string(), <add> choices: Joi.array(), <add> answer: Joi.number(), <add> explanation: Joi.string() <add> }) <add> <add> ).required(), <add> fileName: Joi.string(), <add> files: Joi.object().pattern( <add> /(jsx?|html|css|sass)$/, <add> Joi.object().keys({ <add> key: Joi.string(), <add> ext: Joi.string(), <add> name: Joi.string(), <add> head: Joi.string().allow(''), <add> tail: Joi.string().allow(''), <add> contents: Joi.string() <add> }) <add> ), <add> guideUrl: Joi.string().uri({ scheme: 'https' }), <add> head: Joi.array().items( <add> Joi.string().allow('') <add> ), <add> helpRoom: Joi.string(), <add> id: Joi.objectId().required(), <add> isBeta: Joi.bool(), <add> isComingSoon: Joi.bool(), <add> isLocked: Joi.bool(), <add> isPrivate: Joi.bool(), <add> isRequired: Joi.bool(), <add> name: Joi.string(), <add> order: Joi.number(), <add> required: Joi.array().items( <add> Joi.object().keys({ <add> link: Joi.string(), <add> raw: Joi.bool(), <add> src: Joi.string(), <add> crossDomain: Joi.bool() <add> }) <add> ), <add> solutions: Joi.array().items( <add> Joi.string().optional() <add> ), <add> superBlock: Joi.string(), <add> superOrder: Joi.number(), <add> suborder: Joi.number(), <add> tail: Joi.array().items( <add> Joi.string().allow('') <add> ), <add> tests: Joi.array().items( <add> Joi.string().min(2), <add> Joi.object().keys({ <add> text: Joi.string().required(), <add> testString: Joi.string().allow('').required() <add> }), <add> Joi.object().keys({ <add> id: Joi.objectId().required(), <add> title: Joi.string().required() <add> }) <add> ), <add> template: Joi.string(), <add> time: Joi.string().allow(''), <add> title: Joi.string().required() <add>}); <add> <add>exports.validateChallenge = function validateChallenge(challenge) { <add> return Joi.validate(challenge, schema); <add>};
2
Ruby
Ruby
remove useless spec
365d2b214e681626b2f6203ff7fe4419ae3f76c8
<ide><path>Library/Homebrew/test/cask/cmd_spec.rb <ide> ]) <ide> end <ide> <del> it "ignores the `--language` option, which is handled in `OS::Mac`" do <del> cli = described_class.new("--language=en") <del> expect(cli).to receive(:detect_internal_command).with(no_args) <del> cli.run <del> end <del> <ide> context "when given no arguments" do <ide> it "exits successfully" do <ide> expect(subject).not_to receive(:exit).with(be_nonzero)
1
PHP
PHP
prepare query bindings for exception
ef8a2da67113ddea36f30b38646c1ad5cf52f159
<ide><path>src/Illuminate/Database/Connection.php <ide> protected function run($query, $bindings, Closure $callback) <ide> // lot more helpful to the developer instead of just the database's errors. <ide> catch (\Exception $e) <ide> { <del> throw new QueryException($query, $bindings, $e); <add> throw new QueryException($query, $this->prepareBindings($bindings), $e); <ide> } <ide> <ide> // Once we have run the query we will calculate the time that it took to run and
1
Go
Go
make testpsgroupportrange fast
cfa8aaf16f1f3b777851555afc83a1112c4f8879
<ide><path>integration-cli/docker_cli_ps_test.go <ide> func TestPsLinkedWithNoTrunc(t *testing.T) { <ide> func TestPsGroupPortRange(t *testing.T) { <ide> defer deleteAllContainers() <ide> <del> portRange := "3300-3900" <add> portRange := "3800-3900" <ide> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "porttest", "-p", portRange+":"+portRange, "busybox", "top")) <ide> if err != nil { <ide> t.Fatal(out, err)
1
Java
Java
add generics to abstractcachemanager#caches
42cbee883fb07fdb05da80e5dc9119b8cef8cb8f
<ide><path>org.springframework.context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java <ide> public abstract class AbstractCacheManager implements CacheManager, Initializing <ide> <ide> <ide> public void afterPropertiesSet() { <del> Collection<Cache> caches = loadCaches(); <add> Collection<? extends Cache> caches = loadCaches(); <ide> Assert.notEmpty(caches, "loadCaches must not return an empty Collection"); <ide> this.cacheMap.clear(); <ide> <ide> public Collection<String> getCacheNames() { <ide> * Load the caches for this cache manager. Occurs at startup. <ide> * The returned collection must not be null. <ide> */ <del> protected abstract Collection<Cache> loadCaches(); <add> protected abstract Collection<? extends Cache> loadCaches(); <ide> <ide> } <ide><path>org.springframework.context/src/main/java/org/springframework/cache/support/SimpleCacheManager.java <ide> */ <ide> public class SimpleCacheManager extends AbstractCacheManager { <ide> <del> private Collection<Cache> caches; <add> private Collection<? extends Cache> caches; <ide> <ide> /** <ide> * Specify the collection of Cache instances to use for this CacheManager. <ide> */ <del> public void setCaches(Collection<Cache> caches) { <add> public void setCaches(Collection<? extends Cache> caches) { <ide> this.caches = caches; <ide> } <ide> <ide> @Override <del> protected Collection<Cache> loadCaches() { <add> protected Collection<? extends Cache> loadCaches() { <ide> return this.caches; <ide> } <ide>
2
Go
Go
remove not necessary -d
faf4604dac41b4fdb88b3e6552d24d5ea5e3f16c
<ide><path>integration-cli/docker_api_volumes_test.go <ide> func (s *DockerSuite) TestVolumesApiCreate(c *check.C) { <ide> <ide> func (s *DockerSuite) TestVolumesApiRemove(c *check.C) { <ide> prefix, _ := getPrefixAndSlashFromDaemonPlatform() <del> dockerCmd(c, "run", "-d", "-v", prefix+"/foo", "--name=test", "busybox") <add> dockerCmd(c, "run", "-v", prefix+"/foo", "--name=test", "busybox") <ide> <ide> status, b, err := sockRequest("GET", "/volumes", nil) <ide> c.Assert(err, checker.IsNil) <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { <del> if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { <del> c.Fatal(err) <del> } <add> c.Assert(s.d.StartWithBusybox("--log-driver=none"), checker.IsNil) <ide> <del> out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") <del> if err != nil { <del> c.Fatal(out, err) <del> } <del> id := strings.TrimSpace(out) <del> out, err = s.d.Cmd("logs", id) <del> if err == nil { <del> c.Fatalf("Logs should fail with 'none' driver") <del> } <del> if !strings.Contains(out, `"logs" command is supported only for "json-file" and "journald" logging drivers (got: none)`) { <del> c.Fatalf("There should be an error about none not being a recognized log driver, got: %s", out) <del> } <add> out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> out, err = s.d.Cmd("logs", "test") <add> c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver")) <add> expected := `"logs" command is supported only for "json-file" and "journald" logging drivers (got: none)` <add> c.Assert(out, checker.Contains, expected) <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) { <ide><path>integration-cli/docker_cli_start_volume_driver_unix_test.go <ide> func (s DockerExternalVolumeSuite) TestExternalVolumeDriverVolumesFrom(c *check. <ide> err := s.d.StartWithBusybox() <ide> c.Assert(err, checker.IsNil) <ide> <del> out, err := s.d.Cmd("run", "-d", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest") <add> out, err := s.d.Cmd("run", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest") <ide> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> <ide> out, err = s.d.Cmd("run", "--rm", "--volumes-from", "vol-test1", "--name", "vol-test2", "busybox", "ls", "/tmp") <ide> func (s DockerExternalVolumeSuite) TestExternalVolumeDriverDeleteContainer(c *ch <ide> err := s.d.StartWithBusybox() <ide> c.Assert(err, checker.IsNil) <ide> <del> out, err := s.d.Cmd("run", "-d", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest") <add> out, err := s.d.Cmd("run", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest") <ide> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> <ide> out, err = s.d.Cmd("rm", "-fv", "vol-test1")
3
Text
Text
add pr template
3caf6420d03b65d11c786a58de9d30f0b6a754d0
<ide><path>.github/pull_request_template.md <add><!-- <add>Thanks for opening a PR! Your contribution is much appreciated. <add>In order to make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. <add>Choose the right checklist for the change that you're making: <add>--> <add> <add>## Bug <add> <add>- [ ] Related issues linked using `fixes #number` <add>- [ ] Integration tests added <add> <add>## Feature <add> <add>- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. <add>- [ ] Related issues linked using `fixes #number` <add>- [ ] Integration tests added <add>- [ ] Documentation added <add>- [ ] Telemetry added. In case of a feature if it's used or not. <add> <add>## Documentation / Examples <add> <add>- [ ] Make sure the linting passes
1
Go
Go
fix reference counting in graphdriver
7fab9b8a6054270763508ce88cb06c584cfeb153
<ide><path>daemon/graphdriver/windows/windows.go <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> mountPath, err := hcsshim.GetLayerMountPath(d.info, rID) <ide> if err != nil { <ide> d.ctr.Decrement(rID) <add> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <add> logrus.Warnf("Failed to Unprepare %s: %s", id, err) <add> } <ide> if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { <ide> logrus.Warnf("Failed to Deactivate %s: %s", id, err) <ide> } <ide> func (d *Driver) Put(id string) error { <ide> return nil <ide> } <ide> d.cacheMu.Lock() <add> _, exists := d.cache[rID] <ide> delete(d.cache, rID) <ide> d.cacheMu.Unlock() <ide> <add> // If the cache was not populated, then the layer was left unprepared and deactivated <add> if !exists { <add> return nil <add> } <add> <ide> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <ide> return err <ide> }
1
Ruby
Ruby
set a name for bottles
5d11b5e7a5b05728f05b143c6b07ab8b9bca8989
<ide><path>Library/Homebrew/software_spec.rb <ide> class Bottle <ide> <ide> attr_reader :resource, :prefix, :cellar, :revision <ide> <del> def_delegators :resource, :url, :fetch, :verify_download_integrity <add> def_delegators :resource, :name, :url, :fetch, :verify_download_integrity <ide> def_delegators :resource, :downloader, :cached_download, :clear_cache <ide> <ide> def initialize(f, spec) <del> @resource = Resource.new <add> @resource = Resource.new f.name <ide> @resource.owner = f <ide> @resource.url = bottle_url( <ide> spec.root_url,
1
Python
Python
add optional session argument to xcom_push.
22f6db7969b4c7dac45651f8b4a0fd6cf378af94
<ide><path>airflow/models/taskinstance.py <ide> def set_duration(self) -> None: <ide> self.duration = None <ide> self.log.debug("Task Duration set to %s", self.duration) <ide> <add> @provide_session <ide> def xcom_push( <del> self, <del> key: str, <del> value: Any, <del> execution_date: Optional[datetime] = None) -> None: <add> self, <add> key: str, <add> value: Any, <add> execution_date: Optional[datetime] = None, <add> session: Session = None, <add> ) -> None: <ide> """ <ide> Make an XCom available for tasks to pull. <ide> <ide> def xcom_push( <ide> this date. This can be used, for example, to send a message to a <ide> task on a future date without it being immediately visible. <ide> :type execution_date: datetime <add> :param session: Sqlalchemy ORM Session <add> :type session: Session <ide> """ <ide> if execution_date and execution_date < self.execution_date: <ide> raise ValueError( <ide> def xcom_push( <ide> value=value, <ide> task_id=self.task_id, <ide> dag_id=self.dag_id, <del> execution_date=execution_date or self.execution_date) <add> execution_date=execution_date or self.execution_date, <add> session=session, <add> ) <ide> <ide> @provide_session <ide> def xcom_pull( # pylint: disable=inconsistent-return-statements
1
Python
Python
add examples for np.arg[min|max|sort]
a94c15fcd6456c6df3a060a5fdae797649eb787e
<ide><path>numpy/core/fromnumeric.py <ide> def argsort(a, axis=-1, kind='quicksort', order=None): <ide> array([[0, 1], <ide> [0, 1]]) <ide> <add> Indices of the sorted elements of a N-dimensional array: <add> >>> np.unravel_index(np.argsort(x, axis=None), x.shape) <add> (array([0, 1, 1, 0]), array([0, 0, 1, 1])) <add> >>> from np.testing import assert_equal <add> >>> assert_equal(x[(array([0, 1, 1, 0]), array([0, 0, 1, 1]))], np.sort(x, axis=None)) <add> >>> list(zip(*np.unravel_index(np.argsort(x, axis=None), x.shape))) <add> [(0, 0), (1, 0), (1, 1), (0, 1)] <add> <ide> Sorting with keys: <ide> <ide> >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) <ide> def argmax(a, axis=None, out=None): <ide> >>> np.argmax(a, axis=1) <ide> array([2, 2]) <ide> <add> Indices of the maximal elements of a N-dimensional array: <add> >>> np.unravel_index(np.argmax(a, axis=None), a.shape) <add> (1, 2) <add> >>> np.testing.assert_equal(a[(1, 2)], np.max(a)) <add> <ide> >>> b = np.arange(6) <ide> >>> b[1] = 5 <ide> >>> b <ide> def argmin(a, axis=None, out=None): <ide> >>> np.argmin(a, axis=1) <ide> array([0, 0]) <ide> <add> Indices of the minimum elements of a N-dimensional array: <add> >>> np.unravel_index(np.argmin(a, axis=None), a.shape) <add> (0, 0) <add> >>> np.testing.assert_equal(a[(0, 0)], np.min(a)) <add> <ide> >>> b = np.arange(6) <ide> >>> b[4] = 0 <ide> >>> b
1
Ruby
Ruby
use arel for building the sti type condition
d200d080041bc4cefba8a8d39943b233ee2630a0
<ide><path>activerecord/lib/active_record/base.rb <ide> def array_of_strings?(o) <ide> o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)} <ide> end <ide> <del> def type_condition(table_alias=nil) <del> quoted_table_alias = self.connection.quote_table_name(table_alias || table_name) <del> quoted_inheritance_column = connection.quote_column_name(inheritance_column) <del> type_condition = subclasses.inject("#{quoted_table_alias}.#{quoted_inheritance_column} = '#{sti_name}' " ) do |condition, subclass| <del> condition << "OR #{quoted_table_alias}.#{quoted_inheritance_column} = '#{subclass.sti_name}' " <del> end <add> def type_condition(table_alias = nil) <add> table = Arel::Table.new(table_name, :engine => engine, :as => table_alias) <add> <add> sti_column = table[inheritance_column] <add> condition = sti_column.eq(sti_name) <add> subclasses.each{|subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) } <ide> <del> " (#{type_condition}) " <add> condition.to_sql <ide> end <ide> <ide> # Guesses the table name, but does not decorate it with prefix and suffix information.
1
Ruby
Ruby
fix syntax error
8116411abcb7dd887f06a1fe63885e105ea862e8
<ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb <ide> def test_has_many_through_obeys_order_on_through_association <ide> <ide> club.reload <ide> assert_equal [member], club.favourites <add> end <ide> <ide> def test_has_many_through_unscope_default_scope <ide> post = Post.create!(:title => 'Beaches', :body => "I like beaches!")
1
Java
Java
add missing variants of getbeannamesfortype
2ee1ce61c038c27fb163316961d3180de42f8297
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lb <ide> return result; <ide> } <ide> <add> /** <add> * Get all bean names for the given type, including those defined in ancestor <add> * factories. Will return unique names in case of overridden bean definitions. <add> * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" <add> * flag is set, which means that FactoryBeans will get initialized. If the <add> * object created by the FactoryBean doesn't match, the raw FactoryBean itself <add> * will be matched against the type. If "allowEagerInit" is not set, <add> * only raw FactoryBeans will be checked (which doesn't require initialization <add> * of each FactoryBean). <add> * @param lbf the bean factory <add> * @param includeNonSingletons whether to include prototype or scoped beans too <add> * or just singletons (also applies to FactoryBeans) <add> * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and <add> * <i>objects created by FactoryBeans</i> (or by factory methods with a <add> * "factory-bean" reference) for the type check. Note that FactoryBeans need to be <add> * eagerly initialized to determine their type: So be aware that passing in "true" <add> * for this flag will initialize FactoryBeans and "factory-bean" references. <add> * @param type the type that beans must match (as a {@code ResolvableType}) <add> * @return the array of matching bean names, or an empty array if none <add> * @since 5.2 <add> * @see ListableBeanFactory#getBeanNamesForType(ResolvableType, boolean, boolean) <add> */ <add> public static String[] beanNamesForTypeIncludingAncestors( <add> ListableBeanFactory lbf, ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { <add> <add> Assert.notNull(lbf, "ListableBeanFactory must not be null"); <add> String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); <add> if (lbf instanceof HierarchicalBeanFactory) { <add> HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; <add> if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { <add> String[] parentResult = beanNamesForTypeIncludingAncestors( <add> (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); <add> result = mergeNamesWithParent(result, parentResult, hbf); <add> } <add> } <add> return result; <add> } <add> <ide> /** <ide> * Get all bean names for the given type, including those defined in ancestor <ide> * factories. Will return unique names in case of overridden bean definitions. <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java <ide> public interface ListableBeanFactory extends BeanFactory { <ide> */ <ide> String[] getBeanNamesForType(ResolvableType type); <ide> <add> /** <add> * Return the names of beans matching the given type (including subclasses), <add> * judging from either bean definitions or the value of {@code getObjectType} <add> * in the case of FactoryBeans. <add> * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i> <add> * check nested beans which might match the specified type as well. <add> * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, <add> * which means that FactoryBeans will get initialized. If the object created by the <add> * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the <add> * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked <add> * (which doesn't require initialization of each FactoryBean). <add> * <p>Does not consider any hierarchy this factory may participate in. <add> * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors} <add> * to include beans in ancestor factories too. <add> * <p>Note: Does <i>not</i> ignore singleton beans that have been registered <add> * by other means than bean definitions. <add> * <p>Bean names returned by this method should always return bean names <i>in the <add> * order of definition</i> in the backend configuration, as far as possible. <add> * @param type the generically typed class or interface to match <add> * @param includeNonSingletons whether to include prototype or scoped beans too <add> * or just singletons (also applies to FactoryBeans) <add> * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and <add> * <i>objects created by FactoryBeans</i> (or by factory methods with a <add> * "factory-bean" reference) for the type check. Note that FactoryBeans need to be <add> * eagerly initialized to determine their type: So be aware that passing in "true" <add> * for this flag will initialize FactoryBeans and "factory-bean" references. <add> * @return the names of beans (or objects created by FactoryBeans) matching <add> * the given object type (including subclasses), or an empty array if none <add> * @since 5.2 <add> * @see FactoryBean#getObjectType <add> * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, ResolvableType, boolean, boolean) <add> */ <add> String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit); <add> <ide> /** <ide> * Return the names of beans matching the given type (including subclasses), <ide> * judging from either bean definitions or the value of {@code getObjectType} <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java <ide> public String[] getBeanDefinitionNames() { <ide> <ide> @Override <ide> public String[] getBeanNamesForType(ResolvableType type) { <add> return getBeanNamesForType(type, true, true); <add> } <add> <add> @Override <add> public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { <ide> Class<?> resolved = type.resolve(); <ide> if (resolved != null && !type.hasGenerics()) { <del> return getBeanNamesForType(resolved, true, true); <add> return getBeanNamesForType(resolved, includeNonSingletons, includeNonSingletons); <ide> } <ide> else { <del> return doGetBeanNamesForType(type, true, true); <add> return doGetBeanNamesForType(type, includeNonSingletons, includeNonSingletons); <ide> } <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public String[] getBeanDefinitionNames() { <ide> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable ResolvableType type) { <del> boolean isFactoryType = false; <del> if (type != null) { <del> Class<?> resolved = type.resolve(); <del> if (resolved != null && FactoryBean.class.isAssignableFrom(resolved)) { <del> isFactoryType = true; <del> } <del> } <add> return getBeanNamesForType(type, true, true); <add> } <add> <add> <add> @Override <add> public String[] getBeanNamesForType(@Nullable ResolvableType type, <add> boolean includeNonSingletons, boolean allowEagerInit) { <add> <add> Class<?> resolved = (type != null ? type.resolve() : null); <add> boolean isFactoryType = resolved != null && FactoryBean.class.isAssignableFrom(resolved); <ide> List<String> matches = new ArrayList<>(); <add> <ide> for (Map.Entry<String, Object> entry : this.beans.entrySet()) { <del> String name = entry.getKey(); <add> String beanName = entry.getKey(); <ide> Object beanInstance = entry.getValue(); <ide> if (beanInstance instanceof FactoryBean && !isFactoryType) { <del> Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType(); <del> if (objectType != null && (type == null || type.isAssignableFrom(objectType))) { <del> matches.add(name); <add> FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance; <add> Class<?> objectType = factoryBean.getObjectType(); <add> if ((includeNonSingletons || factoryBean.isSingleton()) && <add> objectType != null && (type == null || type.isAssignableFrom(objectType))) { <add> matches.add(beanName); <ide> } <ide> } <ide> else { <ide> if (type == null || type.isInstance(beanInstance)) { <del> matches.add(name); <add> matches.add(beanName); <ide> } <ide> } <ide> } <ide> public String[] getBeanNamesForType(@Nullable Class<?> type) { <ide> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { <del> return getBeanNamesForType(ResolvableType.forClass(type)); <add> return getBeanNamesForType(ResolvableType.forClass(type), includeNonSingletons, allowEagerInit); <ide> } <ide> <ide> @Override <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java <ide> public void testGetBeanWithArgsNotCreatedForFactoryBeanChecking() { <ide> assertThat(lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length).isEqualTo(1); <ide> assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)).length).isEqualTo(1); <ide> assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)).length).isEqualTo(0); <add> assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class), true, true).length).isEqualTo(1); <add> assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class), true, true).length).isEqualTo(0); <ide> } <ide> <ide> private RootBeanDefinition createConstructorDependencyBeanDefinition(int age) { <ide><path>spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java <ide> public String[] getBeanNamesForType(ResolvableType type) { <ide> return getBeanFactory().getBeanNamesForType(type); <ide> } <ide> <add> @Override <add> public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { <add> assertBeanFactoryActive(); <add> return getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit); <add> } <add> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable Class<?> type) { <ide> assertBeanFactoryActive(); <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java <ide> public String[] getBeanNamesForType(@Nullable ResolvableType type) { <ide> return this.beanFactory.getBeanNamesForType(type); <ide> } <ide> <add> @Override <add> public String[] getBeanNamesForType(@Nullable ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { <add> return this.beanFactory.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); <add> } <add> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable Class<?> type) { <ide> return this.beanFactory.getBeanNamesForType(type);
7
Javascript
Javascript
catch error in runaschild callback
449d1786c2e253f7f725bd85dc4f4246f81f397d
<ide><path>lib/Compiler.js <ide> class Compiler { <ide> */ <ide> runAsChild(callback) { <ide> const startTime = Date.now(); <add> <add> const finalCallback = (err, entries, compilation) => { <add> try { <add> if (err) return callback(err); <add> callback(null, entries, compilation); <add> } catch (e) { <add> const err = new WebpackError( <add> `compiler.runAsChild callback error: ${e}` <add> ); <add> this.parentCompilation.errors.push(err); <add> } <add> }; <add> <ide> this.compile((err, compilation) => { <del> if (err) return callback(err); <add> if (err) return finalCallback(err); <ide> <ide> this.parentCompilation.children.push(compilation); <ide> for (const { name, source, info } of compilation.getAssets()) { <ide> class Compiler { <ide> compilation.startTime = startTime; <ide> compilation.endTime = Date.now(); <ide> <del> return callback(null, entries, compilation); <add> return finalCallback(null, entries, compilation); <ide> }); <ide> } <ide>
1
Python
Python
fix logic for determining dagrun states
24a7072990fb232a6fe23c9eb3fdb72ba0695c96
<ide><path>airflow/models.py <ide> def subdags(self): <ide> <ide> def get_active_runs(self): <ide> """ <del> Maintains and returns the currently active runs as a list of dates <add> Maintains and returns the currently active runs as a list of dates. <add> <add> A run is considered a SUCCESS if all of its root tasks either succeeded <add> or were skipped. <add> <add> A run is considered a FAILURE if any of its root tasks failed OR if <add> it is deadlocked, meaning no tasks can run. <ide> """ <ide> TI = TaskInstance <ide> session = settings.Session() <ide> def get_active_runs(self): <ide> .filter( <ide> DagRun.dag_id == self.dag_id, <ide> DagRun.state == State.RUNNING) <del> .all() <del> ) <add> .order_by(DagRun.execution_date) <add> .all()) <add> <add> task_instances = ( <add> session <add> .query(TI) <add> .filter( <add> TI.dag_id == self.dag_id, <add> TI.task_id.in_(self.active_task_ids), <add> TI.execution_date.in_(r.execution_date for r in active_runs) <add> ) <add> .all()) <add> <add> for ti in task_instances: <add> ti.task = self.get_task(ti.task_id) <add> <add> # Runs are considered deadlocked if there are unfinished tasks but <add> # none of them can run. First we check across *all* dagruns in case <add> # there are depends_on_past relationships which could make individual <add> # dags look deadlocked incorrectly. Later we will check individual <add> # dagruns, as long as they don't have depends_on_past=True <add> all_deadlocked = ( <add> # AND there are unfinished tasks... <add> any(ti.state in State.unfinished() for ti in task_instances) and <add> # AND none of them have dependencies met... <add> all(not ti.are_dependencies_met() for ti in task_instances <add> if ti.state in State.unfinished()) <add> ) <add> <add> <ide> for run in active_runs: <ide> self.logger.info("Checking state for {}".format(run)) <del> task_instances = session.query(TI).filter( <del> TI.dag_id == run.dag_id, <del> TI.task_id.in_(self.active_task_ids), <del> TI.execution_date == run.execution_date, <del> ).all() <del> if len(task_instances) == len(self.active_tasks): <del> task_states = [ti.state for ti in task_instances] <del> if State.FAILED in task_states: <add> <add> tis = [ <add> t for t in task_instances <add> if t.execution_date == run.execution_date <add> ] <add> <add> if len(tis) == len(self.active_tasks): <add> <add> # if any roots failed, the run failed <add> root_ids = [t.task_id for t in self.roots] <add> roots = [t for t in tis if t.task_id in root_ids] <add> if any( <add> r.state in (State.FAILED, State.UPSTREAM_FAILED) <add> for r in roots): <ide> self.logger.info('Marking run {} failed'.format(run)) <ide> run.state = State.FAILED <del> elif len( <del> set(task_states) | <del> set([State.SUCCESS, State.SKIPPED]) <del> ) == 2: <add> <add> # if all roots succeeded, the run succeeded <add> elif all( <add> r.state in (State.SUCCESS, State.SKIPPED) <add> for r in roots): <ide> self.logger.info('Marking run {} successful'.format(run)) <ide> run.state = State.SUCCESS <add> <add> # if *the individual dagrun* is deadlocked, the run failed <add> elif ( <add> # there are unfinished tasks <add> any(t.state in State.unfinished() for t in tis) and <add> # AND none of them depend on past <add> all(not t.task.depends_on_past for t in tis <add> if t.state in State.unfinished()) and <add> # AND none of their dependencies are met <add> all(not t.are_dependencies_met() for t in tis <add> if t.state in State.unfinished()) <add> ): <add> self.logger.info( <add> 'Deadlock; marking run {} failed'.format(run)) <add> run.state = State.FAILED <add> <add> # if *ALL* dagruns are deadlocked, the run failed <add> elif all_deadlocked: <add> self.logger.info( <add> 'Deadlock; marking run {} failed'.format(run)) <add> run.state = State.FAILED <add> <add> # finally, if the roots aren't done, the dag is still running <ide> else: <ide> active_dates.append(run.execution_date) <ide> else:
1
Text
Text
add note for using `getstaticprops` with `404.js`
006eba32256ef67b1fa9cb0b466effca249b1921
<ide><path>docs/advanced-features/custom-error-page.md <ide> export default function Custom404() { <ide> } <ide> ``` <ide> <add>> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) inside this page if you need to fetch data at build time. <add> <ide> ## 500 Page <ide> <ide> By default Next.js provides a 500 error page that matches the default 404 page’s style. This page is not statically optimized as it allows server-side errors to be reported. This is why 404 and 500 (other errors) are separated.
1
Go
Go
use prefix naming for rmi tests
2e2422b0eb163829127692250973472456d0ed77
<ide><path>integration-cli/docker_cli_rmi_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <del>func TestImageRemoveWithContainerFails(t *testing.T) { <add>func TestRmiWithContainerFails(t *testing.T) { <ide> errSubstr := "is using it" <ide> <ide> // create a container <ide> func TestImageRemoveWithContainerFails(t *testing.T) { <ide> logDone("rmi- container using image while rmi, should not remove image name") <ide> } <ide> <del>func TestImageTagRemove(t *testing.T) { <add>func TestRmiTag(t *testing.T) { <ide> imagesBefore, _, _ := cmd(t, "images", "-a") <ide> cmd(t, "tag", "busybox", "utest:tag1") <ide> cmd(t, "tag", "busybox", "utest/docker:tag2")
1
Javascript
Javascript
remove undocumented .onclose property
6da82b1057afb4dbc94e3eada224dfdb97d6a533
<ide><path>lib/internal/worker/io.js <ide> Object.defineProperty(MessagePort.prototype, onInitSymbol, { <ide> <ide> // This is called after the underlying `uv_async_t` has been closed. <ide> function onclose() { <del> if (typeof this.onclose === 'function') { <del> // Not part of the Web standard yet, but there aren't many reasonable <del> // alternatives in a non-EventEmitter usage setting. <del> // Refs: https://github.com/whatwg/html/issues/1766 <del> this.onclose(); <del> } <ide> this.emit('close'); <ide> } <ide>
1
PHP
PHP
support empty strings
871fca6144fabc08c6ebf892098c1d8c8ea8140a
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> protected function compileExtensions($value) <ide> protected function compileStatements($value) <ide> { <ide> return preg_replace_callback( <del> '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>\'[^\']+\') | (?>"[^"]+") | (?>[^()\'"]+) | (?3) )* \))?/x', function ($match) { <add> '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>\'[^\']*\') | (?>"[^"]*") | (?>[^()\'"]+) | (?3) )* \))?/x', function ($match) { <ide> return $this->compileStatement($match); <ide> }, $value <ide> ); <ide><path>tests/View/Blade/BladePhpStatementsTest.php <ide> public function testStringWithParenthesisDataValue() <ide> <ide> $this->assertEquals($expected, $this->compiler->compileString($string)); <ide> } <add> <add> public function testStringWithEmptyStringDataValue() <add> { <add> $string = "@php(\$data = ['test' => ''])"; <add> <add> $expected = "<?php (\$data = ['test' => '']); ?>"; <add> <add> $this->assertEquals($expected, $this->compiler->compileString($string)); <add> <add> $string = "@php(\$data = ['test' => \"\"])"; <add> <add> $expected = "<?php (\$data = ['test' => \"\"]); ?>"; <add> <add> $this->assertEquals($expected, $this->compiler->compileString($string)); <add> } <ide> }
2
PHP
PHP
use less strictness where necessary
177136c6bc288e6c0f9d9e790273f27b455fea10
<ide><path>src/Database/Query.php <ide> class Query implements ExpressionInterface, IteratorAggregate <ide> /** <ide> * Statement object resulting from executing this query. <ide> * <del> * @var \Cake\Database\StatementInterface <add> * @var \Cake\Database\StatementInterface|null <ide> */ <del> protected $_iterator; <add> protected $_iterator = null; <ide> <ide> /** <ide> * The object responsible for generating query placeholders and temporarily store values <ide> * associated to each of those. <ide> * <del> * @var \Cake\Database\ValueBinder <add> * @var \Cake\Database\ValueBinder|null <ide> */ <del> protected $_valueBinder; <add> protected $_valueBinder = null; <ide> <ide> /** <ide> * Instance of functions builder object used for generating arbitrary SQL functions. <ide> * <del> * @var \Cake\Database\FunctionsBuilder <add> * @var \Cake\Database\FunctionsBuilder|null <ide> */ <del> protected $_functionsBuilder; <add> protected $_functionsBuilder = null; <ide> <ide> /** <ide> * Boolean for tracking whether or not buffered results <ide><path>src/View/View.php <ide> public function __construct( <ide> $this->eventManager($eventManager); <ide> $this->request = $request ?: Router::getRequest(true); <ide> $this->response = $response ?: new Response(); <del> if ($this->request === null) { <add> if (!$this->request) { <ide> $this->request = new ServerRequest([ <ide> 'base' => '', <ide> 'url' => '',
2
Javascript
Javascript
add tests for push stream error handling
1aca135cb9a8cacda5d01206d7a8e4a31c521d44
<ide><path>lib/internal/http2/core.js <ide> class ServerHttp2Stream extends Http2Stream { <ide> break; <ide> case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: <ide> err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS'); <del> process.nextTick(() => this.emit('error', err)); <add> process.nextTick(() => session.emit('error', err)); <ide> break; <ide> case NGHTTP2_ERR_STREAM_CLOSED: <ide> err = new errors.Error('ERR_HTTP2_STREAM_CLOSED'); <ide><path>test/parallel/test-http2-server-push-stream-errors-args.js <add>// Flags: --expose-http2 <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add>const assert = require('assert'); <add>const http2 = require('http2'); <add> <add>// Check that pushStream handles being passed wrong arguments <add>// in the expected manner <add> <add>const server = http2.createServer(); <add>server.on('stream', common.mustCall((stream, headers) => { <add> const port = server.address().port; <add> <add> // Must receive a callback (function) <add> common.expectsError( <add> () => stream.pushStream({ <add> ':scheme': 'http', <add> ':path': '/foobar', <add> ':authority': `localhost:${port}`, <add> }, {}, 'callback'), <add> { <add> code: 'ERR_INVALID_CALLBACK', <add> message: 'Callback must be a function' <add> } <add> ); <add> <add> // Must validate headers <add> common.expectsError( <add> () => stream.pushStream({ 'connection': 'test' }, {}, () => {}), <add> { <add> code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', <add> message: 'HTTP/1 Connection specific headers are forbidden' <add> } <add> ); <add> <add> stream.end('test'); <add>})); <add> <add>server.listen(0, common.mustCall(() => { <add> const port = server.address().port; <add> const headers = { ':path': '/' }; <add> const client = http2.connect(`http://localhost:${port}`); <add> const req = client.request(headers); <add> req.setEncoding('utf8'); <add> <add> let data = ''; <add> req.on('data', common.mustCall((d) => data += d)); <add> req.on('end', common.mustCall(() => { <add> assert.strictEqual(data, 'test'); <add> server.close(); <add> client.destroy(); <add> })); <add> req.end(); <add>})); <ide><path>test/parallel/test-http2-server-push-stream-errors.js <add>// Flags: --expose-http2 <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add>const http2 = require('http2'); <add>const { <add> constants, <add> Http2Session, <add> nghttp2ErrorString <add>} = process.binding('http2'); <add> <add>// tests error handling within pushStream <add>// - NGHTTP2_ERR_NOMEM (should emit session error) <add>// - NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE (should emit session error) <add>// - NGHTTP2_ERR_STREAM_CLOSED (should emit stream error) <add>// - every other NGHTTP2 error from binding (should emit stream error) <add> <add>const specificTestKeys = [ <add> 'NGHTTP2_ERR_NOMEM', <add> 'NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE', <add> 'NGHTTP2_ERR_STREAM_CLOSED' <add>]; <add> <add>const specificTests = [ <add> { <add> ngError: constants.NGHTTP2_ERR_NOMEM, <add> error: { <add> code: 'ERR_OUTOFMEMORY', <add> type: Error, <add> message: 'Out of memory' <add> }, <add> type: 'session' <add> }, <add> { <add> ngError: constants.NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE, <add> error: { <add> code: 'ERR_HTTP2_OUT_OF_STREAMS', <add> type: Error, <add> message: 'No stream ID is available because ' + <add> 'maximum stream ID has been reached' <add> }, <add> type: 'session' <add> }, <add> { <add> ngError: constants.NGHTTP2_ERR_STREAM_CLOSED, <add> error: { <add> code: 'ERR_HTTP2_STREAM_CLOSED', <add> type: Error, <add> message: 'The stream is already closed' <add> }, <add> type: 'stream' <add> }, <add>]; <add> <add>const genericTests = Object.getOwnPropertyNames(constants) <add> .filter((key) => ( <add> key.indexOf('NGHTTP2_ERR') === 0 && specificTestKeys.indexOf(key) < 0 <add> )) <add> .map((key) => ({ <add> ngError: constants[key], <add> error: { <add> code: 'ERR_HTTP2_ERROR', <add> type: Error, <add> message: nghttp2ErrorString(constants[key]) <add> }, <add> type: 'stream' <add> })); <add> <add> <add>const tests = specificTests.concat(genericTests); <add> <add>let currentError; <add> <add>// mock submitPushPromise because we only care about testing error handling <add>Http2Session.prototype.submitPushPromise = () => currentError.ngError; <add> <add>const server = http2.createServer(); <add>server.on('stream', common.mustCall((stream, headers) => { <add> const errorMustCall = common.expectsError(currentError.error); <add> const errorMustNotCall = common.mustNotCall( <add> `${currentError.error.code} should emit on ${currentError.type}` <add> ); <add> console.log(currentError); <add> <add> if (currentError.type === 'stream') { <add> stream.session.on('error', errorMustNotCall); <add> stream.on('error', errorMustCall); <add> stream.on('error', common.mustCall(() => { <add> stream.respond(); <add> stream.end(); <add> })); <add> } else { <add> stream.session.once('error', errorMustCall); <add> stream.on('error', errorMustNotCall); <add> } <add> <add> stream.pushStream({}, () => {}); <add>}, tests.length)); <add> <add>server.listen(0, common.mustCall(() => runTest(tests.shift()))); <add> <add>function runTest(test) { <add> const port = server.address().port; <add> const url = `http://localhost:${port}`; <add> const headers = { <add> ':path': '/', <add> ':method': 'POST', <add> ':scheme': 'http', <add> ':authority': `localhost:${port}` <add> }; <add> <add> const client = http2.connect(url); <add> const req = client.request(headers); <add> <add> currentError = test; <add> req.resume(); <add> req.end(); <add> <add> req.on('end', common.mustCall(() => { <add> client.destroy(); <add> <add> if (!tests.length) { <add> server.close(); <add> } else { <add> runTest(tests.shift()); <add> } <add> })); <add>} <ide><path>test/parallel/test-http2-server-push-stream-head.js <add>// Flags: --expose-http2 <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add>const assert = require('assert'); <add>const http2 = require('http2'); <add> <add>// Check that pushStream handles method HEAD correctly <add>// - stream should end immediately (no body) <add> <add>const server = http2.createServer(); <add>server.on('stream', common.mustCall((stream, headers) => { <add> const port = server.address().port; <add> if (headers[':path'] === '/') { <add> stream.pushStream({ <add> ':scheme': 'http', <add> ':method': 'HEAD', <add> ':authority': `localhost:${port}`, <add> }, common.mustCall((push, headers) => { <add> assert.strictEqual(push._writableState.ended, true); <add> stream.end('test'); <add> })); <add> } <add> stream.respond({ <add> 'content-type': 'text/html', <add> ':status': 200 <add> }); <add>})); <add> <add>server.listen(0, common.mustCall(() => { <add> const port = server.address().port; <add> const headers = { ':path': '/' }; <add> const client = http2.connect(`http://localhost:${port}`); <add> const req = client.request(headers); <add> req.setEncoding('utf8'); <add> <add> client.on('stream', common.mustCall((stream, headers) => { <add> assert.strictEqual(headers[':scheme'], 'http'); <add> assert.strictEqual(headers[':path'], '/'); <add> assert.strictEqual(headers[':authority'], `localhost:${port}`); <add> })); <add> <add> let data = ''; <add> <add> req.on('data', common.mustCall((d) => data += d)); <add> req.on('end', common.mustCall(() => { <add> assert.strictEqual(data, 'test'); <add> server.close(); <add> client.destroy(); <add> })); <add> req.end(); <add>})); <ide><path>test/parallel/test-http2-server-push-stream.js <ide> server.on('stream', common.mustCall((stream, headers) => { <ide> ':scheme': 'http', <ide> ':path': '/foobar', <ide> ':authority': `localhost:${port}`, <del> }, (push, headers) => { <add> }, common.mustCall((push, headers) => { <ide> push.respond({ <ide> 'content-type': 'text/html', <ide> ':status': 200, <ide> 'x-push-data': 'pushed by server', <ide> }); <ide> push.end('pushed by server data'); <ide> stream.end('test'); <del> }); <add> })); <ide> } <ide> stream.respond({ <ide> 'content-type': 'text/html',
5
Ruby
Ruby
enable query cache on all connection pools
11e32c1d841c08bd85842eb059fbf30536e804dc
<ide><path>activerecord/lib/active_record/query_cache.rb <ide> def uncached(&block) <ide> end <ide> <ide> def self.run <del> caching_pool = ActiveRecord::Base.connection_pool <del> caching_was_enabled = caching_pool.query_cache_enabled <add> ActiveRecord::Base.connection_handler.connection_pool_list.map do |pool| <add> caching_was_enabled = pool.query_cache_enabled <ide> <del> caching_pool.enable_query_cache! <add> pool.enable_query_cache! <ide> <del> [caching_pool, caching_was_enabled] <add> [pool, caching_was_enabled] <add> end <ide> end <ide> <del> def self.complete((caching_pool, caching_was_enabled)) <del> caching_pool.disable_query_cache! unless caching_was_enabled <add> def self.complete(caching_pools) <add> caching_pools.each do |pool, caching_was_enabled| <add> pool.disable_query_cache! unless caching_was_enabled <add> end <ide> <ide> ActiveRecord::Base.connection_handler.connection_pool_list.each do |pool| <ide> pool.release_connection if pool.active_connection? && !pool.connection.transaction_open? <ide><path>activerecord/test/cases/query_cache_test.rb <ide> def test_query_caching_is_local_to_the_current_thread <ide> end <ide> end <ide> <add> def test_query_cache_is_enabled_on_all_connection_pools <add> middleware { <add> ActiveRecord::Base.connection_handler.connection_pool_list.each do |pool| <add> assert pool.query_cache_enabled <add> assert pool.connection.query_cache_enabled <add> end <add> }.call({}) <add> end <add> <ide> private <ide> def middleware(&app) <ide> executor = Class.new(ActiveSupport::Executor)
2
Ruby
Ruby
update string references to mxcl/homebrew
d7c13f84b62d730389e72cf4283da1863993be5f
<ide><path>Library/Contributions/cmd/brew-pull.rb <ide> def tap arg <ide> <ide> ARGV.named.each do|arg| <ide> if arg.to_i > 0 <del> url = 'https://github.com/mxcl/homebrew/pull/' + arg <add> url = 'https://github.com/Homebrew/homebrew/pull/' + arg <ide> else <ide> url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX <ide> unless url_match <ide><path>Library/Contributions/cmd/brew-tap-readme.rb <ide> -------------------------------- <ide> Just `brew tap homebrew/#{name}` and then `brew install <formula>`. <ide> <del>If the formula conflicts with one from mxcl/master or another tap, you can `brew install homebrew/#{name}/<formula>`. <add>If the formula conflicts with one from Homebrew/homebrew or another tap, you can `brew install homebrew/#{name}/<formula>`. <ide> <ide> You can also install via URL: <ide> <ide> ---- <ide> `brew help`, `man brew`, or the Homebrew [wiki][]. <ide> <del>[wiki]:http://wiki.github.com/mxcl/homebrew <add>[wiki]:http://wiki.github.com/Homebrew/homebrew <ide> EOS <ide> <ide> # puts ERB.new(template, nil, '>').result(binding) <ide><path>Library/Homebrew/cmd/help.rb <ide> Brewing: <ide> brew create [URL [--no-fetch]] <ide> brew edit [FORMULA...] <del> open https://github.com/mxcl/homebrew/wiki/Formula-Cookbook <add> open https://github.com/Homebrew/homebrew/wiki/Formula-Cookbook <ide> <ide> Further help: <ide> man brew <ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(f, dep, wrong, right) <ide> to build #{f}: #{right.type_string} (from #{right.compiler}) <ide> <ide> Please reinstall #{dep} using a compatible compiler. <del> hint: Check https://github.com/mxcl/homebrew/wiki/C++-Standard-Libraries <add> hint: Check https://github.com/Homebrew/homebrew/wiki/C++-Standard-Libraries <ide> EOS <ide> end <ide> end <ide> def dump <ide> if formula.tap? <ide> user, repo = formula.tap.split '/' <ide> tap_issues_url = "https://github.com/#{user}/homebrew-#{repo}/issues" <del> puts "If reporting this issue please do so at (not mxcl/homebrew):" <add> puts "If reporting this issue please do so at (not Homebrew/homebrew):" <ide> puts " #{tap_issues_url}" <ide> end <ide> else <ide><path>Library/Homebrew/global.rb <ide> module Homebrew extend self <ide> <ide> require 'metafiles' <ide> FORMULA_META_FILES = Metafiles.new <del>ISSUES_URL = "https://github.com/mxcl/homebrew/wiki/troubleshooting" <add>ISSUES_URL = "https://github.com/Homebrew/homebrew/wiki/troubleshooting" <ide> HOMEBREW_PULL_OR_COMMIT_URL_REGEX = 'https:\/\/github.com\/(\w+)\/homebrew(-\w+)?\/(pull\/(\d+)|commit\/\w{4,40})' <ide> <ide> require 'compat' unless ARGV.include? "--no-compat" or ENV['HOMEBREW_NO_COMPAT'] <ide><path>Library/Homebrew/os/mac.rb <ide> def compilers_standard? <ide> Homebrew doesn't know what compiler versions ship with your version <ide> of Xcode (#{Xcode.version}). Please `brew update` and if that doesn't help, file <ide> an issue with the output of `brew --config`: <del> https://github.com/mxcl/homebrew/issues <add> https://github.com/Homebrew/homebrew/issues <ide> <ide> Thanks! <ide> EOS <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_formula_spec_integration <ide> mirror 'file:///foo.org/testball-0.1.tbz' <ide> sha1 TEST_SHA1 <ide> <del> head 'https://github.com/mxcl/homebrew.git', :tag => 'foo' <add> head 'https://github.com/Homebrew/homebrew.git', :tag => 'foo' <ide> <ide> devel do <ide> url 'file:///foo.com/testball-0.2.tbz'
7
PHP
PHP
support old namespace for now
b800fa6c7c0c295ec266db0df9bfafb6fad2880e
<ide><path>src/Mailer/Email.php <ide> protected function _constructTransport($name) <ide> } <ide> <ide> $className = App::className($config['className'], 'Mailer/Transport', 'Transport'); <add> if (!$className) { <add> $className = App::className($config['className'], 'Network/Email', 'Transport'); <add> } <add> <ide> if (!$className) { <ide> throw new InvalidArgumentException(sprintf('Transport class "%s" not found.', $name)); <ide> } elseif (!method_exists($className, 'send')) {
1
Python
Python
raise memory limit for test
518edc70744faa0bd1443c9f9ce76a1c01d7749e
<ide><path>numpy/lib/tests/test_io.py <ide> def test_unicode_and_bytes_fmt(self, fmt, iotype): <ide> <ide> @pytest.mark.skipif(sys.platform=='win32', reason="files>4GB may not work") <ide> @pytest.mark.slow <del> @requires_memory(free_bytes=7e9) <add> @requires_memory(free_bytes=8e9) <ide> def test_large_zip(self): <ide> def check_large_zip(memoryerror_raised): <ide> memoryerror_raised.value = False
1
PHP
PHP
add some filesystem tests
c3eb81c341d5be7df1df22acd03e5ba748c07044
<ide><path>tests/Filesystem/FilesystemTest.php <ide> <ide> namespace Illuminate\Tests\Filesystem; <ide> <add>use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <ide> use League\Flysystem\Adapter\Ftp; <ide> use Illuminate\Filesystem\Filesystem; <ide> public function setUp() <ide> <ide> public function tearDown() <ide> { <add> m::close(); <add> <ide> $files = new Filesystem; <ide> $files->deleteDirectory($this->tempDir); <ide> } <ide> public function testDeleteDirectory() <ide> $this->assertFileNotExists($this->tempDir.'/foo/file.txt'); <ide> } <ide> <add> public function testDeleteDirectoryReturnFalseWhenNotADirectory() <add> { <add> mkdir($this->tempDir.'/foo'); <add> file_put_contents($this->tempDir.'/foo/file.txt', 'Hello World'); <add> $files = new Filesystem; <add> $this->assertFalse($files->deleteDirectory($this->tempDir.'/foo/file.txt')); <add> } <add> <ide> public function testCleanDirectory() <ide> { <ide> mkdir($this->tempDir.'/foo'); <ide> public function testMoveDirectoryMovesEntireDirectoryAndOverwrites() <ide> $this->assertFalse(is_dir($this->tempDir.'/tmp')); <ide> } <ide> <add> public function testMoveDirectoryReturnsFalseWhileOverwritingAndUnableToDeleteDestinationDirectory() <add> { <add> mkdir($this->tempDir.'/tmp', 0777, true); <add> file_put_contents($this->tempDir.'/tmp/foo.txt', ''); <add> mkdir($this->tempDir.'/tmp2', 0777, true); <add> <add> $files = m::mock(Filesystem::class)->makePartial(); <add> $files->shouldReceive('deleteDirectory')->andReturn(false); <add> $this->assertFalse($files->moveDirectory($this->tempDir.'/tmp', $this->tempDir.'/tmp2', true)); <add> } <add> <ide> /** <ide> * @expectedException \Illuminate\Contracts\Filesystem\FileNotFoundException <ide> */ <ide> public function testMoveMovesFiles() <ide> $this->assertFileNotExists($this->tempDir.'/foo.txt'); <ide> } <ide> <add> public function testNameReturnsName() <add> { <add> file_put_contents($this->tempDir.'/foobar.txt', 'foo'); <add> $filesystem = new Filesystem; <add> $this->assertEquals('foobar', $filesystem->name($this->tempDir.'/foobar.txt')); <add> } <add> <ide> public function testExtensionReturnsExtension() <ide> { <ide> file_put_contents($this->tempDir.'/foo.txt', 'foo'); <ide> public function testCreateFtpDriver() <ide> $this->assertEquals('ftp.example.com', $adapter->getHost()); <ide> $this->assertEquals('admin', $adapter->getUsername()); <ide> } <add> <add> public function testHash() <add> { <add> file_put_contents($this->tempDir.'/foo.txt', 'foo'); <add> $filesystem = new Filesystem; <add> $this->assertEquals('acbd18db4cc2f85cedef654fccc4a4d8', $filesystem->hash($this->tempDir.'/foo.txt')); <add> } <ide> }
1
Java
Java
extend annotationmetadata and methodmetadata
8e445f3a211395d43895f747d04158ff7f9c0913
<ide><path>spring-core/src/main/java/org/springframework/core/type/AnnotatedElementUtils.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.core.type; <add> <add>import java.lang.annotation.Annotation; <add>import java.lang.reflect.AnnotatedElement; <add>import java.util.HashSet; <add>import java.util.LinkedHashSet; <add>import java.util.Map; <add>import java.util.Set; <add> <add>import org.springframework.core.annotation.AnnotationUtils; <add>import org.springframework.util.LinkedMultiValueMap; <add>import org.springframework.util.MultiValueMap; <add> <add>/** <add> * Internal utility class used to collect all annotation values including those declared <add> * on meta-annotations. <add> * <add> * @author Phillip Webb <add> * @since 4.0 <add> */ <add>class AnnotatedElementUtils { <add> <add> public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, <add> String annotationType) { <add> final Set<String> types = new LinkedHashSet<String>(); <add> process(element, annotationType, new Processor<Object>() { <add> public Object process(Annotation annotation, int depth) { <add> if (depth > 0) { <add> types.add(annotation.annotationType().getName()); <add> } <add> return null; <add> } <add> }); <add> return (types.size() == 0 ? null : types); <add> } <add> <add> public static boolean hasMetaAnnotationTypes(AnnotatedElement element, <add> String annotationType) { <add> return Boolean.TRUE.equals( <add> process(element, annotationType, new Processor<Boolean>() { <add> public Boolean process(Annotation annotation, int depth) { <add> if (depth > 0) { <add> return true; <add> } <add> return null; <add> } <add> })); <add> } <add> <add> public static boolean isAnnotated(AnnotatedElement element, String annotationType) { <add> return Boolean.TRUE.equals( <add> process(element, annotationType, new Processor<Boolean>() { <add> public Boolean process(Annotation annotation, int depth) { <add> return true; <add> } <add> })); <add> } <add> <add> public static Map<String, Object> getAnnotationAttributes(AnnotatedElement element, <add> String annotationType, final boolean classValuesAsString, <add> final boolean nestedAnnotationsAsMap) { <add> return process(element, annotationType, new Processor<Map<String, Object>>() { <add> public Map<String, Object> process(Annotation annotation, int depth) { <add> return AnnotationUtils.getAnnotationAttributes(annotation, <add> classValuesAsString, nestedAnnotationsAsMap); <add> } <add> }); <add> } <add> <add> public static MultiValueMap<String, Object> getAllAnnotationAttributes( <add> AnnotatedElement element, final String annotationType, <add> final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) { <add> final MultiValueMap<String, Object> attributes = new LinkedMultiValueMap<String, Object>(); <add> process(element, annotationType, new Processor<Object>() { <add> public Object process(Annotation annotation, int depth) { <add> if (annotation.annotationType().getName().equals(annotationType)) { <add> for (Map.Entry<String, Object> entry : AnnotationUtils.getAnnotationAttributes( <add> annotation, classValuesAsString, nestedAnnotationsAsMap).entrySet()) { <add> attributes.add(entry.getKey(), entry.getValue()); <add> } <add> } <add> return null; <add> } <add> }); <add> return (attributes.size() == 0 ? null : attributes); <add> } <add> <add> /** <add> * Process all annotations of the specified annotation type and recursively all <add> * meta-annotations on the specified type. <add> * @param element the annotated element <add> * @param annotationType the annotation type to find. Only items of the specified type <add> * or meta-annotations of the specified type will be processed <add> * @param processor the processor <add> * @return the result of the processor <add> */ <add> private static <T> T process(AnnotatedElement element, String annotationType, <add> Processor<T> processor) { <add> return recursivelyProcess(element, annotationType, processor, <add> new HashSet<AnnotatedElement>(), 0); <add> } <add> <add> private static <T> T recursivelyProcess(AnnotatedElement element, <add> String annotationType, Processor<T> processor, Set<AnnotatedElement> visited, <add> int depth) { <add> T result = null; <add> if (visited.add(element)) { <add> for (Annotation annotation : element.getAnnotations()) { <add> if (annotation.annotationType().getName().equals(annotationType) || depth > 0) { <add> result = result != null ? result : <add> processor.process(annotation, depth); <add> result = result != null ? result : <add> recursivelyProcess(annotation.annotationType(), annotationType, <add> processor, visited, depth + 1); <add> } <add> } <add> for (Annotation annotation : element.getAnnotations()) { <add> result = result != null ? result : <add> recursivelyProcess(annotation.annotationType(), annotationType, <add> processor, visited, depth); <add> } <add> <add> } <add> return result; <add> } <add> <add> /** <add> * Callback interface used to process an annotation. <add> * @param <T> the result type <add> */ <add> private static interface Processor<T> { <add> <add> /** <add> * Called to process the annotation. <add> * @param annotation the annotation to process <add> * @param depth the depth of the annotation relative to the initial match. For <add> * example a matched annotation will have a depth of 0, a meta-annotation 1 <add> * and a meta-meta-annotation 2 <add> * @return the result of the processing or {@code null} to continue <add> */ <add> T process(Annotation annotation, int depth); <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/core/type/AnnotatedTypeMetadata.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.core.type; <add> <add>import java.util.Map; <add> <add>import org.springframework.util.MultiValueMap; <add> <add>/** <add> * Defines access to the annotations of a specific type ({@link AnnotationMetadata class} <add> * or {@link MethodMetadata method}), in a form that does not necessarily require the <add> * class-loading. <add> * <add> * @author Juergen Hoeller <add> * @author Mark Fisher <add> * @author Mark Pollack <add> * @author Chris Beams <add> * @author Phillip Webb <add> * @since 4.0 <add> * @see AnnotationMetadata <add> * @see MethodMetadata <add> */ <add>public interface AnnotatedTypeMetadata { <add> <add> /** <add> * Determine whether the underlying type has an annotation or <add> * meta-annotation of the given type defined. <add> * <p>If this method returns {@code true}, then <add> * {@link #getAnnotationAttributes} will return a non-null Map. <add> * @param annotationType the annotation type to look for <add> * @return whether a matching annotation is defined <add> */ <add> boolean isAnnotated(String annotationType); <add> <add> /** <add> * Retrieve the attributes of the annotation of the given type, <add> * if any (i.e. if defined on the underlying class, as direct <add> * annotation or as meta-annotation). <add> * @param annotationType the annotation type to look for <add> * @return a Map of attributes, with the attribute name as key (e.g. "value") <add> * and the defined attribute value as Map value. This return value will be <add> * {@code null} if no matching annotation is defined. <add> */ <add> Map<String, Object> getAnnotationAttributes(String annotationType); <add> <add> /** <add> * Retrieve the attributes of the annotation of the given type, <add> * if any (i.e. if defined on the underlying class, as direct <add> * annotation or as meta-annotation). <add> * @param annotationType the annotation type to look for <add> * @param classValuesAsString whether to convert class references to String <add> * class names for exposure as values in the returned Map, instead of Class <add> * references which might potentially have to be loaded first <add> * @return a Map of attributes, with the attribute name as key (e.g. "value") <add> * and the defined attribute value as Map value. This return value will be <add> * {@code null} if no matching annotation is defined. <add> */ <add> Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString); <add> <add> /** <add> * Retrieve all attributes of all annotations of the given type, if any (i.e. if <add> * defined on the underlying method, as direct annotation or as meta-annotation). <add> * @param annotationType the annotation type to look for <add> * @return a MultiMap of attributes, with the attribute name as key (e.g. "value") and <add> * a list of the defined attribute values as Map value. This return value will <add> * be {@code null} if no matching annotation is defined. <add> */ <add> MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType); <add> <add> /** <add> * Retrieve all attributes of all annotations of the given type, if any (i.e. if <add> * defined on the underlying method, as direct annotation or as meta-annotation). <add> * @param annotationType the annotation type to look for <add> * @param classValuesAsString whether to convert class references to String <add> * @return a MultiMap of attributes, with the attribute name as key (e.g. "value") and <add> * a list of the defined attribute values as Map value. This return value will <add> * be {@code null} if no matching annotation is defined. <add> * @see #getAllAnnotationAttributes(String) <add> */ <add> MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType, <add> boolean classValuesAsString); <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/core/type/AnnotationMetadata.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.core.type; <ide> <del>import java.util.Map; <ide> import java.util.Set; <ide> <ide> /** <ide> * <ide> * @author Juergen Hoeller <ide> * @author Mark Fisher <add> * @author Phillip Webb <ide> * @since 2.5 <ide> * @see StandardAnnotationMetadata <ide> * @see org.springframework.core.type.classreading.MetadataReader#getAnnotationMetadata() <add> * @see AnnotatedTypeMetadata <ide> */ <del>public interface AnnotationMetadata extends ClassMetadata { <add>public interface AnnotationMetadata extends ClassMetadata, AnnotatedTypeMetadata { <ide> <ide> /** <ide> * Return the names of all annotation types defined on the underlying class. <ide> public interface AnnotationMetadata extends ClassMetadata { <ide> */ <ide> boolean hasMetaAnnotation(String metaAnnotationType); <ide> <del> /** <del> * Determine whether the underlying class has an annotation or <del> * meta-annotation of the given type defined. <del> * <p>This is equivalent to a "hasAnnotation || hasMetaAnnotation" <del> * check. If this method returns {@code true}, then <del> * {@link #getAnnotationAttributes} will return a non-null Map. <del> * @param annotationType the annotation type to look for <del> * @return whether a matching annotation is defined <del> */ <del> boolean isAnnotated(String annotationType); <del> <del> /** <del> * Retrieve the attributes of the annotation of the given type, <del> * if any (i.e. if defined on the underlying class, as direct <del> * annotation or as meta-annotation). <del> * @param annotationType the annotation type to look for <del> * @return a Map of attributes, with the attribute name as key (e.g. "value") <del> * and the defined attribute value as Map value. This return value will be <del> * {@code null} if no matching annotation is defined. <del> */ <del> Map<String, Object> getAnnotationAttributes(String annotationType); <del> <del> /** <del> * Retrieve the attributes of the annotation of the given type, <del> * if any (i.e. if defined on the underlying class, as direct <del> * annotation or as meta-annotation). <del> * @param annotationType the annotation type to look for <del> * @param classValuesAsString whether to convert class references to String <del> * class names for exposure as values in the returned Map, instead of Class <del> * references which might potentially have to be loaded first <del> * @return a Map of attributes, with the attribute name as key (e.g. "value") <del> * and the defined attribute value as Map value. This return value will be <del> * {@code null} if no matching annotation is defined. <del> */ <del> Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString); <del> <ide> /** <ide> * Determine whether the underlying class has any methods that are <ide> * annotated (or meta-annotated) with the given annotation type. <ide><path>spring-core/src/main/java/org/springframework/core/type/MethodMetadata.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.core.type; <ide> <del>import java.util.Map; <del> <ide> /** <ide> * Interface that defines abstract access to the annotations of a specific <ide> * class, in a form that does not require that class to be loaded yet. <ide> * <ide> * @author Juergen Hoeller <ide> * @author Mark Pollack <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.0 <ide> * @see StandardMethodMetadata <ide> * @see AnnotationMetadata#getAnnotatedMethods <add> * @see AnnotatedTypeMetadata <ide> */ <del>public interface MethodMetadata { <add>public interface MethodMetadata extends AnnotatedTypeMetadata { <ide> <ide> /** <ide> * Return the name of the method. <ide> public interface MethodMetadata { <ide> */ <ide> boolean isOverridable(); <ide> <del> /** <del> * Determine whether the underlying method has an annotation or <del> * meta-annotation of the given type defined. <del> * @param annotationType the annotation type to look for <del> * @return whether a matching annotation is defined <del> */ <del> boolean isAnnotated(String annotationType); <del> <del> /** <del> * Retrieve the attributes of the annotation of the given type, <del> * if any (i.e. if defined on the underlying method, as direct <del> * annotation or as meta-annotation). <del> * @param annotationType the annotation type to look for <del> * @return a Map of attributes, with the attribute name as key (e.g. "value") <del> * and the defined attribute value as Map value. This return value will be <del> * {@code null} if no matching annotation is defined. <del> */ <del> Map<String, Object> getAnnotationAttributes(String annotationType); <del> <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/type/StandardAnnotationMetadata.java <ide> import java.util.Set; <ide> <ide> import org.springframework.core.annotation.AnnotationAttributes; <del>import org.springframework.core.annotation.AnnotationUtils; <add>import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> * {@link AnnotationMetadata} implementation that uses standard reflection <ide> * @author Juergen Hoeller <ide> * @author Mark Fisher <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 2.5 <ide> */ <ide> public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata { <ide> public Set<String> getAnnotationTypes() { <ide> } <ide> <ide> public Set<String> getMetaAnnotationTypes(String annotationType) { <del> Annotation[] anns = getIntrospectedClass().getAnnotations(); <del> for (Annotation ann : anns) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> Set<String> types = new LinkedHashSet<String>(); <del> Annotation[] metaAnns = ann.annotationType().getAnnotations(); <del> for (Annotation metaAnn : metaAnns) { <del> types.add(metaAnn.annotationType().getName()); <del> for (Annotation metaMetaAnn : metaAnn.annotationType().getAnnotations()) { <del> types.add(metaMetaAnn.annotationType().getName()); <del> } <del> } <del> return types; <del> } <del> } <del> return null; <add> return AnnotatedElementUtils.getMetaAnnotationTypes(getIntrospectedClass(), annotationType); <ide> } <ide> <ide> public boolean hasAnnotation(String annotationType) { <ide> public boolean hasAnnotation(String annotationType) { <ide> } <ide> <ide> public boolean hasMetaAnnotation(String annotationType) { <del> Annotation[] anns = getIntrospectedClass().getAnnotations(); <del> for (Annotation ann : anns) { <del> Annotation[] metaAnns = ann.annotationType().getAnnotations(); <del> for (Annotation metaAnn : metaAnns) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> for (Annotation metaMetaAnn : metaAnn.annotationType().getAnnotations()) { <del> if (metaMetaAnn.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> } <del> } <del> } <del> return false; <add> return AnnotatedElementUtils.hasMetaAnnotationTypes(getIntrospectedClass(), annotationType); <ide> } <ide> <ide> public boolean isAnnotated(String annotationType) { <del> Annotation[] anns = getIntrospectedClass().getAnnotations(); <del> for (Annotation ann : anns) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> } <del> } <del> return false; <add> return AnnotatedElementUtils.isAnnotated(getIntrospectedClass(), annotationType); <ide> } <ide> <ide> public Map<String, Object> getAnnotationAttributes(String annotationType) { <ide> return this.getAnnotationAttributes(annotationType, false); <ide> } <ide> <del> public Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString) { <del> Annotation[] anns = getIntrospectedClass().getAnnotations(); <del> for (Annotation ann : anns) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> return AnnotationUtils.getAnnotationAttributes( <del> ann, classValuesAsString, this.nestedAnnotationsAsMap); <del> } <del> } <del> for (Annotation ann : anns) { <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return AnnotationUtils.getAnnotationAttributes( <del> metaAnn, classValuesAsString, this.nestedAnnotationsAsMap); <del> } <del> } <del> } <del> return null; <add> public Map<String, Object> getAnnotationAttributes(String annotationType, <add> boolean classValuesAsString) { <add> return AnnotatedElementUtils.getAnnotationAttributes(getIntrospectedClass(), <add> annotationType, classValuesAsString, this.nestedAnnotationsAsMap); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType) { <add> return getAllAnnotationAttributes(annotationType, false); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes( <add> String annotationType, boolean classValuesAsString) { <add> return AnnotatedElementUtils.getAllAnnotationAttributes(getIntrospectedClass(), <add> annotationType, classValuesAsString, this.nestedAnnotationsAsMap); <ide> } <ide> <ide> public boolean hasAnnotatedMethods(String annotationType) { <ide> Method[] methods = getIntrospectedClass().getDeclaredMethods(); <ide> for (Method method : methods) { <del> for (Annotation ann : method.getAnnotations()) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> else { <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> } <del> } <add> if (AnnotatedElementUtils.isAnnotated(method, annotationType)) { <add> return true; <ide> } <ide> } <ide> return false; <ide> public Set<MethodMetadata> getAnnotatedMethods(String annotationType) { <ide> Method[] methods = getIntrospectedClass().getDeclaredMethods(); <ide> Set<MethodMetadata> annotatedMethods = new LinkedHashSet<MethodMetadata>(); <ide> for (Method method : methods) { <del> for (Annotation ann : method.getAnnotations()) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> annotatedMethods.add(new StandardMethodMetadata(method, this.nestedAnnotationsAsMap)); <del> break; <del> } <del> else { <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> annotatedMethods.add(new StandardMethodMetadata(method, this.nestedAnnotationsAsMap)); <del> break; <del> } <del> } <del> } <add> if (AnnotatedElementUtils.isAnnotated(method, annotationType)) { <add> annotatedMethods.add(new StandardMethodMetadata(method, <add> this.nestedAnnotationsAsMap)); <ide> } <ide> } <ide> return annotatedMethods; <ide><path>spring-core/src/main/java/org/springframework/core/type/StandardMethodMetadata.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.core.type; <ide> <del>import java.lang.annotation.Annotation; <ide> import java.lang.reflect.Method; <ide> import java.lang.reflect.Modifier; <ide> import java.util.Map; <ide> <del>import org.springframework.core.annotation.AnnotationUtils; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> * {@link MethodMetadata} implementation that uses standard reflection <ide> * @author Juergen Hoeller <ide> * @author Mark Pollack <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.0 <ide> */ <ide> public class StandardMethodMetadata implements MethodMetadata { <ide> public boolean isOverridable() { <ide> } <ide> <ide> public boolean isAnnotated(String annotationType) { <del> Annotation[] anns = this.introspectedMethod.getAnnotations(); <del> for (Annotation ann : anns) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return true; <del> } <del> } <del> } <del> return false; <add> return AnnotatedElementUtils.isAnnotated(this.introspectedMethod, annotationType); <ide> } <ide> <ide> public Map<String, Object> getAnnotationAttributes(String annotationType) { <del> Annotation[] anns = this.introspectedMethod.getAnnotations(); <del> for (Annotation ann : anns) { <del> if (ann.annotationType().getName().equals(annotationType)) { <del> return AnnotationUtils.getAnnotationAttributes( <del> ann, true, nestedAnnotationsAsMap); <del> } <del> for (Annotation metaAnn : ann.annotationType().getAnnotations()) { <del> if (metaAnn.annotationType().getName().equals(annotationType)) { <del> return AnnotationUtils.getAnnotationAttributes( <del> metaAnn, true, this.nestedAnnotationsAsMap); <del> } <del> } <del> } <del> return null; <add> return getAnnotationAttributes(annotationType, false); <add> } <add> <add> public Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString) { <add> return AnnotatedElementUtils.getAnnotationAttributes(this.introspectedMethod, <add> annotationType, classValuesAsString, this.nestedAnnotationsAsMap); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType) { <add> return getAllAnnotationAttributes(annotationType, false); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes( <add> String annotationType, boolean classValuesAsString) { <add> return AnnotatedElementUtils.getAllAnnotationAttributes(this.introspectedMethod, <add> annotationType, classValuesAsString, this.nestedAnnotationsAsMap); <ide> } <ide> <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/AnnotationAttributesReadingVisitor.java <ide> import org.springframework.asm.Type; <ide> import org.springframework.core.annotation.AnnotationAttributes; <ide> import org.springframework.core.annotation.AnnotationUtils; <add>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.ReflectionUtils; <ide> <del> <ide> /** <ide> * @author Chris Beams <ide> * @author Juergen Hoeller <add> * @author Phillip Webb <ide> * @since 3.1.1 <ide> */ <ide> abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor { <ide> abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor { <ide> <ide> protected final ClassLoader classLoader; <ide> <add> <ide> public AbstractRecursiveAnnotationVisitor(ClassLoader classLoader, AnnotationAttributes attributes) { <ide> super(SpringAsmInfo.ASM_VERSION); <ide> this.classLoader = classLoader; <ide> this.attributes = attributes; <ide> } <ide> <add> <ide> public void visit(String attributeName, Object attributeValue) { <ide> this.attributes.put(attributeName, attributeValue); <ide> } <ide> final class RecursiveAnnotationArrayVisitor extends AbstractRecursiveAnnotationV <ide> <ide> private final List<AnnotationAttributes> allNestedAttributes = new ArrayList<AnnotationAttributes>(); <ide> <add> <ide> public RecursiveAnnotationArrayVisitor( <ide> String attributeName, AnnotationAttributes attributes, ClassLoader classLoader) { <ide> super(classLoader, attributes); <ide> this.attributeName = attributeName; <ide> } <ide> <add> <ide> @Override <ide> public void visit(String attributeName, Object attributeValue) { <ide> Object newValue = attributeValue; <ide> class RecursiveAnnotationAttributesVisitor extends AbstractRecursiveAnnotationVi <ide> <ide> private final String annotationType; <ide> <add> <ide> public RecursiveAnnotationAttributesVisitor( <ide> String annotationType, AnnotationAttributes attributes, ClassLoader classLoader) { <ide> super(classLoader, attributes); <ide> this.annotationType = annotationType; <ide> } <ide> <add> <ide> public final void visitEnd() { <ide> try { <ide> Class<?> annotationClass = this.classLoader.loadClass(this.annotationType); <ide> else if (defaultValue instanceof Annotation[]) { <ide> * <ide> * @author Juergen Hoeller <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.0 <ide> */ <ide> final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttributesVisitor { <ide> <ide> private final String annotationType; <ide> <del> private final Map<String, AnnotationAttributes> attributesMap; <add> private final MultiValueMap<String, AnnotationAttributes> attributesMap; <ide> <ide> private final Map<String, Set<String>> metaAnnotationMap; <ide> <add> <ide> public AnnotationAttributesReadingVisitor( <del> String annotationType, Map<String, AnnotationAttributes> attributesMap, <add> String annotationType, MultiValueMap<String, AnnotationAttributes> attributesMap, <ide> Map<String, Set<String>> metaAnnotationMap, ClassLoader classLoader) { <ide> <ide> super(annotationType, new AnnotationAttributes(), classLoader); <ide> public AnnotationAttributesReadingVisitor( <ide> this.metaAnnotationMap = metaAnnotationMap; <ide> } <ide> <add> <ide> @Override <ide> public void doVisitEnd(Class<?> annotationClass) { <ide> super.doVisitEnd(annotationClass); <del> this.attributesMap.put(this.annotationType, this.attributes); <del> registerMetaAnnotations(annotationClass); <del> } <del> <del> private void registerMetaAnnotations(Class<?> annotationClass) { <del> // Register annotations that the annotation type is annotated with. <add> List<AnnotationAttributes> attributes = this.attributesMap.get(this.annotationType); <add> if (attributes == null) { <add> this.attributesMap.add(this.annotationType, this.attributes); <add> } <add> else { <add> attributes.add(0, this.attributes); <add> } <ide> Set<String> metaAnnotationTypeNames = new LinkedHashSet<String>(); <ide> for (Annotation metaAnnotation : annotationClass.getAnnotations()) { <del> metaAnnotationTypeNames.add(metaAnnotation.annotationType().getName()); <del> if (!this.attributesMap.containsKey(metaAnnotation.annotationType().getName())) { <del> this.attributesMap.put(metaAnnotation.annotationType().getName(), <del> AnnotationUtils.getAnnotationAttributes(metaAnnotation, true, true)); <del> } <del> for (Annotation metaMetaAnnotation : metaAnnotation.annotationType().getAnnotations()) { <del> metaAnnotationTypeNames.add(metaMetaAnnotation.annotationType().getName()); <del> } <add> recusivelyCollectMetaAnnotations(metaAnnotationTypeNames, metaAnnotation); <ide> } <ide> if (this.metaAnnotationMap != null) { <ide> this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames); <ide> } <ide> } <ide> <add> private void recusivelyCollectMetaAnnotations(Set<String> visited, Annotation annotation) { <add> if (visited.add(annotation.annotationType().getName())) { <add> this.attributesMap.add(annotation.annotationType().getName(), <add> AnnotationUtils.getAnnotationAttributes(annotation, true, true)); <add> for (Annotation metaMetaAnnotation : annotation.annotationType().getAnnotations()) { <add> recusivelyCollectMetaAnnotations(visited, metaMetaAnnotation); <add> } <add> } <add> } <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/AnnotationMetadataReadingVisitor.java <ide> * @author Juergen Hoeller <ide> * @author Mark Fisher <ide> * @author Costin Leau <add> * @author Phillip Webb <ide> * @since 2.5 <ide> */ <ide> public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor implements AnnotationMetadata { <ide> public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisito <ide> <ide> protected final Map<String, Set<String>> metaAnnotationMap = new LinkedHashMap<String, Set<String>>(4); <ide> <del> protected final Map<String, AnnotationAttributes> attributeMap = new LinkedHashMap<String, AnnotationAttributes>(4); <add> protected final MultiValueMap<String, AnnotationAttributes> attributeMap = new LinkedMultiValueMap<String, AnnotationAttributes>(4); <ide> <ide> protected final MultiValueMap<String, MethodMetadata> methodMetadataMap = new LinkedMultiValueMap<String, MethodMetadata>(); <ide> <ide> public AnnotationAttributes getAnnotationAttributes(String annotationType) { <ide> } <ide> <ide> public AnnotationAttributes getAnnotationAttributes(String annotationType, boolean classValuesAsString) { <del> AnnotationAttributes raw = this.attributeMap.get(annotationType); <del> return convertClassValues(raw, classValuesAsString); <add> List<AnnotationAttributes> attributes = this.attributeMap.get(annotationType); <add> AnnotationAttributes raw = (attributes == null ? null : attributes.get(0)); <add> return AnnotationReadingVisitorUtils.convertClassValues(this.classLoader, raw, <add> classValuesAsString); <ide> } <ide> <del> private AnnotationAttributes convertClassValues(AnnotationAttributes original, boolean classValuesAsString) { <del> if (original == null) { <add> public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType) { <add> return getAllAnnotationAttributes(annotationType, false); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes( <add> String annotationType, boolean classValuesAsString) { <add> MultiValueMap<String, Object> allAttributes = new LinkedMultiValueMap<String, Object>(); <add> List<AnnotationAttributes> attributes = this.attributeMap.get(annotationType); <add> if (attributes == null) { <ide> return null; <ide> } <del> AnnotationAttributes result = new AnnotationAttributes(original.size()); <del> for (Map.Entry<String, Object> entry : original.entrySet()) { <del> try { <del> Object value = entry.getValue(); <del> if (value instanceof AnnotationAttributes) { <del> value = convertClassValues((AnnotationAttributes) value, classValuesAsString); <del> } <del> else if (value instanceof AnnotationAttributes[]) { <del> AnnotationAttributes[] values = (AnnotationAttributes[])value; <del> for (int i = 0; i < values.length; i++) { <del> values[i] = convertClassValues(values[i], classValuesAsString); <del> } <del> } <del> else if (value instanceof Type) { <del> value = (classValuesAsString ? ((Type) value).getClassName() : <del> this.classLoader.loadClass(((Type) value).getClassName())); <del> } <del> else if (value instanceof Type[]) { <del> Type[] array = (Type[]) value; <del> Object[] convArray = (classValuesAsString ? new String[array.length] : new Class[array.length]); <del> for (int i = 0; i < array.length; i++) { <del> convArray[i] = (classValuesAsString ? array[i].getClassName() : <del> this.classLoader.loadClass(array[i].getClassName())); <del> } <del> value = convArray; <del> } <del> else if (classValuesAsString) { <del> if (value instanceof Class) { <del> value = ((Class<?>) value).getName(); <del> } <del> else if (value instanceof Class[]) { <del> Class<?>[] clazzArray = (Class[]) value; <del> String[] newValue = new String[clazzArray.length]; <del> for (int i = 0; i < clazzArray.length; i++) { <del> newValue[i] = clazzArray[i].getName(); <del> } <del> value = newValue; <del> } <del> } <del> result.put(entry.getKey(), value); <del> } <del> catch (Exception ex) { <del> // Class not found - can't resolve class reference in annotation attribute. <add> for (AnnotationAttributes raw : attributes) { <add> for (Map.Entry<String, Object> entry : AnnotationReadingVisitorUtils.convertClassValues( <add> this.classLoader, raw, classValuesAsString).entrySet()) { <add> allAttributes.add(entry.getKey(), entry.getValue()); <ide> } <ide> } <del> return result; <add> return allAttributes; <ide> } <ide> <ide> public boolean hasAnnotatedMethods(String annotationType) { <ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/AnnotationReadingVisitorUtils.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.core.type.classreading; <add> <add>import java.util.Map; <add> <add>import org.springframework.asm.Type; <add>import org.springframework.core.annotation.AnnotationAttributes; <add> <add>/** <add> * Internal utility class used when reading annotations. <add> * <add> * @author Juergen Hoeller <add> * @author Mark Fisher <add> * @author Costin Leau <add> * @author Phillip Webb <add> * @since 4.0 <add> */ <add>abstract class AnnotationReadingVisitorUtils { <add> <add> public static AnnotationAttributes convertClassValues(ClassLoader classLoader, <add> AnnotationAttributes original, boolean classValuesAsString) { <add> <add> if (original == null) { <add> return null; <add> } <add> <add> AnnotationAttributes result = new AnnotationAttributes(original.size()); <add> for (Map.Entry<String, Object> entry : original.entrySet()) { <add> try { <add> Object value = entry.getValue(); <add> if (value instanceof AnnotationAttributes) { <add> value = convertClassValues(classLoader, (AnnotationAttributes) value, <add> classValuesAsString); <add> } <add> else if (value instanceof AnnotationAttributes[]) { <add> AnnotationAttributes[] values = (AnnotationAttributes[])value; <add> for (int i = 0; i < values.length; i++) { <add> values[i] = convertClassValues(classLoader, values[i], <add> classValuesAsString); <add> } <add> } <add> else if (value instanceof Type) { <add> value = (classValuesAsString ? ((Type) value).getClassName() : <add> classLoader.loadClass(((Type) value).getClassName())); <add> } <add> else if (value instanceof Type[]) { <add> Type[] array = (Type[]) value; <add> Object[] convArray = (classValuesAsString ? new String[array.length] : new Class[array.length]); <add> for (int i = 0; i < array.length; i++) { <add> convArray[i] = (classValuesAsString ? array[i].getClassName() : <add> classLoader.loadClass(array[i].getClassName())); <add> } <add> value = convArray; <add> } <add> else if (classValuesAsString) { <add> if (value instanceof Class) { <add> value = ((Class<?>) value).getName(); <add> } <add> else if (value instanceof Class[]) { <add> Class<?>[] clazzArray = (Class[]) value; <add> String[] newValue = new String[clazzArray.length]; <add> for (int i = 0; i < clazzArray.length; i++) { <add> newValue[i] = clazzArray[i].getName(); <add> } <add> value = newValue; <add> } <add> } <add> result.put(entry.getKey(), value); <add> } <add> catch (Exception ex) { <add> // Class not found - can't resolve class reference in annotation attribute. <add> } <add> } <add> return result; <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/MethodMetadataReadingVisitor.java <ide> <ide> package org.springframework.core.type.classreading; <ide> <del>import java.util.LinkedHashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.springframework.asm.AnnotationVisitor; <ide> import org.springframework.asm.Type; <ide> import org.springframework.core.annotation.AnnotationAttributes; <ide> import org.springframework.core.type.MethodMetadata; <add>import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> * @author Mark Pollack <ide> * @author Costin Leau <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.0 <ide> */ <ide> public class MethodMetadataReadingVisitor extends MethodVisitor implements MethodMetadata { <ide> public class MethodMetadataReadingVisitor extends MethodVisitor implements Metho <ide> <ide> protected final MultiValueMap<String, MethodMetadata> methodMetadataMap; <ide> <del> protected final Map<String, AnnotationAttributes> attributeMap = new LinkedHashMap<String, AnnotationAttributes>(2); <add> protected final MultiValueMap<String, AnnotationAttributes> attributeMap = new LinkedMultiValueMap<String, AnnotationAttributes>(2); <ide> <ide> <ide> public MethodMetadataReadingVisitor(String name, int access, String declaringClassName, ClassLoader classLoader, <ide> public boolean isAnnotated(String annotationType) { <ide> return this.attributeMap.containsKey(annotationType); <ide> } <ide> <del> public AnnotationAttributes getAnnotationAttributes(String annotationType) { <del> return this.attributeMap.get(annotationType); <add> public Map<String, Object> getAnnotationAttributes(String annotationType) { <add> return getAnnotationAttributes(annotationType, false); <add> } <add> <add> public Map<String, Object> getAnnotationAttributes(String annotationType, <add> boolean classValuesAsString) { <add> List<AnnotationAttributes> attributes = this.attributeMap.get(annotationType); <add> return (attributes == null ? null : AnnotationReadingVisitorUtils.convertClassValues( <add> this.classLoader, attributes.get(0), classValuesAsString)); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType) { <add> return getAllAnnotationAttributes(annotationType, false); <add> } <add> <add> public MultiValueMap<String, Object> getAllAnnotationAttributes( <add> String annotationType, boolean classValuesAsString) { <add> if(!this.attributeMap.containsKey(annotationType)) { <add> return null; <add> } <add> MultiValueMap<String, Object> allAttributes = new LinkedMultiValueMap<String, Object>(); <add> for (AnnotationAttributes annotationAttributes : this.attributeMap.get(annotationType)) { <add> for (Map.Entry<String, Object> entry : AnnotationReadingVisitorUtils.convertClassValues( <add> this.classLoader, annotationAttributes, classValuesAsString).entrySet()) { <add> allAttributes.add(entry.getKey(), entry.getValue()); <add> } <add> } <add> return allAttributes; <ide> } <ide> <ide> public String getDeclaringClassName() { <ide><path>spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java <ide> <ide> import static org.hamcrest.CoreMatchers.instanceOf; <ide> import static org.hamcrest.CoreMatchers.is; <add>import static org.hamcrest.Matchers.equalTo; <ide> import static org.junit.Assert.assertArrayEquals; <add>import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add>import java.util.Arrays; <add>import java.util.HashSet; <add>import java.util.List; <ide> import java.util.Set; <ide> <ide> import org.junit.Test; <del> <ide> import org.springframework.core.annotation.AnnotationAttributes; <ide> import org.springframework.core.type.classreading.MetadataReader; <ide> import org.springframework.core.type.classreading.MetadataReaderFactory; <ide> * <ide> * @author Juergen Hoeller <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> */ <ide> public class AnnotationMetadataTests { <ide> <ide> private void doTestAnnotationInfo(AnnotationMetadata metadata) { <ide> assertThat(metadata.hasAnnotation(Component.class.getName()), is(true)); <ide> assertThat(metadata.hasAnnotation(Scope.class.getName()), is(true)); <ide> assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(true)); <del> assertThat(metadata.getAnnotationTypes().size(), is(3)); <add> assertThat(metadata.getAnnotationTypes().size(), is(5)); <ide> assertThat(metadata.getAnnotationTypes().contains(Component.class.getName()), is(true)); <ide> assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName()), is(true)); <ide> assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName()), is(true)); <ide> private void doTestAnnotationInfo(AnnotationMetadata metadata) { <ide> AnnotationAttributes scopeAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(Scope.class.getName()); <ide> assertThat(scopeAttrs.size(), is(1)); <ide> assertThat(scopeAttrs.getString("value"), is("myScope")); <add> <add> Set<MethodMetadata> methods = metadata.getAnnotatedMethods(DirectAnnotation.class.getName()); <add> MethodMetadata method = methods.iterator().next(); <add> assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); <add> List<Object> allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); <add> assertThat(new HashSet<Object>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta"))))); <add> <add> assertTrue(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())); <add> <ide> { // perform tests with classValuesAsString = false (the default) <ide> AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName()); <ide> assertThat(specialAttrs.size(), is(6)); <ide> private void doTestAnnotationInfo(AnnotationMetadata metadata) { <ide> assertTrue(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)); <ide> assertArrayEquals(new Class[]{Void.class}, (Class[])optionalArray[0].get("classArray")); <ide> assertArrayEquals(new Class[]{Void.class}, optionalArray[0].getClassArray("classArray")); <add> <add> assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); <add> allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); <add> assertThat(new HashSet<Object>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta"))))); <ide> } <ide> { // perform tests with classValuesAsString = true <ide> AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName(), true); <ide> private void doTestAnnotationInfo(AnnotationMetadata metadata) { <ide> AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray"); <ide> assertArrayEquals(new String[]{Void.class.getName()}, (String[])optionalArray[0].get("classArray")); <ide> assertArrayEquals(new String[]{Void.class.getName()}, optionalArray[0].getStringArray("classArray")); <add> <add> assertEquals(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"), "direct"); <add> allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); <add> assertThat(new HashSet<Object>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta"))))); <ide> } <ide> } <ide> <ide> public static enum SomeEnum { <ide> NestedAnno[] optionalArray() default {@NestedAnno(value="optional", anEnum=SomeEnum.DEFAULT, classArray=Void.class)}; <ide> } <ide> <add> @Target({ ElementType.TYPE, ElementType.METHOD }) <add> @Retention(RetentionPolicy.RUNTIME) <add> public @interface DirectAnnotation { <add> String value(); <add> } <add> <add> @Target({ ElementType.TYPE }) <add> @Retention(RetentionPolicy.RUNTIME) <add> public @interface IsAnnotatedAnnotation { <add> } <add> <add> @Target(ElementType.TYPE) <add> @Retention(RetentionPolicy.RUNTIME) <add> @DirectAnnotation("meta") <add> @IsAnnotatedAnnotation <add> public @interface MetaAnnotation { <add> } <add> <add> @Target({ ElementType.TYPE, ElementType.METHOD }) <add> @Retention(RetentionPolicy.RUNTIME) <add> @MetaAnnotation <add> public @interface MetaMetaAnnotation { <add> } <ide> <ide> @Component("myName") <ide> @Scope("myScope") <ide> public static enum SomeEnum { <ide> @NestedAnno(value = "na1", anEnum = SomeEnum.LABEL2, classArray = {Number.class}) <ide> }) <ide> @SuppressWarnings({"serial", "unused"}) <add> @DirectAnnotation("direct") <add> @MetaMetaAnnotation <ide> private static class AnnotatedComponent implements Serializable { <ide> <ide> @TestAutowired <ide> public void doWork(@TestQualifier("myColor") java.awt.Color color) { <ide> <ide> public void doSleep() { <ide> } <add> <add> @DirectAnnotation("direct") <add> @MetaMetaAnnotation <add> public void meta() { <add> } <ide> } <ide> <ide> }
11
Text
Text
add deeper instructions on project tags
a8cc73c5e674e5b3e6a6a91b99da27812a7a7843
<ide><path>docs/getting-started.md <ide> list of all symbols in the current file, which you can fuzzy filter similarly to <ide> `cmd-t`. <ide> <ide> To search for symbols across your project, use `cmd-shift-r`. First you'll need <del>to make sure you have ctags installed and a tags file generated for your <del>project. Also, if you're editing CoffeeScript, it's a good idea to update your <del>`~/.ctags` file to understand the language. Here is [a good example][ctags]. <add>to make sure you have `tags` (or `TAGS`) file generated for your project. <add>This can be done by installing [ctags](http://ctags.sourceforge.net/) and <add>running a command such as `ctags -R src` from the command line in your project's <add>root directory. Using [Homebrew](http://brew.sh/)? Just run <add>`brew install ctags`. <add> <add>You can customize how tags are generated by creating your own `.ctags` file <add>in your home directory (`~/.ctags`). Here is [a good example][ctags] to start <add>from. <ide> <ide> ### Split Panes <ide>
1
Javascript
Javascript
add missing assertion
c5e3353953bb5a332cb5125616f9115fda71b944
<ide><path>test/parallel/test-dgram-multicast-set-interface.js <ide> const dgram = require('dgram'); <ide> socket.bind(0); <ide> socket.on('listening', common.mustCall(() => { <ide> // Try to set with an invalid interfaceAddress (wrong address class) <add> // <add> // This operation succeeds on some platforms, throws `EINVAL` on some <add> // platforms, and throws `ENOPROTOOPT` on others. This is unpleasant, but <add> // we should at least test for it. <ide> try { <ide> socket.setMulticastInterface('::'); <del> throw new Error('Not detected.'); <ide> } catch (e) { <del> console.error(`setMulticastInterface: wrong family error is: ${e}`); <add> assert(e.code === 'EINVAL' || e.code === 'ENOPROTOOPT'); <ide> } <ide> <ide> socket.close();
1
Text
Text
remove the paypal badge
4e4fe95369c15e62364f7d6a6bfc9464c1143dc6
<ide><path>README.md <ide> <a href="https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md"> <ide> <img src="https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square" height="20" alt="Contributions Welcome"> <ide> </a> <del> <a href="https://www.paypal.me/TheAlgorithms/100"> <del> <img src="https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal&style=flat-square" height="20" alt="Donate"> <del> </a> <ide> <img src="https://img.shields.io/github/repo-size/TheAlgorithms/Python.svg?label=Repo%20size&style=flat-square" height="20"> <ide> <a href="https://discord.gg/c7MnfGFGa6"> <ide> <img src="https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square" height="20" alt="Discord chat">
1
Ruby
Ruby
add transfer_encoding= setter deprecation
2d567e470adb9241b400e02ccb0501efb7d09b14
<ide><path>actionmailer/lib/action_mailer/tmail_compat.rb <ide> def transfer_encoding(value = nil) <ide> old_transfer_encoding <ide> end <ide> end <del> <add> <add> def transfer_encoding=(value) <add> ActiveSupport::Deprecation.warn('Message#transfer_encoding= is deprecated, please call ' << <add> 'Message#content_transfer_encoding= with the same arguments', caller[0,2]) <add> self.content_transfer_encoding = value <add> end <add> <ide> def original_filename <ide> ActiveSupport::Deprecation.warn('Message#original_filename is deprecated, ' << <ide> 'please call Message#filename', caller[0,2]) <ide><path>actionmailer/test/old_base/tmail_compat_test.rb <ide> def test_transfer_encoding_raises_deprecation_warning <ide> end <ide> assert_equal mail.content_transfer_encoding, "base64" <ide> end <add> <add> def test_transfer_encoding_setter_raises_deprecation_warning <add> mail = Mail.new <add> assert_deprecated do <add> assert_nothing_raised do <add> mail.transfer_encoding = "base64" <add> end <add> end <add> assert_equal mail.content_transfer_encoding, "base64" <add> end <ide> <ide> end
2
Ruby
Ruby
set a name for bottles."
35093b7a372e492fa28f0f23dff159c018b26a6f
<ide><path>Library/Homebrew/software_spec.rb <ide> class Bottle <ide> <ide> attr_reader :resource, :prefix, :cellar, :revision <ide> <del> def_delegators :resource, :name, :url, :fetch, :verify_download_integrity <add> def_delegators :resource, :url, :fetch, :verify_download_integrity <ide> def_delegators :resource, :downloader, :cached_download, :clear_cache <ide> <ide> def initialize(f, spec) <del> @resource = Resource.new f.name <add> @resource = Resource.new <ide> @resource.owner = f <ide> @resource.url = bottle_url( <ide> spec.root_url,
1
Javascript
Javascript
add node.fs prefix to some constants. oops
2fe090b7f6026d6b2a05f484f7e3c994d1892842
<ide><path>src/file.js <ide> node.fs.File = function (options) { <ide> <ide> var internal_methods = { <ide> open: function (path, mode) { <del> var m = node.fs.O_RDONLY; <add> var flags; <ide> switch (mode) { <ide> case "r": <del> m = node.fs.O_RDONLY; <add> flags = node.fs.O_RDONLY; <ide> break; <ide> case "r+": <del> m = node.fs.O_RDWR; <add> flags = node.fs.O_RDWR; <ide> break; <ide> case "w": <del> m = O_CREAT | O_TRUNC | O_WRONLY; <add> flags = node.fs.O_CREAT | node.fs.O_TRUNC | node.fs.O_WRONLY; <ide> break; <ide> case "w+": <del> m = O_CREAT | O_TRUNC | O_RDWR; <add> flags = node.fs.O_CREAT | node.fs.O_TRUNC | node.fs.O_RDWR; <ide> break; <ide> case "a": <del> m = O_APPEND | O_CREAT | O_WRONLY; <add> flags = node.fs.O_APPEND | node.fs.O_CREAT | node.fs.O_WRONLY; <ide> break; <ide> case "a+": <del> m = O_APPEND | O_CREAT | O_RDWR; <add> flags = node.fs.O_APPEND | node.fs.O_CREAT | node.fs.O_RDWR; <ide> break; <ide> default: <ide> throw "Unknown mode"; <ide> } <del> <del> node.fs.open(path, m, 0666, function (status, fd) { <add> // fix the mode here <add> node.fs.open(path, flags, 0666, function (status, fd) { <ide> self.fd = fd; <ide> poll(status, fd); <ide> });
1
Ruby
Ruby
reduce calls to get path info when finding routes
9ec803bb0700a747a32157c78b748349e5763278
<ide><path>actionpack/lib/action_dispatch/journey/router.rb <ide> def filter_routes(path) <ide> end <ide> <ide> def find_routes(req) <del> routes = filter_routes(req.path_info).concat custom_routes.find_all { |r| <del> r.path.match?(req.path_info) <add> path_info = req.path_info <add> routes = filter_routes(path_info).concat custom_routes.find_all { |r| <add> r.path.match?(path_info) <ide> } <ide> <ide> if req.head? <ide> def find_routes(req) <ide> routes.sort_by!(&:precedence) <ide> <ide> routes.map! { |r| <del> match_data = r.path.match(req.path_info) <add> match_data = r.path.match(path_info) <ide> path_parameters = {} <ide> match_data.names.each_with_index { |name, i| <ide> val = match_data[i + 1]
1
PHP
PHP
add test
fab61079afd17483ec91e6a897a912fd3990d97e
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testWithCountAndSelect() <ide> $this->assertSame('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql()); <ide> } <ide> <add> public function testWithCountSecondRelationWithClosure() <add> { <add> $model = new EloquentBuilderTestModelParentStub; <add> <add> $builder = $model->withCount(['address', 'foo' => function ($query) { <add> $query->where('active', false); <add> }]); <add> <add> $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "address_count", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "active" = ?) as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql()); <add> } <add> <ide> public function testWithCountAndMergedWheres() <ide> { <ide> $model = new EloquentBuilderTestModelParentStub;
1
Javascript
Javascript
avoid inline assignments
b2571e8976b084e466f336c192fd0a2e4b5491e3
<ide><path>src/project.js <ide> class Project extends Model { <ide> // * `projectPath` {String} The path to remove. <ide> removePath (projectPath) { <ide> // The projectPath may be a URI, in which case it should not be normalized. <del> let needle <del> if ((needle = projectPath, !this.getPaths().includes(needle))) { <add> if (!this.getPaths().includes(projectPath)) { <ide> projectPath = this.defaultDirectoryProvider.normalizePath(projectPath) <ide> } <ide>
1
Javascript
Javascript
update devtools injection
5470972f6a61111da661b0092d71645751bf1259
<ide><path>src/renderers/native/ReactNative/ReactNative.js <ide> <ide> // Require ReactNativeDefaultInjection first for its side effects of setting up <ide> // the JS environment <add>var ReactNativeComponentTree = require('ReactNativeComponentTree'); <ide> var ReactNativeDefaultInjection = require('ReactNativeDefaultInjection'); <ide> <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> if ( <ide> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && <ide> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { <ide> __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ <del> CurrentOwner: ReactCurrentOwner, <del> InstanceHandles: ReactInstanceHandles, <add> ComponentTree: { <add> getClosestInstanceFromNode: function(node) { <add> return ReactNativeComponentTree.getClosestInstanceFromNode(node); <add> }, <add> getNodeFromInstance: function(inst) { <add> // inst is an internal instance (but could be a composite) <add> while (inst._renderedComponent) { <add> inst = inst._renderedComponent; <add> } <add> if (inst) { <add> return ReactNativeComponentTree.getNodeFromInstance(inst); <add> } else { <add> return null; <add> } <add> }, <add> }, <ide> Mount: ReactNativeMount, <ide> Reconciler: require('ReactReconciler'), <del> TextComponent: require('ReactNativeTextComponent'), <ide> }); <ide> } <ide>
1
Text
Text
add info about building n-api addons
cb36fa67d77ff6891a48db0b473d1c51888e23ed
<ide><path>doc/api/n-api.md <ide> changes in the underlying JavaScript engine and allow modules <ide> compiled for one major version to run on later major versions of Node.js without <ide> recompilation. The [ABI Stability][] guide provides a more in-depth explanation. <ide> <del>Addons are built/packaged with the same approach/tools <del>outlined in the section titled [C++ Addons](addons.html). <del>The only difference is the set of APIs that are used by the native code. <del>Instead of using the V8 or [Native Abstractions for Node.js][] APIs, <del>the functions available in the N-API are used. <add>Addons are built/packaged with the same approach/tools outlined in the section <add>titled [C++ Addons][]. The only difference is the set of APIs that are used by <add>the native code. Instead of using the V8 or [Native Abstractions for Node.js][] <add>APIs, the functions available in the N-API are used. <ide> <ide> APIs exposed by N-API are generally used to create and manipulate <ide> JavaScript values. Concepts and operations generally map to ideas specified <ide> if (status != napi_ok) { <ide> The end result is that the addon only uses the exported C APIs. As a result, <ide> it still gets the benefits of the ABI stability provided by the C API. <ide> <del>When using `node-addon-api` instead of the C APIs, start with the API <del>[docs](https://github.com/nodejs/node-addon-api#api-documentation) <add>When using `node-addon-api` instead of the C APIs, start with the API [docs][] <ide> for `node-addon-api`. <ide> <ide> ## Implications of ABI Stability <ide> must make use exclusively of N-API by restricting itself to using <ide> and by checking, for all external libraries that it uses, that the external <ide> library makes ABI stability guarantees similar to N-API. <ide> <add>## Building <add> <add>Unlike modules written in JavaScript, developing and deploying Node.js <add>native addons using N-API requires an additional set of tools. Besides the <add>basic tools required to develop for Node.js, the native addon developer <add>requires a toolchain that can compile C and C++ code into a binary. In <add>addition, depending upon how the native addon is deployed, the *user* of <add>the native addon will also need to have a C/C++ toolchain installed. <add> <add>For Linux developers, the necessary C/C++ toolchain packages are readily <add>available. [GCC][] is widely used in the Node.js community to build and <add>test across a variety of plarforms. For many developers, the [LLVM][] <add>compiler infrastructure is also a good choice. <add> <add>For Mac developers, [Xcode][] offers all the required compiler tools. <add>However, it is not necessary to install the entire Xcode IDE. The following <add>command installs the necessary toolchain: <add> <add>```bash <add>xcode-select --install <add>``` <add> <add>For Windows developers, [Visual Studio][] offers all the required compiler <add>tools. However, it is not necessary to install the entire Visual Studio <add>IDE. The following command installs the necessary toolchain: <add> <add>```bash <add>npm install --global --production windows-build-tools <add>``` <add> <add>The sections below describe the additional tools available for developing <add>and deploying Node.js native addons. <add> <add>### Build tools <add> <add>Both the tools listed here require that *users* of the native <add>addon have a C/C++ toolchain installed in order to successfully install <add>the native addon. <add> <add>#### node-gyp <add> <add>[node-gyp][] is a build system based on Google's [GYP][] tool and comes <add>bundled with npm. GYP, and therefore node-gyp, requires that Python be <add>installed. <add> <add>Historically, node-gyp has been the tool of choice for building native <add>addons. It has widespread adoption and documentation. However, some <add>developers have run into limitations in node-gyp. <add> <add>#### CMake.js <add> <add>[CMake.js][] is an alternative build system based on [CMake][]. <add> <add>CMake.js is a good choice for projects that already use CMake or for <add>developers affected by limitations in node-gyp. <add> <add>### Uploading precompiled binaries <add> <add>The three tools listed here permit native addon developers and maintainers <add>to create and upload binaries to public or private servers. These tools are <add>typically integrated with CI/CD build systems like [Travis CI][] and <add>[AppVeyor][] to build and upload binaries for a variety of platforms and <add>architectures. These binaries are then available for download by users who <add>do not need to have a C/C++ toolchain installed. <add> <add>#### node-pre-gyp <add> <add>[node-pre-gyp][] is a tool based on node-gyp that adds the ability to <add>upload binaries to a server of the developer's choice. node-pre-gyp has <add>particularly good support for uploading binaries to Amazon S3. <add> <add>#### prebuild <add> <add>[prebuild][] is a tool that supports builds using either node-gyp or <add>CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild <add>uploads binaries only to [GitHub releases][]. prebuild is a good choice for <add>GitHub projects using CMake.js. <add> <add>#### prebuildify <add> <add>[prebuildify][] is tool based on node-gyp. The advantage of prebuildify is <add>that the built binaries are bundled with the native module when it's <add>uploaded to npm. The binaries are downloaded from npm and are immediately <add>available to the module user when the native module is installed. <add> <ide> ## Usage <ide> <del>In order to use the N-API functions, include the file <del>[`node_api.h`](https://github.com/nodejs/node/blob/master/src/node_api.h) <del>which is located in the src directory in the node development tree: <add>In order to use the N-API functions, include the file [`node_api.h`][] which is <add>located in the src directory in the node development tree: <ide> <ide> ```C <ide> #include <node_api.h> <ide> This API may only be called from the main thread. <ide> [context-aware addons]: addons.html#addons_context_aware_addons <ide> [node-addon-api]: https://github.com/nodejs/node-addon-api <ide> [worker threads]: https://nodejs.org/api/worker_threads.html <add>[C++ Addons]: addons.html <add>[docs]: https://github.com/nodejs/node-addon-api#api-documentation <add>[GCC]: https://gcc.gnu.org <add>[LLVM]: https://llvm.org <add>[Xcode]: https://developer.apple.com/xcode/ <add>[Visual Studio]: https://visualstudio.microsoft.com <add>[node-gyp]: https://github.com/nodejs/node-gyp <add>[GYP]: https://gyp.gsrc.io <add>[CMake.js]: https://github.com/cmake-js/cmake-js <add>[CMake]: https://cmake.org <add>[Travis CI]: https://travis-ci.org <add>[AppVeyor]: https://www.appveyor.com <add>[node-pre-gyp]: https://github.com/mapbox/node-pre-gyp <add>[prebuild]: https://github.com/prebuild/prebuild <add>[GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases <add>[prebuildify]: https://github.com/prebuild/prebuildify <add>[`node_api.h`]: https://github.com/nodejs/node/blob/master/src/node_api.h
1
Go
Go
return bufio error if set in parseenvfile
e8484940170e81eef1866f55f79030731e3d3d69
<ide><path>opts/envfile.go <ide> func ParseEnvFile(filename string) ([]string, error) { <ide> } <ide> } <ide> } <del> return lines, nil <add> return lines, scanner.Err() <ide> } <ide> <ide> var whiteSpaces = " \t"
1
PHP
PHP
improve foreignkeydefinition meta class
eb73a500f8bf3a42c3ca80845484589796ae5a55
<ide><path>src/Illuminate/Database/Schema/ForeignKeyDefinition.php <ide> use Illuminate\Support\Fluent; <ide> <ide> /** <del> * @method ForeignKeyDefinition references(string $table) Specify the referenced table <del> * @method ForeignKeyDefinition on(string $column) Specify the referenced column <add> * @method ForeignKeyDefinition references(string|array $columns) Specify the referenced column(s) <add> * @method ForeignKeyDefinition on(string $table) Specify the referenced table <ide> * @method ForeignKeyDefinition onDelete(string $action) Add an ON DELETE action <ide> * @method ForeignKeyDefinition onUpdate(string $action) Add an ON UPDATE action <add> * @method ForeignKeyDefinition deferrable(bool $value = true) Set the foreign key as deferrable (PostgreSQL) <add> * @method ForeignKeyDefinition initiallyImmediate(bool $value = true) Set the default time to check the constraint (PostgreSQL) <ide> */ <ide> class ForeignKeyDefinition extends Fluent <ide> {
1
Python
Python
add hf hub to env version command
ab2f8d12a7c04e351cc397942db6736a74d6a00c
<ide><path>src/transformers/commands/env.py <ide> import platform <ide> from argparse import ArgumentParser <ide> <add>import huggingface_hub <add> <ide> from .. import __version__ as version <ide> from ..file_utils import is_flax_available, is_tf_available, is_torch_available <ide> from . import BaseTransformersCLICommand <ide> def run(self): <ide> "`transformers` version": version, <ide> "Platform": platform.platform(), <ide> "Python version": platform.python_version(), <add> "Huggingface_hub version": huggingface_hub.__version__, <ide> "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})", <ide> "Tensorflow version (GPU?)": f"{tf_version} ({tf_cuda_available})", <ide> "Flax version (CPU?/GPU?/TPU?)": f"{flax_version} ({jax_backend})",
1
Ruby
Ruby
remove extra flat_map array
242d70278689a0f7e6c6f415992c8de0aa5caee0
<ide><path>activerecord/lib/active_record/associations/preloader/association.rb <ide> def associated_records_by_owner <ide> # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) <ide> # Make several smaller queries if necessary or make one query if the adapter supports it <ide> sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) <del> records = sliced.flat_map { |slice| records_for(slice) } <del> <del> records.each do |record| <del> owner_key = owner_id_for records, record <del> <del> owners_map[owner_key].each do |owner| <del> records_by_owner[owner] << record <add> sliced.each { |slice| <add> records = records_for(slice) <add> records.each do |record| <add> owner_key = owner_id_for records, record <add> <add> owners_map[owner_key].each do |owner| <add> records_by_owner[owner] << record <add> end <ide> end <del> end <add> } <ide> end <ide> <ide> records_by_owner
1
Text
Text
update core ideas.md
a8048875ce8b9b3ded1e89e05d31d7622afbbfa1
<ide><path>docs/Basics/Core Ideas.md <ide> Redux can be described in three fundamental principles: <ide> * **The only way to mutate the state is to emit an *action*, an object describing what happened.** This ensures that the views or the network callbacks never write directly to the state, and instead express the intent to mutate. Because all mutations are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. Actions are just plain objects, so they can be logged, serialized, stored, and later replayed for debugging or testing purposes. <ide> <ide> * **To specify how the state tree is transformed by the actions, you write pure *reducers*.** Reducers are just pure functions that take the previous state and the action, and return the next state. You can start with a single reducer, but as your app grows, you can split it into smaller reducers that manage the specific parts of the state tree. Because reducers are just functions, you can control the order in which they are called, pass additional data, or even make reusable reducers for common tasks such as pagination. <add> <add>-------------------------- <add> <add>Next: [Getting Started](Getting Started.md)
1
Javascript
Javascript
throw a decent error on missing font
40102adda0cccdaf17a5e794e6e6fad0c254d920
<ide><path>src/extras/FontUtils.js <ide> THREE.FontUtils = { <ide> <ide> getFace: function () { <ide> <del> return this.faces[ this.face ][ this.weight ][ this.style ]; <add> try { <add> <add> return this.faces[ this.face ][ this.weight ][ this.style ]; <add> <add> } catch (e) { <add> <add> throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing." <add> <add> }; <ide> <ide> }, <ide>
1
PHP
PHP
fix failing test
ad7db4cc541e2258178d4d76d145d81388eae544
<ide><path>cake/tests/cases/libs/view/view.test.php <ide> function testRenderLayoutWithMockCacheHelper() { <ide> Configure::write('Cache.check', true); <ide> <ide> $Controller =& new ViewPostsController(); <del> $Controller->cacheAction = '1 day'; <add> $Controller->cacheAction = '+1 day'; <ide> $View =& new View($Controller); <ide> $View->loaded['cache'] = new ViewTestMockCacheHelper(); <ide> $View->loaded['cache']->expectCallCount('cache', 2); <ide> <del> $result = $View->render('index'); <del> $this->assertPattern('/posts index/', $result); <add> $View->render('index'); <ide> <ide> Configure::write('Cache.check', $_check); <ide> }
1
Javascript
Javascript
use a getter for stream options
81c01bbdbaa414c0bbceec6deaf0046cdcaaa95d
<ide><path>lib/internal/quic/core.js <ide> const kContinueBind = Symbol('kContinueBind'); <ide> const kDestroy = Symbol('kDestroy'); <ide> const kEndpointBound = Symbol('kEndpointBound'); <ide> const kEndpointClose = Symbol('kEndpointClose'); <del>const kGetStreamOptions = Symbol('kGetStreamOptions'); <ide> const kHandshake = Symbol('kHandshake'); <ide> const kHandshakePost = Symbol('kHandshakePost'); <ide> const kHeaders = Symbol('kHeaders'); <ide> const kSetSocket = Symbol('kSetSocket'); <ide> const kSetSocketAfterBind = Symbol('kSetSocketAfterBind'); <ide> const kStartFilePipe = Symbol('kStartFilePipe'); <ide> const kStreamClose = Symbol('kStreamClose'); <add>const kStreamOptions = Symbol('kStreamOptions'); <ide> const kStreamReset = Symbol('kStreamReset'); <ide> const kTrackWriteState = Symbol('kTrackWriteState'); <ide> const kUDPHandleForTesting = Symbol('kUDPHandleForTesting'); <ide> function onSessionReady(handle) { <ide> new QuicServerSession( <ide> socket, <ide> handle, <del> socket[kGetStreamOptions]()); <add> socket[kStreamOptions]); <ide> try { <ide> socket.emit('session', session); <ide> } catch (error) { <ide> function onStreamReady(streamHandle, id, push_id) { <ide> const { <ide> highWaterMark, <ide> defaultEncoding, <del> } = session[kGetStreamOptions](); <add> } = session[kStreamOptions]; <ide> const stream = new QuicStream({ <ide> writable: !uni, <ide> highWaterMark, <ide> class QuicSocket extends EventEmitter { <ide> // Returns the default QuicStream options for peer-initiated <ide> // streams. These are passed on to new client and server <ide> // QuicSession instances when they are created. <del> [kGetStreamOptions]() { <add> get [kStreamOptions]() { <ide> const state = this[kInternalState]; <ide> return { <ide> highWaterMark: state.highWaterMark, <ide> class QuicSession extends EventEmitter { <ide> socket[kAddSession](this); <ide> } <ide> <del> // kGetStreamOptions is called to get the configured options <del> // for peer initiated QuicStream instances. <del> [kGetStreamOptions]() { <add> // Used to get the configured options for peer initiated QuicStream <add> // instances. <add> get [kStreamOptions]() { <ide> const state = this[kInternalState]; <ide> return { <ide> highWaterMark: state.highWaterMark,
1
Text
Text
update faq about hls and dash with vhs
808d818c7d8ee8467003e6958172840736b6389c
<ide><path>docs/guides/faq.md <ide> Video.js is an extendable framework/library around the native video element. It <ide> * Offers an extendable and themable UI <ide> * Ensures accessibility for keyboard and screen reader users <ide> * Has a set of core plugins that offer support for additional video formats: <del> * [videojs-contrib-hls][hls] <del> * [videojs-contrib-dash][dash] <add> * HLS and DASH are supported natively. <add> * [videojs-contrib-dash][dash] can be used for more complete DASH support <ide> * Supports DRM video via a core plugin: <ide> * [videojs-contrib-eme][eme] <ide> * Is extensible with lots of plugins offering support for all kinds of features. See the [plugin list on videojs.com][plugin-list] <ide> techs/plugins made available to Video.js. For more information on media formats <ide> <ide> ## Q: How does Video.js choose which source to use? <ide> <del>When an array of sources is available, Video.js test each source in the order given. For each source, each tech in the [`techOrder`][techorder] will be checked to see if it can play it whether directly or via source handler (such as videojs-contrib-hls). The first match will be chosen. <add>When an array of sources is available, Video.js test each source in the order given. For each source, each tech in the [`techOrder`][techorder] will be checked to see if it can play it whether directly or via source handler (such as videojs-http-streaming). The first match will be chosen. <ide> <ide> ## Q: How do I autoplay a video? <ide> <ide> Yes! See the [text tracks guide][text-tracks] for information on using text trac <ide> <ide> ## Q: Does Video.js support HLS (HTTP Live streaming) video? <ide> <del>Video.js supports HLS video if the native HTML5 element supports HLS (e.g. Safari, Edge, <del>Chrome for Android, and iOS). For browsers without native support the [videojs-contrib-hls][hls] <del>project which adds support. <add>Video.js supports HLS. It will play using native support if the HTML5 element supports HLS (e.g. Safari, iOS, legacy Edge, or Chrome for Android). <add>On other browsers, it will play using our playback engine [videojs-http-streaming][hls]. <ide> <ide> Note that for non-native playback of HLS it is essential that the server hosting the video sets [CORS headers][cors]. <ide> <ide> ## Q: Does Video.js support MPEG DASH video? <ide> <del>MPEG DASH support is provided byt the [videojs-contrib-dash][dash] <del>package. <add>Video.js provides support for some DASH streams with our playback engine [videojs-http-streaming][hls]. <add> <add>Alternatively, [videojs-contrib-dash][dash] package can be used. <ide> <ide> Like HLS, DASH streams require [CORS headers][cors]. <ide> <ide> ## Q: Does Video.js support live video? <ide> <ide> Yes! Common formats for live are HLS or historically RTMP. <del>HLS is supported via [videojs-contrib-hls][hls]. and RTMP via [videojs-flash][flash]. <add>HLS is supported via [videojs-http-streaming][hls] and RTMP via [videojs-flash][flash]. <ide> <ide> ## Q: Can Video.js play YouTube videos? <ide> <ide> Yes! See [ReactJS integration example][react-guide]. <ide> <ide> [google-ima]: https://github.com/googleads/videojs-ima <ide> <del>[hls]: https://github.com/videojs/videojs-contrib-hls <add>[hls]: https://github.com/videojs/http-streaming <ide> <ide> [install-guide]: https://videojs.com/getting-started/ <ide>
1
Javascript
Javascript
strengthen flowtype of measurelayout
bcc58bce02acf51f6d5cff6e5457f447f12b1e30
<ide><path>Libraries/Renderer/shims/ReactNativeTypes.js <ide> class ReactNativeComponent<Props> extends React.Component<Props> { <ide> measure(callback: MeasureOnSuccessCallback): void {} <ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void {} <ide> measureLayout( <del> relativeToNativeNode: number | Object, <add> relativeToNativeNode: number | React.ElementRef<HostComponent<mixed>>, <ide> onSuccess: MeasureLayoutOnSuccessCallback, <ide> onFail?: () => void, <ide> ): void {} <ide> setNativeProps(nativeProps: Object): void {} <ide> } <ide> <ide> /** <del> * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync. <add> * This type keeps HostComponent and NativeMethodsMixin in sync. <ide> * It can also provide types for ReactNative applications that use NMM or refs. <ide> */ <del>export type NativeMethodsMixinType = { <add>type NativeMethods = $ReadOnly<{| <ide> blur(): void, <ide> focus(): void, <ide> measure(callback: MeasureOnSuccessCallback): void, <ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void, <ide> measureLayout( <del> relativeToNativeNode: number | Object, <add> relativeToNativeNode: number | React.ElementRef<HostComponent<mixed>>, <ide> onSuccess: MeasureLayoutOnSuccessCallback, <del> onFail: () => void, <add> onFail?: () => void, <ide> ): void, <ide> setNativeProps(nativeProps: Object): void, <del>}; <add>|}>; <ide> <del>export type HostComponent<T> = React.AbstractComponent< <del> T, <del> $ReadOnly<{| <del> blur(): void, <del> focus(): void, <del> measure(callback: MeasureOnSuccessCallback): void, <del> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void, <del> measureLayout( <del> relativeToNativeNode: number | Object, <del> onSuccess: MeasureLayoutOnSuccessCallback, <del> onFail?: () => void, <del> ): void, <del> setNativeProps(nativeProps: Object): void, <del> |}>, <del>>; <add>export type NativeMethodsMixinType = NativeMethods; <add>export type HostComponent<T> = React.AbstractComponent<T, NativeMethods>; <ide> <ide> type SecretInternalsType = { <ide> NativeMethodsMixin: NativeMethodsMixinType,
1
Javascript
Javascript
remove dump from test
b641181b938270af4a468e0718fe8a250538402f
<ide><path>test/ngAnimate/animateCssSpec.js <ide> describe("ngAnimate $animateCss", function() { <ide> // Let's flush the remaining amout of time for the timeout timer to kick in <ide> $timeout.flush(500); <ide> <del> dump(element.attr('style')); <ide> expect(element.css(prefix + 'transition-duration')).toBeOneOf('', '0s'); <ide> expect(element.css(prefix + 'transition-delay')).toBeOneOf('', '0s'); <ide> }));
1
Javascript
Javascript
use object static properties from primordials
a8806535d9e7db7bf20b3b3ef8f911320baf7511
<ide><path>lib/internal/abort_controller.js <ide> // in https://github.com/mysticatea/abort-controller (MIT license) <ide> <ide> const { <del> Object, <add> ObjectAssign, <add> ObjectDefineProperties, <ide> Symbol, <ide> } = primordials; <ide> <ide> function customInspect(self, obj, depth, options) { <ide> if (depth < 0) <ide> return self; <ide> <del> const opts = Object.assign({}, options, { <add> const opts = ObjectAssign({}, options, { <ide> depth: options.depth === null ? null : options.depth - 1 <ide> }); <ide> <ide> class AbortSignal extends EventTarget { <ide> } <ide> } <ide> <del>Object.defineProperties(AbortSignal.prototype, { <add>ObjectDefineProperties(AbortSignal.prototype, { <ide> aborted: { enumerable: true } <ide> }); <ide> <ide> class AbortController { <ide> } <ide> } <ide> <del>Object.defineProperties(AbortController.prototype, { <add>ObjectDefineProperties(AbortController.prototype, { <ide> signal: { enumerable: true }, <ide> abort: { enumerable: true } <ide> }); <ide><path>lib/internal/event_target.js <ide> const { <ide> Error, <ide> Map, <ide> NumberIsInteger, <del> Object, <add> ObjectAssign, <add> ObjectDefineProperties, <ide> ObjectDefineProperty, <ide> Symbol, <ide> SymbolFor, <ide> class Event { <ide> if (depth < 0) <ide> return name; <ide> <del> const opts = Object.assign({}, options, { <add> const opts = ObjectAssign({}, options, { <ide> depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth <ide> }); <ide> <ide> class Event { <ide> static BUBBLING_PHASE = 3; <ide> } <ide> <del>Object.defineProperty(Event.prototype, SymbolToStringTag, { <add>ObjectDefineProperty(Event.prototype, SymbolToStringTag, { <ide> writable: false, <ide> enumerable: false, <ide> configurable: true, <ide> class EventTarget { <ide> if (depth < 0) <ide> return name; <ide> <del> const opts = Object.assign({}, options, { <add> const opts = ObjectAssign({}, options, { <ide> depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth <ide> }); <ide> <ide> return `${name} ${inspect({}, opts)}`; <ide> } <ide> } <ide> <del>Object.defineProperties(EventTarget.prototype, { <add>ObjectDefineProperties(EventTarget.prototype, { <ide> addEventListener: { enumerable: true }, <ide> removeEventListener: { enumerable: true }, <ide> dispatchEvent: { enumerable: true } <ide> }); <del>Object.defineProperty(EventTarget.prototype, SymbolToStringTag, { <add>ObjectDefineProperty(EventTarget.prototype, SymbolToStringTag, { <ide> writable: false, <ide> enumerable: false, <ide> configurable: true, <ide> class NodeEventTarget extends EventTarget { <ide> } <ide> } <ide> <del>Object.defineProperties(NodeEventTarget.prototype, { <add>ObjectDefineProperties(NodeEventTarget.prototype, { <ide> setMaxListeners: { enumerable: true }, <ide> getMaxListeners: { enumerable: true }, <ide> eventNames: { enumerable: true }, <ide> function emitUnhandledRejectionOrErr(that, err, event) { <ide> function defineEventHandler(emitter, name) { <ide> // 8.1.5.1 Event handlers - basically `on[eventName]` attributes <ide> let eventHandlerValue; <del> Object.defineProperty(emitter, `on${name}`, { <add> ObjectDefineProperty(emitter, `on${name}`, { <ide> get() { <ide> return eventHandlerValue; <ide> }, <ide><path>lib/internal/modules/cjs/loader.js <ide> const { <ide> ObjectGetOwnPropertyDescriptor, <ide> ObjectGetPrototypeOf, <ide> ObjectKeys, <add> ObjectPrototype, <ide> ObjectPrototypeHasOwnProperty, <ide> ObjectSetPrototypeOf, <ide> ReflectSet, <ide> const CircularRequirePrototypeWarningProxy = new Proxy({}, { <ide> } <ide> }); <ide> <del>// Object.prototype and ObjectPrototype refer to our 'primordials' versions <del>// and are not identical to the versions on the global object. <del>const PublicObjectPrototype = global.Object.prototype; <del> <ide> function getExportsForCircularRequire(module) { <ide> if (module.exports && <ide> !isProxy(module.exports) && <del> ObjectGetPrototypeOf(module.exports) === PublicObjectPrototype && <add> ObjectGetPrototypeOf(module.exports) === ObjectPrototype && <ide> // Exclude transpiled ES6 modules / TypeScript code because those may <ide> // employ unusual patterns for accessing 'module.exports'. That should <ide> // be okay because ES6 modules have a different approach to circular <ide> Module._load = function(request, parent, isMain) { <ide> !isProxy(module.exports) && <ide> ObjectGetPrototypeOf(module.exports) === <ide> CircularRequirePrototypeWarningProxy) { <del> ObjectSetPrototypeOf(module.exports, PublicObjectPrototype); <add> ObjectSetPrototypeOf(module.exports, ObjectPrototype); <ide> } <ide> } <ide> <ide><path>lib/timers.js <ide> 'use strict'; <ide> <ide> const { <del> ObjectCreate, <ide> MathTrunc, <del> Object, <add> ObjectCreate, <add> ObjectDefineProperty, <ide> SymbolToPrimitive <ide> } = primordials; <ide> <ide> function setTimeout(callback, after, arg1, arg2, arg3) { <ide> return timeout; <ide> } <ide> <del>Object.defineProperty(setTimeout, customPromisify, { <add>ObjectDefineProperty(setTimeout, customPromisify, { <ide> enumerable: true, <ide> get() { <ide> if (!timersPromises) <ide> function setImmediate(callback, arg1, arg2, arg3) { <ide> return new Immediate(callback, args); <ide> } <ide> <del>Object.defineProperty(setImmediate, customPromisify, { <add>ObjectDefineProperty(setImmediate, customPromisify, { <ide> enumerable: true, <ide> get() { <ide> if (!timersPromises)
4
Go
Go
add flag to set default graph driver
6dbeed89c061b85551ab638f93282d87de8ab929
<ide><path>config.go <ide> type DaemonConfig struct { <ide> BridgeIface string <ide> DefaultIp net.IP <ide> InterContainerCommunication bool <add> GraphDriver string <ide> } <ide> <ide> // ConfigFromJob creates and returns a new DaemonConfig object <ide> func ConfigFromJob(job *engine.Job) *DaemonConfig { <ide> } <ide> config.DefaultIp = net.ParseIP(job.Getenv("DefaultIp")) <ide> config.InterContainerCommunication = job.GetenvBool("InterContainerCommunication") <add> config.GraphDriver = job.Getenv("GraphDriver") <ide> return &config <ide> } <ide><path>docker/docker.go <ide> func main() { <ide> flEnableIptables := flag.Bool("iptables", true, "Disable iptables within docker") <ide> flDefaultIp := flag.String("ip", "0.0.0.0", "Default ip address to use when binding a containers ports") <ide> flInterContainerComm := flag.Bool("icc", true, "Enable inter-container communication") <add> flGraphDriver := flag.String("graph-driver", "", "For docker to use a specific graph driver") <ide> <ide> flag.Parse() <ide> <ide> func main() { <ide> job.Setenv("BridgeIface", *bridgeName) <ide> job.Setenv("DefaultIp", *flDefaultIp) <ide> job.SetenvBool("InterContainerCommunication", *flInterContainerComm) <add> job.Setenv("GraphDriver", *flGraphDriver) <ide> if err := job.Run(); err != nil { <ide> log.Fatal(err) <ide> } <ide><path>graphdriver/driver.go <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/utils" <del> "os" <ide> "path" <ide> ) <ide> <add>var DefaultDriver string <add> <ide> type InitFunc func(root string) (Driver, error) <ide> <ide> type Driver interface { <ide> func GetDriver(name, home string) (Driver, error) { <ide> func New(root string) (Driver, error) { <ide> var driver Driver <ide> var lastError error <del> // Use environment variable DOCKER_DRIVER to force a choice of driver <del> if name := os.Getenv("DOCKER_DRIVER"); name != "" { <del> return GetDriver(name, root) <add> <add> if DefaultDriver != "" { <add> return GetDriver(DefaultDriver, root) <ide> } <ide> // Check for priority drivers first <ide> for _, name := range priority { <ide><path>runtime.go <ide> func NewRuntime(config *DaemonConfig) (*Runtime, error) { <ide> } <ide> <ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <add> <add> // Set the default driver <add> graphdriver.DefaultDriver = config.GraphDriver <add> <ide> // Load storage driver <ide> driver, err := graphdriver.New(config.Root) <ide> if err != nil {
4
Text
Text
update image preprocessing docs
34b8b57c2fdf10e3490753bae1f358f81dba966f
<ide><path>docs/templates/preprocessing/image.md <ide> keras.preprocessing.image.ImageDataGenerator(featurewise_center=False, <ide> cval=0., <ide> horizontal_flip=False, <ide> vertical_flip=False, <del> dim_ordering='th') <add> rescale=None, <add> dim_ordering=K.image_dim_ordering()) <ide> ``` <ide> <ide> Generate batches of tensor image data with real-time data augmentation. The data will be looped over (in batches) indefinitely. <ide> Generate batches of tensor image data with real-time data augmentation. The data <ide> - __cval__: Float or Int. Value used for points outside the boundaries when `fill_mode = "constant"`. <ide> - __horizontal_flip__: Boolean. Randomly flip inputs horizontally. <ide> - __vertical_flip__: Boolean. Randomly flip inputs vertically. <add> - __rescale__: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, <add> otherwise we multiply the data by the value provided (before applying <add> any other transformation). <ide> - __dim_ordering__: One of {"th", "tf"}. <ide> "tf" mode means that the images should have shape `(samples, width, height, channels)`, <ide> "th" mode means that the images should have shape `(samples, channels, width, height)`. <ide> Generate batches of tensor image data with real-time data augmentation. The data <ide> If you never set it, then it will be "th". <ide> <ide> - __Methods__: <del> - __fit(X)__: Required if featurewise_center or featurewise_std_normalization or zca_whitening. Compute necessary quantities on some sample data. <add> - __fit(X)__: Compute the internal data stats related to the data-dependent transformations, based on an array of sample data. <add> Only required if featurewise_center or featurewise_std_normalization or zca_whitening. <ide> - __Arguments__: <ide> - __X__: sample data. <ide> - __augment__: Boolean (default: False). Whether to fit on randomly augmented samples. <ide> - __rounds__: int (default: 1). If augment, how many augmentation passes over the data to use. <del> - __flow(X, y)__: <add> - __flow(X, y)__: Takes numpy data & label arrays, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. <ide> - __Arguments__: <ide> - __X__: data. <ide> - __y__: labels. <ide> - __batch_size__: int (default: 32). <ide> - __shuffle__: boolean (defaut: False). <del> - __save_to_dir__: None or str. This allows you to optimally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing). <del> - __save_prefix__: str. Prefix to use for filenames of saved pictures. <del> - __save_format__: one of "png", jpeg". <add> - __save_to_dir__: None or str (default: None). This allows you to optimally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing). <add> - __save_prefix__: str (default: `''`). Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set). <add> - __save_format__: one of "png", jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg". <add> - ___yields__: Tuples of `(x, y)` where `x` is a numpy array of image data and `y` is a numpy array of corresponding labels. <add> The generator loops indefinitely. <add> - __flow_from_directory(directory)__: Takes the path to a directory, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. <add> - __Arguments__: <add> - __directory: path to the target directory. It should contain one subdirectory per class, <add> and the subdirectories should contain PNG or JPG images, e.g.: <add> ``` <add> data/ <-- this is our "directory" argument <add> dogs/ <add> dog001.jpg <add> dog002.jpg <add> ... <add> cats/ <add> cat001.jpg <add> cat002.jpg <add> ... <add> ``` <add> - __target_size__: tuple of integers, default: `(256, 256)`. The dimensions to which all images found will be resized. <add> - __color_mode__: one of "grayscale", "rbg". Default: "rgb". Whether the images will be converted to have 1 or 3 color channels. <add> - __classes__: optional list of class subdirectories (e.g. `['dogs', 'cats']`). Default: None. If not provided, the list of classes will be automatically infered (and the order of the classes, which will map to the label indices, will be alphanumeral). <add> - __class_mode__: one of "categorical", "binary", "sparse" or None. Default: "categorical". Determines the type of label arrays that are returned: "categorical" will be 2D one-hot encoded labels, "binary" will be 1D binary labels, "sparse" will be 1D integer labels. If None, no labels are returned (the generator will only yield batches of image data, which is useful to use `model.predict_generator()`, `model.evaluate_generator()`, etc.). <add> - __batch_size__: size of the batches of data (default: 32). <add> - __shuffle__: whether to shuffle the data (default: True) <add> - __seed__: optional random seed for shuffling. <add> - __save_to_dir__: None or str (default: None). This allows you to optimally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing). <add> - __save_prefix__: str. Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set). <add> - __save_format__: one of "png", jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg". <add> <add> <add>- __Examples__: <add> <add>Example of using `.flow(X, y)`: <ide> <del>- __Example__: <ide> ```python <ide> (X_train, y_train), (X_test, y_test) = cifar10.load_data(test_split=0.1) <ide> Y_train = np_utils.to_categorical(y_train, nb_classes) <ide> for e in range(nb_epoch): <ide> # the generator loops indefinitely <ide> break <ide> ``` <add> <add>Example of using `.flow_from_directory(directory)`: <add> <add>```python <add>train_datagen = ImageDataGenerator( <add> rescale=1./255, <add> shear_range=0.2, <add> zoom_range=0.2, <add> horizontal_flip=True) <add> <add>test_datagen = ImageDataGenerator(rescale=1./255) <add> <add>train_generator = train_datagen.flow_from_directory( <add> 'data/train', <add> target_size=(150, 150), <add> batch_size=32, <add> class_mode='binary') <add> <add>validation_generator = test_datagen.flow_from_directory( <add> 'data/validation', <add> target_size=(150, 150), <add> batch_size=32, <add> class_mode='binary') <add> <add>model.fit_generator( <add> train_generator, <add> samples_per_epoch=2000, <add> nb_epoch=50, <add> validation_data=validation_generator, <add> nb_val_samples=800) <add>``` <ide>\ No newline at end of file
1
Mixed
Ruby
add bigint primary key support for mysql
a327a9dc583e8b7fea030cfe9cda74af632ef210
<ide><path>activerecord/CHANGELOG.md <add>* Add bigint primary key support for MySQL. <add> <add> Example: <add> <add> create_table :foos, id: :bigint do |t| <add> end <add> <add> *Ryuta Kamizono* <add> <ide> * Support for any type primary key. <ide> <ide> Fixes #14194. <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb <ide> def column_options(o) <ide> column_options[:column] = o <ide> column_options[:first] = o.first <ide> column_options[:after] = o.after <add> column_options[:auto_increment] = o.auto_increment <ide> column_options[:primary_key] = o.primary_key <ide> column_options <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, : <ide> # are typically created by methods in TableDefinition, and added to the <ide> # +columns+ attribute of said TableDefinition object, in order to be used <ide> # for generating a number of table creation or table changing SQL statements. <del> class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key, :sql_type, :cast_type) #:nodoc: <add> class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :auto_increment, :primary_key, :sql_type, :cast_type) #:nodoc: <ide> <ide> def primary_key? <ide> primary_key || type.to_sym == :primary_key <ide> def new_column_definition(name, type, options) # :nodoc: <ide> column.null = options[:null] <ide> column.first = options[:first] <ide> column.after = options[:after] <add> column.auto_increment = options[:auto_increment] <ide> column.primary_key = type == :primary_key || options[:primary_key] <ide> column <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> module ConnectionAdapters <ide> class AbstractMysqlAdapter < AbstractAdapter <ide> include Savepoints <ide> <add> class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition <add> def primary_key(name, type = :primary_key, options = {}) <add> options[:auto_increment] ||= type == :bigint <add> super <add> end <add> end <add> <ide> class SchemaCreation < AbstractAdapter::SchemaCreation <ide> def visit_AddColumn(o) <ide> add_column_position!(super, column_options(o)) <ide> def extract_foreign_key_action(structure, name, action) # :nodoc: <ide> end <ide> end <ide> <add> def create_table_definition(name, temporary, options, as = nil) # :nodoc: <add> TableDefinition.new(native_database_types, name, temporary, options, as) <add> end <add> <ide> class MysqlString < Type::String # :nodoc: <ide> def type_cast_for_database(value) <ide> case value <ide><path>activerecord/test/cases/primary_keys_test.rb <ide> def test_primary_key_method_with_ansi_quotes <ide> end <ide> end <ide> <del>if current_adapter?(:PostgreSQLAdapter) <add>if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter) <ide> class PrimaryKeyBigSerialTest < ActiveRecord::TestCase <ide> self.use_transactional_fixtures = false <ide> <ide> class Widget < ActiveRecord::Base <ide> <ide> setup do <ide> @connection = ActiveRecord::Base.connection <del> @connection.create_table(:widgets, id: :bigserial) { |t| } <add> if current_adapter?(:PostgreSQLAdapter) <add> @connection.create_table(:widgets, id: :bigserial, force: true) <add> else <add> @connection.create_table(:widgets, id: :bigint, force: true) <add> end <ide> end <ide> <ide> teardown do <del> @connection.drop_table :widgets <add> @connection.execute("DROP TABLE IF EXISTS widgets") <ide> end <ide> <del> def test_bigserial_primary_key <del> assert_equal "id", Widget.primary_key <del> assert_equal :integer, Widget.columns_hash[Widget.primary_key].type <add> test "primary key column type with bigserial" do <add> column_type = Widget.type_for_attribute(Widget.primary_key) <add> assert_equal :integer, column_type.type <add> assert_equal 8, column_type.limit <add> end <ide> <add> test "primary key with bigserial are automatically numbered" do <ide> widget = Widget.create! <ide> assert_not_nil widget.id <ide> end
5
PHP
PHP
add documentation for form
db1681f7298305dc420c90880b123f8f8a8c4555
<ide><path>src/Form/Form.php <ide> * or to other permanent datastores. Ideal for implement forms on top of <ide> * API services, or contact forms. <ide> * <add> * ### Building a form <add> * <add> * This class is most useful when subclassed. In a subclass you <add> * should define the `_buildSchema`, `_buildValidator` and optionally, <add> * the `_execute` methods. These allow you to declare your form's <add> * fields, validation and primary action respectively. <add> * <add> * You can also define the validation and schema by chaining method <add> * calls off of `$form->schema()` and `$form->validator()`. <add> * <add> * Forms are conventionally placed in the `App\Form` namespace. <ide> */ <ide> class Form { <ide> <add>/** <add> * The schema used by this form. <add> * <add> * @var \Cake\Form\Schema; <add> */ <ide> protected $_schema; <add> <add>/** <add> * The errors if any <add> * <add> * @var array <add> */ <ide> protected $_errors = []; <add> <add>/** <add> * The validator used by this form. <add> * <add> * @var \Cake\Valiation\Validator; <add> */ <ide> protected $_validator; <ide> <add>/** <add> * Get/Set the schema for this form. <add> * <add> * This method will call `_buildSchema()` when the schema <add> * is first built. This hook method lets you configure the <add> * schema or load a pre-defined one. <add> * <add> * @param \Cake\Form\Schema $schema The schema to set, or null. <add> * @return \Cake\Form\Schema the schema instance. <add> */ <ide> public function schema(Schema $schema = null) { <ide> if ($schema === null && empty($this->_schema)) { <ide> $schema = $this->_buildSchema(new Schema()); <ide> public function schema(Schema $schema = null) { <ide> return $this->_schema; <ide> } <ide> <add>/** <add> * A hook method intended to be implemented by subclasses. <add> * <add> * You can use this method to define the schema using <add> * the methods on Cake\Form\Schema, or loads a pre-defined <add> * schema from a concrete class. <add> * <add> * @param \Cake\Form\Schema $schema The schema to customize. <add> * @return \Cake\Form\Schema The schema to use. <add> */ <ide> protected function _buildSchema($schema) { <ide> return $schema; <ide> } <ide> <add>/** <add> * Get/Set the validator for this form. <add> * <add> * This method will call `_buildValidator()` when the validator <add> * is first built. This hook method lets you configure the <add> * validator or load a pre-defined one. <add> * <add> * @param \Cake\Validation\Validator $validator The validator to set, or null. <add> * @return \Cake\Validation\Validator the validator instance. <add> */ <ide> public function validator(Validator $validator = null) { <ide> if ($validator === null && empty($this->_validator)) { <ide> $validator = $this->_buildValidator(new Validator()); <ide> public function validator(Validator $validator = null) { <ide> return $this->_validator; <ide> } <ide> <add>/** <add> * A hook method intended to be implemented by subclasses. <add> * <add> * You can use this method to define the validator using <add> * the methods on Cake\Validation\Validator or loads a pre-defined <add> * validator from a concrete class. <add> * <add> * @param \Cake\Validation\Validator $validator The validator to customize. <add> * @return \Cake\Validation\Validator The validator to use. <add> */ <ide> protected function _buildValidator($validator) { <ide> return $validator; <ide> } <ide> <add>/** <add> * Used to check if $data passes this form's validation. <add> * <add> * @param array $data The data to check. <add> * @return bool Whether or not the data is valid. <add> */ <ide> public function isValid($data) { <ide> $validator = $this->validator(); <ide> $this->_errors = $validator->errors($data); <ide> return count($this->_errors) === 0; <ide> } <ide> <add>/** <add> * Get the errors in the form <add> * <add> * Will return the errors from the last call <add> * to `isValid()` or `execute()`. <add> * <add> * @return array Last set validation errors. <add> */ <ide> public function errors() { <ide> return $this->_errors; <ide> } <ide> <add>/** <add> * Execute the form if it is valid. <add> * <add> * First validates the form, then calls the `_execute()` hook method. <add> * This hook method can be implemented in subclasses to perform <add> * the action of the form. This may be sending email, interacting <add> * with a remote API, or anything else you may need. <add> * <add> * @return bool False on validation failure, otherwise returns the <add> * result of the `_execute()` method. <add> */ <ide> public function execute($data) { <ide> if (!$this->isValid($data)) { <ide> return false; <ide> } <ide> return $this->_execute($data); <ide> } <ide> <add>/** <add> * Hook method to be implemented in subclasses. <add> * <add> * Used by `execute()` to execute the form's action. <add> * <add> * @return bool <add> */ <ide> protected function _execute($data) { <add> return true; <ide> } <ide> <ide> } <ide><path>tests/TestCase/Form/FormTest.php <ide> public function testExecuteInvalid() { <ide> $this->assertFalse($form->execute($data)); <ide> } <ide> <add>/** <add> * test execute() when data is valid. <add> * <add> * @return void <add> */ <ide> public function testExecuteValid() { <ide> $form = $this->getMock('Cake\Form\Form', ['_execute']); <ide> $form->validator() <ide> public function testExecuteValid() { <ide> ]; <ide> $form->expects($this->once()) <ide> ->method('_execute') <del> ->with($data); <add> ->with($data) <add> ->will($this->returnValue(true)); <ide> <del> $this->assertNull($form->execute($data)); <add> $this->assertTrue($form->execute($data)); <ide> } <ide> <ide> }
2
Ruby
Ruby
reduce calls to scope_level
374d66be3e9e994bbe8ad2702ee2209c24b581b0
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def root(path, options={}) <ide> raise ArgumentError, "must be called with a path and/or options" <ide> end <ide> <del> if @scope.scope_level == :resources <add> if @scope.resources? <ide> with_scope_level(:root) do <ide> scope(parent_resource.path) do <ide> super(options) <ide> def nested? <ide> scope_level == :nested <ide> end <ide> <add> def resources? <add> scope_level == :resources <add> end <add> <ide> def resource_scope? <ide> RESOURCE_SCOPES.include? scope_level <ide> end
1
Java
Java
fix incomplete log message
d554229981381979d63c3228ae0195a376fa3b18
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java <ide> private void scheduleSessionTask() { <ide> if (this.sessionCleanupTask != null) { <ide> return; <ide> } <del> final List<String> removedSessionIds = new ArrayList<String>(); <ide> this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() { <ide> @Override <ide> public void run() { <add> List<String> removedIds = new ArrayList<String>(); <ide> for (SockJsSession session : sessions.values()) { <ide> try { <ide> if (session.getTimeSinceLastActive() > getDisconnectDelay()) { <ide> sessions.remove(session.getId()); <add> removedIds.add(session.getId()); <ide> session.close(); <ide> } <ide> } <ide> public void run() { <ide> logger.debug("Failed to close " + session, ex); <ide> } <ide> } <del> if (logger.isDebugEnabled() && !removedSessionIds.isEmpty()) { <del> logger.debug("Closed " + removedSessionIds.size() + " sessions " + removedSessionIds); <del> removedSessionIds.clear(); <add> if (logger.isDebugEnabled() && !removedIds.isEmpty()) { <add> logger.debug("Closed " + removedIds.size() + " sessions: " + removedIds); <ide> } <ide> } <ide> }, getDisconnectDelay());
1
Python
Python
replace pipe type with callable in language
6f9d630f7e9c11d8d5f7ba37e3764ef3630c172d
<ide><path>spacy/cli/debug_data.py <ide> from ..training import Example, remove_bilu_prefix <ide> from ..training.initialize import get_sourced_components <ide> from ..schemas import ConfigSchemaTraining <add>from ..pipeline import TrainablePipe <ide> from ..pipeline._parser_internals import nonproj <ide> from ..pipeline._parser_internals.nonproj import DELIMITER <ide> from ..pipeline import Morphologizer, SpanCategorizer <ide> def _get_labels_from_model(nlp: Language, factory_name: str) -> Set[str]: <ide> labels: Set[str] = set() <ide> for pipe_name in pipe_names: <ide> pipe = nlp.get_pipe(pipe_name) <add> assert isinstance(pipe, TrainablePipe) <ide> labels.update(pipe.labels) <ide> return labels <ide> <ide><path>spacy/language.py <ide> from .compat import Literal <ide> <ide> <del>if TYPE_CHECKING: <del> from .pipeline import Pipe # noqa: F401 <add>PipeCallable = Callable[[Doc], Doc] <ide> <ide> <ide> # This is the base config will all settings (training etc.) <ide> def __init__( <ide> self.vocab: Vocab = vocab <ide> if self.lang is None: <ide> self.lang = self.vocab.lang <del> self._components: List[Tuple[str, "Pipe"]] = [] <add> self._components: List[Tuple[str, PipeCallable]] = [] <ide> self._disabled: Set[str] = set() <ide> self.max_length = max_length <ide> # Create the default tokenizer from the default config <ide> def factory_names(self) -> List[str]: <ide> return SimpleFrozenList(names) <ide> <ide> @property <del> def components(self) -> List[Tuple[str, "Pipe"]]: <add> def components(self) -> List[Tuple[str, PipeCallable]]: <ide> """Get all (name, component) tuples in the pipeline, including the <ide> currently disabled components. <ide> """ <ide> def component_names(self) -> List[str]: <ide> return SimpleFrozenList(names, error=Errors.E926.format(attr="component_names")) <ide> <ide> @property <del> def pipeline(self) -> List[Tuple[str, "Pipe"]]: <add> def pipeline(self) -> List[Tuple[str, PipeCallable]]: <ide> """The processing pipeline consisting of (name, component) tuples. The <ide> components are called on the Doc in order as it passes through the <ide> pipeline. <ide> <del> RETURNS (List[Tuple[str, Pipe]]): The pipeline. <add> RETURNS (List[Tuple[str, Callable[[Doc], Doc]]]): The pipeline. <ide> """ <ide> pipes = [(n, p) for n, p in self._components if n not in self._disabled] <ide> return SimpleFrozenList(pipes, error=Errors.E926.format(attr="pipeline")) <ide> def component( <ide> assigns: Iterable[str] = SimpleFrozenList(), <ide> requires: Iterable[str] = SimpleFrozenList(), <ide> retokenizes: bool = False, <del> func: Optional["Pipe"] = None, <add> func: Optional[PipeCallable] = None, <ide> ) -> Callable[..., Any]: <ide> """Register a new pipeline component. Can be used for stateless function <ide> components that don't require a separate factory. Can be used as a <ide> def component( <ide> e.g. "token.ent_id". Used for pipeline analysis. <ide> retokenizes (bool): Whether the component changes the tokenization. <ide> Used for pipeline analysis. <del> func (Optional[Callable]): Factory function if not used as a decorator. <add> func (Optional[Callable[[Doc], Doc]): Factory function if not used as a decorator. <ide> <ide> DOCS: https://spacy.io/api/language#component <ide> """ <ide> def component( <ide> raise ValueError(Errors.E853.format(name=name)) <ide> component_name = name if name is not None else util.get_object_name(func) <ide> <del> def add_component(component_func: "Pipe") -> Callable: <add> def add_component(component_func: PipeCallable) -> Callable: <ide> if isinstance(func, type): # function is a class <ide> raise ValueError(Errors.E965.format(name=component_name)) <ide> <del> def factory_func(nlp, name: str) -> "Pipe": <add> def factory_func(nlp, name: str) -> PipeCallable: <ide> return component_func <ide> <ide> internal_name = cls.get_factory_name(name) <ide> def analyze_pipes( <ide> print_pipe_analysis(analysis, keys=keys) <ide> return analysis <ide> <del> def get_pipe(self, name: str) -> "Pipe": <add> def get_pipe(self, name: str) -> PipeCallable: <ide> """Get a pipeline component for a given component name. <ide> <ide> name (str): Name of pipeline component to get. <ide> def create_pipe( <ide> config: Dict[str, Any] = SimpleFrozenDict(), <ide> raw_config: Optional[Config] = None, <ide> validate: bool = True, <del> ) -> "Pipe": <add> ) -> PipeCallable: <ide> """Create a pipeline component. Mostly used internally. To create and <ide> add a component to the pipeline, you can use nlp.add_pipe. <ide> <ide> def create_pipe( <ide> raw_config (Optional[Config]): Internals: the non-interpolated config. <ide> validate (bool): Whether to validate the component config against the <ide> arguments and types expected by the factory. <del> RETURNS (Pipe): The pipeline component. <add> RETURNS (Callable[[Doc], Doc]): The pipeline component. <ide> <ide> DOCS: https://spacy.io/api/language#create_pipe <ide> """ <ide> def create_pipe( <ide> <ide> def create_pipe_from_source( <ide> self, source_name: str, source: "Language", *, name: str <del> ) -> Tuple["Pipe", str]: <add> ) -> Tuple[PipeCallable, str]: <ide> """Create a pipeline component by copying it from an existing model. <ide> <ide> source_name (str): Name of the component in the source pipeline. <ide> source (Language): The source nlp object to copy from. <ide> name (str): Optional alternative name to use in current pipeline. <del> RETURNS (Tuple[Callable, str]): The component and its factory name. <add> RETURNS (Tuple[Callable[[Doc], Doc], str]): The component and its factory name. <ide> """ <ide> # Check source type <ide> if not isinstance(source, Language): <ide> def add_pipe( <ide> config: Dict[str, Any] = SimpleFrozenDict(), <ide> raw_config: Optional[Config] = None, <ide> validate: bool = True, <del> ) -> "Pipe": <add> ) -> PipeCallable: <ide> """Add a component to the processing pipeline. Valid components are <ide> callables that take a `Doc` object, modify it and return it. Only one <ide> of before/after/first/last can be set. Default behaviour is "last". <ide> def add_pipe( <ide> raw_config (Optional[Config]): Internals: the non-interpolated config. <ide> validate (bool): Whether to validate the component config against the <ide> arguments and types expected by the factory. <del> RETURNS (Pipe): The pipeline component. <add> RETURNS (Callable[[Doc], Doc]): The pipeline component. <ide> <ide> DOCS: https://spacy.io/api/language#add_pipe <ide> """ <ide> def replace_pipe( <ide> *, <ide> config: Dict[str, Any] = SimpleFrozenDict(), <ide> validate: bool = True, <del> ) -> "Pipe": <add> ) -> PipeCallable: <ide> """Replace a component in the pipeline. <ide> <ide> name (str): Name of the component to replace. <ide> def replace_pipe( <ide> component. Will be merged with default config, if available. <ide> validate (bool): Whether to validate the component config against the <ide> arguments and types expected by the factory. <del> RETURNS (Pipe): The new pipeline component. <add> RETURNS (Callable[[Doc], Doc]): The new pipeline component. <ide> <ide> DOCS: https://spacy.io/api/language#replace_pipe <ide> """ <ide> def rename_pipe(self, old_name: str, new_name: str) -> None: <ide> init_cfg = self._config["initialize"]["components"].pop(old_name) <ide> self._config["initialize"]["components"][new_name] = init_cfg <ide> <del> def remove_pipe(self, name: str) -> Tuple[str, "Pipe"]: <add> def remove_pipe(self, name: str) -> Tuple[str, PipeCallable]: <ide> """Remove a component from the pipeline. <ide> <ide> name (str): Name of the component to remove. <del> RETURNS (tuple): A `(name, component)` tuple of the removed component. <add> RETURNS (Tuple[str, Callable[[Doc], Doc]]): A `(name, component)` tuple of the removed component. <ide> <ide> DOCS: https://spacy.io/api/language#remove_pipe <ide> """ <ide> def resume_training(self, *, sgd: Optional[Optimizer] = None) -> Optimizer: <ide> <ide> def set_error_handler( <ide> self, <del> error_handler: Callable[[str, "Pipe", List[Doc], Exception], NoReturn], <add> error_handler: Callable[[str, PipeCallable, List[Doc], Exception], NoReturn], <ide> ): <del> """Set an error handler object for all the components in the pipeline that implement <del> a set_error_handler function. <add> """Set an error handler object for all the components in the pipeline <add> that implement a set_error_handler function. <ide> <del> error_handler (Callable[[str, Pipe, List[Doc], Exception], NoReturn]): <del> Function that deals with a failing batch of documents. This callable function should take in <del> the component's name, the component itself, the offending batch of documents, and the exception <del> that was thrown. <add> error_handler (Callable[[str, Callable[[Doc], Doc], List[Doc], Exception], NoReturn]): <add> Function that deals with a failing batch of documents. This callable <add> function should take in the component's name, the component itself, <add> the offending batch of documents, and the exception that was thrown. <ide> DOCS: https://spacy.io/api/language#set_error_handler <ide> """ <ide> self.default_error_handler = error_handler <ide><path>spacy/tests/pipeline/test_textcat.py <ide> def test_textcat_loss(multi_label: bool, expected_loss: float): <ide> textcat = nlp.add_pipe("textcat_multilabel") <ide> else: <ide> textcat = nlp.add_pipe("textcat") <del> textcat.initialize(lambda: train_examples) <ide> assert isinstance(textcat, TextCategorizer) <add> textcat.initialize(lambda: train_examples) <ide> scores = textcat.model.ops.asarray( <ide> [[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], dtype="f" # type: ignore <ide> ) <ide><path>spacy/util.py <ide> <ide> if TYPE_CHECKING: <ide> # This lets us add type hints for mypy etc. without causing circular imports <del> from .language import Language # noqa: F401 <del> from .pipeline import Pipe # noqa: F401 <add> from .language import Language, PipeCallable # noqa: F401 <ide> from .tokens import Doc, Span # noqa: F401 <ide> from .vocab import Vocab # noqa: F401 <ide> <ide> def check_bool_env_var(env_var: str) -> bool: <ide> <ide> def _pipe( <ide> docs: Iterable["Doc"], <del> proc: "Pipe", <add> proc: "PipeCallable", <ide> name: str, <del> default_error_handler: Callable[[str, "Pipe", List["Doc"], Exception], NoReturn], <add> default_error_handler: Callable[[str, "PipeCallable", List["Doc"], Exception], NoReturn], <ide> kwargs: Mapping[str, Any], <ide> ) -> Iterator["Doc"]: <ide> if hasattr(proc, "pipe"):
4
Go
Go
restrict domain name to 255 characters
b2f05c220721d5ef9a31fc259e3f6c2c057ab4ab
<ide><path>opts/opts.go <ide> func validateDomain(val string) (string, error) { <ide> return "", fmt.Errorf("%s is not a valid domain", val) <ide> } <ide> ns := domainRegexp.FindSubmatch([]byte(val)) <del> if len(ns) > 0 { <add> if len(ns) > 0 && len(ns[1]) < 255 { <ide> return string(ns[1]), nil <ide> } <ide> return "", fmt.Errorf("%s is not a valid domain", val) <ide><path>opts/opts_test.go <ide> func TestValidateDnsSearch(t *testing.T) { <ide> `foo.bar-.baz`, <ide> `foo.-bar`, <ide> `foo.-bar.baz`, <add> `foo.bar.baz.this.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbe`, <ide> } <ide> <ide> for _, domain := range valid {
2
Python
Python
make sqlmigrate ignore the runpython operation
8a3e543f268ba027a631274d1cfe44db64ad9025
<ide><path>django/db/migrations/executor.py <ide> def collect_sql(self, plan): <ide> with self.connection.schema_editor(collect_sql=True) as schema_editor: <ide> project_state = self.loader.graph.project_state((migration.app_label, migration.name), at_end=False) <ide> if not backwards: <del> migration.apply(project_state, schema_editor) <add> migration.apply(project_state, schema_editor, collect_sql=True) <ide> else: <del> migration.unapply(project_state, schema_editor) <add> migration.unapply(project_state, schema_editor, collect_sql=True) <ide> statements.extend(schema_editor.collected_sql) <ide> return statements <ide> <ide><path>django/db/migrations/migration.py <ide> def mutate_state(self, project_state): <ide> operation.state_forwards(self.app_label, new_state) <ide> return new_state <ide> <del> def apply(self, project_state, schema_editor): <add> def apply(self, project_state, schema_editor, collect_sql=False): <ide> """ <ide> Takes a project_state representing all migrations prior to this one <ide> and a schema_editor for a live database and applies the migration <ide> def apply(self, project_state, schema_editor): <ide> Migrations. <ide> """ <ide> for operation in self.operations: <add> # If this operation cannot be represented as SQL, place a comment <add> # there instead <add> if collect_sql and not operation.reduces_to_sql: <add> schema_editor.collected_sql.append("--") <add> schema_editor.collected_sql.append("-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:") <add> schema_editor.collected_sql.append("-- %s" % operation.describe()) <add> schema_editor.collected_sql.append("--") <add> continue <ide> # Get the state after the operation has run <ide> new_state = project_state.clone() <ide> operation.state_forwards(self.app_label, new_state) <ide> def apply(self, project_state, schema_editor): <ide> project_state = new_state <ide> return project_state <ide> <del> def unapply(self, project_state, schema_editor): <add> def unapply(self, project_state, schema_editor, collect_sql=False): <ide> """ <ide> Takes a project_state representing all migrations prior to this one <ide> and a schema_editor for a live database and applies the migration <ide> def unapply(self, project_state, schema_editor): <ide> # We need to pre-calculate the stack of project states <ide> to_run = [] <ide> for operation in self.operations: <add> # If this operation cannot be represented as SQL, place a comment <add> # there instead <add> if collect_sql and not operation.reduces_to_sql: <add> schema_editor.collected_sql.append("--") <add> schema_editor.collected_sql.append("-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:") <add> schema_editor.collected_sql.append("-- %s" % operation.describe()) <add> schema_editor.collected_sql.append("--") <add> continue <add> # If it's irreversible, error out <ide> if not operation.reversible: <del> raise Migration.IrreversibleError("Operation %s in %s is not reversible" % (operation, sekf)) <add> raise Migration.IrreversibleError("Operation %s in %s is not reversible" % (operation, self)) <ide> new_state = project_state.clone() <ide> operation.state_forwards(self.app_label, new_state) <ide> to_run.append((operation, project_state, new_state)) <ide><path>django/db/migrations/operations/special.py <ide> def database_forwards(self, app_label, schema_editor, from_state, to_state): <ide> <ide> def database_backwards(self, app_label, schema_editor, from_state, to_state): <ide> raise NotImplementedError("You cannot reverse this operation") <add> <add> def describe(self): <add> return "Raw Python operation"
3
PHP
PHP
handle command
5b65863336fe08e3bbdf5a00336530d9d6304094
<ide><path>src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php <ide> public function __construct(Filesystem $files, Composer $composer) <ide> */ <ide> public function handle() <ide> { <del> parent::fire(); <add> parent::handle(); <ide> <ide> $this->composer->dumpAutoloads(); <ide> } <ide><path>src/Illuminate/Foundation/Console/ListenerMakeCommand.php <ide> public function handle() <ide> return $this->error('Missing required option: --event'); <ide> } <ide> <del> parent::fire(); <add> parent::handle(); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Foundation/Console/MailMakeCommand.php <ide> class MailMakeCommand extends GeneratorCommand <ide> */ <ide> public function handle() <ide> { <del> if (parent::fire() === false) { <add> if (parent::handle() === false) { <ide> return; <ide> } <ide> <ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php <ide> class ModelMakeCommand extends GeneratorCommand <ide> */ <ide> public function handle() <ide> { <del> if (parent::fire() === false) { <add> if (parent::handle() === false) { <ide> return; <ide> } <ide> <ide><path>src/Illuminate/Foundation/Console/NotificationMakeCommand.php <ide> class NotificationMakeCommand extends GeneratorCommand <ide> */ <ide> public function handle() <ide> { <del> if (parent::fire() === false) { <add> if (parent::handle() === false) { <ide> return; <ide> } <ide>
5
PHP
PHP
apply fixes from styleci
4288dbb7df86f95687d514a4d7b33b93c8200fc8
<ide><path>src/Illuminate/Console/Concerns/InteractsWithIO.php <ide> use Symfony\Component\Console\Formatter\OutputFormatterStyle; <ide> use Symfony\Component\Console\Helper\Table; <ide> use Symfony\Component\Console\Input\InputInterface; <del>use Symfony\Component\Console\Output\ConsoleOutput; <ide> use Symfony\Component\Console\Output\OutputInterface; <ide> use Symfony\Component\Console\Question\ChoiceQuestion; <ide> use Symfony\Component\Console\Question\Question;
1
Javascript
Javascript
compile all next module files
59280f7747b807fa9d1f5810e1d762d4f147124c
<ide><path>packages/next/build/webpack-config.js <ide> function externalsConfig (isServer, target) { <ide> } <ide> <ide> // Default pages have to be transpiled <del> if (res.match(/next[/\\]dist[/\\]pages/) || res.match(/next[/\\]dist[/\\]client/) || res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) || res.match(/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/)) { <add> if (res.match(/next[/\\]dist[/\\]/) || res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) || res.match(/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/)) { <ide> return callback() <ide> } <ide>
1
Text
Text
add version info for types
dd6481a183d38c7b48864c558ca5383164825b01
<ide><path>doc/api/n-api.md <ide> consumed by the various APIs. These APIs should be treated as opaque, <ide> introspectable only with other N-API calls. <ide> <ide> ### napi_status <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Integral status code indicating the success or failure of a N-API call. <ide> Currently, the following status codes are supported. <ide> ```C <ide> If additional information is required upon an API returning a failed status, <ide> it can be obtained by calling `napi_get_last_error_info`. <ide> <ide> ### napi_extended_error_info <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> ```C <ide> typedef struct { <ide> const char* error_message; <ide> not allowed. <ide> This is an opaque pointer that is used to represent a JavaScript value. <ide> <ide> ### napi_threadsafe_function <add><!-- YAML <add>added: v10.6.0 <add>napiVersion: 4 <add>--> <ide> <ide> This is an opaque pointer that represents a JavaScript function which can be <ide> called asynchronously from multiple threads via <ide> `napi_call_threadsafe_function()`. <ide> <ide> ### napi_threadsafe_function_release_mode <add><!-- YAML <add>added: v10.6.0 <add>napiVersion: 4 <add>--> <ide> <ide> A value to be given to `napi_release_threadsafe_function()` to indicate whether <ide> the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or <ide> typedef enum { <ide> ``` <ide> <ide> ### napi_threadsafe_function_call_mode <add><!-- YAML <add>added: v10.6.0 <add>napiVersion: 4 <add>--> <ide> <ide> A value to be given to `napi_call_threadsafe_function()` to indicate whether <ide> the call should block whenever the queue associated with the thread-safe <ide> longer referenced from the current stack frame. <ide> For more details, review the [Object Lifetime Management][]. <ide> <ide> #### napi_escapable_handle_scope <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Escapable handle scopes are a special type of handle scope to return values <ide> created within a particular handle scope to a parent scope. <ide> <ide> #### napi_ref <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> This is the abstraction to use to reference a `napi_value`. This allows for <ide> users to manage the lifetimes of JavaScript values, including defining their <ide> minimum lifetimes explicitly. <ide> For more details, review the [Object Lifetime Management][]. <ide> <ide> ### N-API Callback types <ide> #### napi_callback_info <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Opaque datatype that is passed to a callback function. It can be used for <ide> getting additional information about the context in which the callback was <ide> invoked. <ide> <ide> #### napi_callback <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Function pointer type for user-provided native functions which are to be <ide> exposed to JavaScript via N-API. Callback functions should satisfy the <ide> following signature: <ide> typedef napi_value (*napi_callback)(napi_env, napi_callback_info); <ide> ``` <ide> <ide> #### napi_finalize <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Function pointer type for add-on provided functions that allow the user to be <ide> notified when externally-owned data is ready to be cleaned up because the <ide> object with which it was associated with, has been garbage-collected. The user <ide> typedef void (*napi_finalize)(napi_env env, <ide> ``` <ide> <ide> #### napi_async_execute_callback <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Function pointer used with functions that support asynchronous <ide> operations. Callback functions must satisfy the following signature: <ide> <ide> JavaScript objects. Most often, any code that needs to make N-API <ide> calls should be made in `napi_async_complete_callback` instead. <ide> <ide> #### napi_async_complete_callback <add><!-- YAML <add>added: v8.0.0 <add>napiVersion: 1 <add>--> <ide> Function pointer used with functions that support asynchronous <ide> operations. Callback functions must satisfy the following signature: <ide> <ide> typedef void (*napi_async_complete_callback)(napi_env env, <ide> ``` <ide> <ide> #### napi_threadsafe_function_call_js <add><!-- YAML <add>added: v10.6.0 <add>napiVersion: 4 <add>--> <ide> <ide> Function pointer used with asynchronous thread-safe function calls. The callback <ide> will be called on the main thread. Its purpose is to use a data item arriving <ide> In order to retrieve this information [`napi_get_last_error_info`][] <ide> is provided which returns a `napi_extended_error_info` structure. <ide> The format of the `napi_extended_error_info` structure is as follows: <ide> <add><!-- YAML <add>added: v10.6.0 <add>napiVersion: 4 <add>--> <ide> ```C <ide> typedef struct napi_extended_error_info { <ide> const char* error_message;
1
PHP
PHP
remove runtime errors for router deprecations
62683ba557918c86fc2b69197661adb66f89170c
<ide><path>src/Routing/Router.php <ide> public static function connect($route, $defaults = [], $options = []) <ide> */ <ide> public static function redirect($route, $url, $options = []) <ide> { <del> trigger_error( <del> 'Router::redirect() is deprecated. Use Router::scope() and $routes->redirect() instead.', <del> E_USER_DEPRECATED <del> ); <ide> $options['routeClass'] = 'Cake\Routing\Route\RedirectRoute'; <ide> if (is_string($url)) { <ide> $url = ['redirect' => $url]; <ide> public static function redirect($route, $url, $options = []) <ide> */ <ide> public static function mapResources($controller, $options = []) <ide> { <del> trigger_error( <del> 'Router::mapResources() is deprecated. Use Router::scope() and $routes->resources() instead.', <del> E_USER_DEPRECATED <del> ); <ide> foreach ((array)$controller as $name) { <ide> list($plugin, $name) = pluginSplit($name); <ide> <ide> public static function extensions($extensions = null, $merge = true) <ide> */ <ide> public static function parseNamedParams(Request $request, array $options = []) <ide> { <del> trigger_error( <del> 'Router::parseNamedParams() is deprecated and will be removed in 4.0.', <del> E_USER_DEPRECATED <del> ); <ide> $options += ['separator' => ':']; <ide> if (empty($request->params['pass'])) { <ide> $request->params['named'] = []; <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testRouteDefaultParams() <ide> */ <ide> public function testMapResources() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::mapResources('Posts'); <ide> <ide> $expected = [ <ide> public function testMapResources() <ide> ]; <ide> $result = Router::parse('/posts/name', 'PUT'); <ide> $this->assertEquals($expected, $result); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testMapResources() <ide> */ <ide> public function testPluginMapResources() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::mapResources('TestPlugin.TestPlugin'); <ide> <ide> $result = Router::parse('/test_plugin/test_plugin', 'GET'); <ide> public function testPluginMapResources() <ide> '_method' => 'GET', <ide> ]; <ide> $this->assertEquals($expected, $result); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testPluginMapResources() <ide> */ <ide> public function testMapResourcesWithPrefix() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::mapResources('Posts', ['prefix' => 'api']); <ide> <ide> $result = Router::parse('/api/posts', 'GET'); <ide> public function testMapResourcesWithPrefix() <ide> '_method' => 'GET', <ide> ]; <ide> $this->assertEquals($expected, $result); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testMapResourcesWithPrefix() <ide> */ <ide> public function testMapResourcesWithExtension() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::extensions(['json', 'xml'], false); <ide> Router::mapResources('Posts', ['_ext' => 'json']); <ide> <ide> public function testMapResourcesWithExtension() <ide> <ide> $result = Router::parse('/posts.xml', 'GET'); <ide> $this->assertArrayNotHasKey('_method', $result, 'Not an extension/resource route.'); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> * testMapResources with custom connectOptions <ide> */ <ide> public function testMapResourcesConnectOptions() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Plugin::load('TestPlugin'); <ide> Router::mapResources('Posts', [ <ide> 'connectOptions' => [ <ide> public function testMapResourcesConnectOptions() <ide> $route = $routes[0]; <ide> $this->assertInstanceOf('TestPlugin\Routing\Route\TestRoute', $route); <ide> $this->assertEquals('^(bar)$', $route->options['foo']); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testMapResourcesConnectOptions() <ide> */ <ide> public function testPluginMapResourcesWithPrefix() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::mapResources('TestPlugin.TestPlugin', ['prefix' => 'api']); <ide> <ide> $result = Router::parse('/api/test_plugin/test_plugin', 'GET'); <ide> public function testPluginMapResourcesWithPrefix() <ide> 'prefix' => 'api', <ide> ]; <ide> $this->assertEquals($expected, $result); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testMultipleResourceRoute() <ide> */ <ide> public function testGenerateUrlResourceRoute() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::mapResources('Posts'); <ide> <ide> $result = Router::url([ <ide> public function testGenerateUrlResourceRoute() <ide> $result = Router::url(['controller' => 'Posts', 'action' => 'edit', '_method' => 'PATCH', 'id' => 10]); <ide> $expected = '/posts/10'; <ide> $this->assertEquals($expected, $result); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testPatternOnAction() <ide> */ <ide> public function testRedirect() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <ide> Router::redirect('/mobile', '/', ['status' => 301]); <ide> $routes = Router::routes(); <ide> $route = $routes[0]; <ide> $this->assertInstanceOf('Cake\Routing\Route\RedirectRoute', $route); <del> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testRedirect() <ide> */ <ide> public function testParseNamedParameters() <ide> { <del> $restore = error_reporting(E_ALL ^ E_USER_DEPRECATED); <del> <ide> $request = new Request(); <ide> $request->addParams([ <ide> 'controller' => 'posts', <ide> public function testParseNamedParameters() <ide> ] <ide> ]; <ide> $this->assertEquals($expected, $request->params); <del> error_reporting($restore); <ide> } <ide> <ide> /**
2
Python
Python
fix assertion error
ee69348e566e20c6ff2931059ddaa8b9e57a2b9f
<ide><path>celery/tests/worker/test_autoscale.py <ide> def test_no_negative_scale(self): <ide> x.body() <ide> total_num_processes.append(self.pool.num_processes) <ide> <del> self. assertTrue(all(i <= x.min_concurrency for i in total_num_processes) <del> ) <del> self. assertTrue(all(i <= x.max_concurrency for i in total_num_processes) <del> ) <ide>\ No newline at end of file <add> self. assertTrue( <add> all(x.min_concurrency <= i <= x.max_concurrency for i in total_num_processes) <add> )
1
Go
Go
fix hack in old integration test for new init
9694209241074c10d4cc625b24dfedcb2387de93
<ide><path>integration/runtime_test.go <ide> import ( <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/nat" <add> "github.com/docker/docker/reexec" <ide> "github.com/docker/docker/runconfig" <del> "github.com/docker/docker/sysinit" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <ide> func init() { <ide> os.Setenv("DOCKER_TMPDIR", unitTestDockerTmpdir) <ide> <ide> // Hack to run sys init during unit testing <del> if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") { <del> sysinit.SysInit() <add> if reexec.Init() { <ide> return <ide> } <ide>
1
Python
Python
simplify test for string-likes
0ab1a2b12baabe3bd7063e2963c83482a4f57016
<ide><path>numpy/core/numeric.py <ide> def count_nonzero(a, axis=None): <ide> if issubdtype(a.dtype, np.number): <ide> return (a != 0).sum(axis=axis, dtype=np.intp) <ide> <del> if (issubdtype(a.dtype, np.string_) or <del> issubdtype(a.dtype, np.unicode_)): <add> if issubdtype(a.dtype, np.character): <ide> nullstr = a.dtype.type('') <ide> return (a != nullstr).sum(axis=axis, dtype=np.intp) <ide>
1
Ruby
Ruby
cask dsl caveats
7603d05d053db11c7a7606d5fc414cee3b23df13
<ide><path>Library/Homebrew/cask/lib/hbc/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> <ide> brew cask install java <ide> EOS <del> elsif java_version.include?("9") || java_version.include?("+") <add> elsif java_version.include?("10") || java_version.include?("+") <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install the latest version with <ide>
1
Python
Python
allow relative imports in dynamic code
0b072304099e14f86dc62b59ca84f7eb5676af4e
<ide><path>src/transformers/models/auto/dynamic.py <ide> from pathlib import Path <ide> from typing import Dict, Optional, Union <ide> <add>from huggingface_hub import HfFolder, model_info <add> <ide> from ...file_utils import ( <ide> HF_MODULES_CACHE, <ide> TRANSFORMERS_DYNAMIC_MODULE_NAME, <ide> def check_imports(filename): <ide> # Only keep the top-level module <ide> imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")] <ide> <add> # Imports of the form `import .xxx` <add> relative_imports = re.findall("^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE) <add> # Imports of the form `from .xxx import yyy` <add> relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE) <add> relative_imports = list(set(relative_imports)) <add> <ide> # Unique-ify and test we got them all <ide> imports = list(set(imports)) <ide> missing_packages = [] <ide> def check_imports(filename): <ide> f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`" <ide> ) <ide> <add> return relative_imports <add> <ide> <ide> def get_class_in_module(class_name, module_path): <ide> """ <ide> def get_class_in_module(class_name, module_path): <ide> return getattr(module, class_name) <ide> <ide> <del>def get_class_from_dynamic_module( <add>def get_cached_module_file( <ide> pretrained_model_name_or_path: Union[str, os.PathLike], <ide> module_file: str, <del> class_name: str, <ide> cache_dir: Optional[Union[str, os.PathLike]] = None, <ide> force_download: bool = False, <ide> resume_download: bool = False, <ide> proxies: Optional[Dict[str, str]] = None, <ide> use_auth_token: Optional[Union[bool, str]] = None, <ide> revision: Optional[str] = None, <ide> local_files_only: bool = False, <del> **kwargs, <ide> ): <ide> """ <del> Extracts a class from a module file, present in the local folder or repository of a model. <del> <del> <Tip warning={true}> <del> <del> Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should <del> therefore only be called on trusted repos. <del> <del> </Tip> <add> Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached <add> Transformers module. <ide> <ide> Args: <ide> pretrained_model_name_or_path (`str` or `os.PathLike`): <ide> def get_class_from_dynamic_module( <ide> <ide> module_file (`str`): <ide> The name of the module file containing the class to look for. <del> class_name (`str`): <del> The name of the class to import in the module. <ide> cache_dir (`str` or `os.PathLike`, *optional*): <ide> Path to a directory in which a downloaded pretrained model configuration should be cached if the standard <ide> cache should not be used. <ide> def get_class_from_dynamic_module( <ide> </Tip> <ide> <ide> Returns: <del> `type`: The class, dynamically imported from the module. <del> <del> Examples: <del> <del> ```python <del> # Download module *modeling.py* from huggingface.co and cache then extract the class *MyBertModel* from this <del> # module. <del> cls = get_class_from_dynamic_module("sgugger/my-bert-model", "modeling.py", "MyBertModel") <del> ```""" <add> `str`: The path to the module inside the cache.""" <ide> if is_offline_mode() and not local_files_only: <ide> logger.info("Offline mode: forcing local_files_only=True") <ide> local_files_only = True <ide> def get_class_from_dynamic_module( <ide> raise <ide> <ide> # Check we have all the requirements in our environment <del> check_imports(resolved_module_file) <add> modules_needed = check_imports(resolved_module_file) <ide> <ide> # Now we move the module inside our cached dynamic modules. <ide> full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule <ide> def get_class_from_dynamic_module( <ide> # We always copy local files (we could hash the file to see if there was a change, and give them the name of <ide> # that hash, to only copy when there is a modification but it seems overkill for now). <ide> # The only reason we do the copy is to avoid putting too many folders in sys.path. <del> module_name = module_file <ide> shutil.copy(resolved_module_file, submodule_path / module_file) <add> for module_needed in modules_needed: <add> module_needed = f"{module_needed}.py" <add> shutil.copy(os.path.join(pretrained_model_name_or_path, module_needed), submodule_path / module_needed) <ide> else: <del> # The module file will end up being named module_file + the etag. This way we get the benefit of versioning. <del> resolved_module_file_name = Path(resolved_module_file).name <del> module_name_parts = [module_file.replace(".py", "")] + resolved_module_file_name.split(".") <del> module_name = "_".join(module_name_parts) + ".py" <del> if not (submodule_path / module_name).exists(): <del> shutil.copy(resolved_module_file, submodule_path / module_name) <add> # Get the commit hash <add> # TODO: we will get this info in the etag soon, so retrieve it from there. <add> if isinstance(use_auth_token, str): <add> token = use_auth_token <add> elif use_auth_token is True: <add> token = HfFolder.get_token() <add> else: <add> token = None <add> <add> commit_hash = model_info(pretrained_model_name_or_path, revision=revision, token=token).sha <add> <add> # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the <add> # benefit of versioning. <add> submodule_path = submodule_path / commit_hash <add> full_submodule = full_submodule + os.path.sep + commit_hash <add> create_dynamic_module(full_submodule) <add> <add> if not (submodule_path / module_file).exists(): <add> shutil.copy(resolved_module_file, submodule_path / module_file) <add> # Make sure we also have every file with relative <add> for module_needed in modules_needed: <add> if not (submodule_path / module_needed).exists(): <add> get_cached_module_file( <add> pretrained_model_name_or_path, <add> f"{module_needed}.py", <add> cache_dir=cache_dir, <add> force_download=force_download, <add> resume_download=resume_download, <add> proxies=proxies, <add> use_auth_token=use_auth_token, <add> revision=revision, <add> local_files_only=local_files_only, <add> ) <add> return os.path.join(full_submodule, module_file) <add> <add> <add>def get_class_from_dynamic_module( <add> pretrained_model_name_or_path: Union[str, os.PathLike], <add> module_file: str, <add> class_name: str, <add> cache_dir: Optional[Union[str, os.PathLike]] = None, <add> force_download: bool = False, <add> resume_download: bool = False, <add> proxies: Optional[Dict[str, str]] = None, <add> use_auth_token: Optional[Union[bool, str]] = None, <add> revision: Optional[str] = None, <add> local_files_only: bool = False, <add> **kwargs, <add>): <add> """ <add> Extracts a class from a module file, present in the local folder or repository of a model. <add> <add> <Tip warning={true}> <add> <add> Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should <add> therefore only be called on trusted repos. <add> <add> </Tip> <add> <add> Args: <add> pretrained_model_name_or_path (`str` or `os.PathLike`): <add> This can be either: <add> <add> - a string, the *model id* of a pretrained model configuration hosted inside a model repo on <add> huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced <add> under a user or organization name, like `dbmdz/bert-base-german-cased`. <add> - a path to a *directory* containing a configuration file saved using the <add> [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. <add> <add> module_file (`str`): <add> The name of the module file containing the class to look for. <add> class_name (`str`): <add> The name of the class to import in the module. <add> cache_dir (`str` or `os.PathLike`, *optional*): <add> Path to a directory in which a downloaded pretrained model configuration should be cached if the standard <add> cache should not be used. <add> force_download (`bool`, *optional*, defaults to `False`): <add> Whether or not to force to (re-)download the configuration files and override the cached versions if they <add> exist. <add> resume_download (`bool`, *optional*, defaults to `False`): <add> Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists. <add> proxies (`Dict[str, str]`, *optional*): <add> A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', <add> 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. <add> use_auth_token (`str` or *bool*, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated <add> when running `transformers-cli login` (stored in `~/.huggingface`). <add> revision(`str`, *optional*, defaults to `"main"`): <add> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <add> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <add> identifier allowed by git. <add> local_files_only (`bool`, *optional*, defaults to `False`): <add> If `True`, will only try to load the tokenizer configuration from local files. <add> <add> <Tip> <add> <add> Passing `use_auth_token=True` is required when you want to use a private model. <ide> <add> </Tip> <add> <add> Returns: <add> `type`: The class, dynamically imported from the module. <add> <add> Examples: <add> <add> ```python <add> # Download module *modeling.py* from huggingface.co and cache then extract the class *MyBertModel* from this <add> # module. <add> cls = get_class_from_dynamic_module("sgugger/my-bert-model", "modeling.py", "MyBertModel") <add> ```""" <ide> # And lastly we get the class inside our newly created module <del> final_module = os.path.join(full_submodule, module_name.replace(".py", "")) <del> return get_class_in_module(class_name, final_module) <add> final_module = get_cached_module_file( <add> pretrained_model_name_or_path, <add> module_file, <add> cache_dir=cache_dir, <add> force_download=force_download, <add> resume_download=resume_download, <add> proxies=proxies, <add> use_auth_token=use_auth_token, <add> revision=revision, <add> local_files_only=local_files_only, <add> ) <add> return get_class_in_module(class_name, final_module.replace(".py", "")) <ide><path>tests/test_configuration_auto.py <ide> def test_configuration_not_found(self): <ide> "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.", <ide> ): <ide> _ = AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo") <add> <add> def test_from_pretrained_dynamic_config(self): <add> config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True) <add> self.assertEqual(config.__class__.__name__, "NewModelConfig") <ide><path>tests/test_modeling_auto.py <ide> def test_parents_and_children_in_mappings(self): <ide> for child, parent in [(a, b) for a in child_model for b in parent_model]: <ide> assert not issubclass(child, parent), f"{child.__name__} is child of {parent.__name__}" <ide> <del> def test_from_pretrained_dynamic_model(self): <add> def test_from_pretrained_dynamic_model_local(self): <ide> config = BertConfig( <ide> vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 <ide> ) <ide> def test_from_pretrained_dynamic_model(self): <ide> for p1, p2 in zip(model.parameters(), new_model.parameters()): <ide> self.assertTrue(torch.equal(p1, p2)) <ide> <add> def test_from_pretrained_dynamic_model_distant(self): <add> model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True) <add> self.assertEqual(model.__class__.__name__, "NewModel") <add> <add> # This one uses a relative import to a util file, this checks it is downloaded and used properly. <add> model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model_with_util", trust_remote_code=True) <add> self.assertEqual(model.__class__.__name__, "NewModel") <add> <ide> def test_new_model_registration(self): <ide> AutoConfig.register("new-model", NewModelConfig) <ide>
3
Javascript
Javascript
fix error routes (#595)
897c60b4fd7e7f2204a8ba176754a868ea58d064
<ide><path>lib/router/router.js <ide> export default class Router extends EventEmitter { <ide> error <ide> } = await this.getRouteInfo(route, pathname, query) <ide> <del> if (error) { <add> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, as) <del> // We don't need to throw here since the error is already logged by <del> // this.getRouteInfo <ide> return <ide> } <ide> <ide> this.route = route <ide> this.set(pathname, query, { ...data, props }) <del> this.emit('routeChangeComplete', as) <add> <add> if (error) { <add> this.emit('routeChangeError', error, as) <add> } else { <add> this.emit('routeChangeComplete', as) <add> } <ide> } <ide> <ide> update (route, Component) { <ide> export default class Router extends EventEmitter { <ide> error <ide> } = await this.getRouteInfo(route, pathname, query) <ide> <del> if (error) { <add> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, url) <del> throw error <add> return <ide> } <ide> <ide> this.notify({ ...data, props }) <ide> <add> if (error) { <add> this.emit('routeChangeError', error, url) <add> throw error <add> } <add> <ide> this.emit('routeChangeComplete', url) <ide> } <ide> <ide> export default class Router extends EventEmitter { <ide> data, props, error <ide> } = await this.getRouteInfo(route, pathname, query) <ide> <del> if (error) { <add> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, as) <del> throw error <add> return false <ide> } <ide> <ide> changeState() <ide> <ide> this.route = route <ide> this.set(pathname, query, { ...data, props }) <ide> <add> if (error) { <add> this.emit('routeChangeError', error, as) <add> throw error <add> } <add> <ide> this.emit('routeChangeComplete', as) <ide> return true <ide> <ide><path>server/index.js <ide> export default class Server { <ide> return renderErrorJSON(err, req, res, this.renderOpts) <ide> } <ide> <add> async serveStaticWithGzip (req, res, path) { <add> this._serveStatic(req, res, () => { <add> return serveStaticWithGzip(req, res, path) <add> }) <add> } <add> <add> serveStatic (req, res, path) { <add> this._serveStatic(req, res, () => { <add> return serveStatic(req, res, path) <add> }) <add> } <add> <add> async _serveStatic (req, res, fn) { <add> try { <add> await fn() <add> } catch (err) { <add> if (err.code === 'ENOENT') { <add> this.render404(req, res) <add> } else { <add> throw err <add> } <add> } <add> } <add> <ide> getCompilationError (page) { <ide> if (!this.hotReloader) return <ide> <ide><path>server/render.js <ide> export async function serveStaticWithGzip (req, res, path) { <ide> export function serveStatic (req, res, path) { <ide> return new Promise((resolve, reject) => { <ide> send(req, path) <del> .on('error', (err) => { <del> if (err.code === 'ENOENT') { <del> res.statusCode = 404 <del> res.end('Not Found') <del> resolve() <del> } else { <del> reject(err) <del> } <del> }) <add> .on('error', reject) <ide> .pipe(res) <ide> .on('finish', resolve) <ide> })
3
Python
Python
add support for partial serializer updates
c3644234cda5c457d72baf1fbf145f12f49a1fa4
<ide><path>rest_framework/fields.py <ide> def __init__(self, source=None, read_only=False, required=None, <ide> self.widget = widget <ide> <ide> def validate(self, value): <del> if value in validators.EMPTY_VALUES and self.required: <add> if value in validators.EMPTY_VALUES and self.required and not self.root.partial: <ide> raise ValidationError(self.error_messages['required']) <ide> <ide> def run_validators(self, value): <ide> def field_from_native(self, data, files, field_name, into): <ide> if self.default is not None: <ide> native = self.default <ide> else: <del> if self.required: <add> if self.required and not self.root.partial: <ide> raise ValidationError(self.error_messages['required']) <ide> return <ide> <ide><path>rest_framework/serializers.py <ide> class Meta(object): <ide> _options_class = SerializerOptions <ide> _dict_class = SortedDictWithMetadata # Set to unsorted dict for backwards compatibility with unsorted implementations. <ide> <del> def __init__(self, instance=None, data=None, files=None, context=None, **kwargs): <add> def __init__(self, instance=None, data=None, files=None, context=None, partial=False, **kwargs): <ide> super(BaseSerializer, self).__init__(**kwargs) <ide> self.opts = self._options_class(self.Meta) <ide> self.fields = copy.deepcopy(self.base_fields) <ide> self.parent = None <ide> self.root = None <add> self.partial = partial <ide> <ide> self.context = context or {} <ide> <ide><path>rest_framework/tests/serializer.py <ide> def test_update(self): <ide> self.assertTrue(serializer.object is expected) <ide> self.assertEquals(serializer.data['sub_comment'], 'And Merry Christmas!') <ide> <add> def test_partial_update(self): <add> msg = 'Merry New Year!' <add> partial_data = {'content': msg} <add> serializer = CommentSerializer(self.comment, data=partial_data) <add> self.assertEquals(serializer.is_valid(), False) <add> serializer = CommentSerializer(self.comment, data=partial_data, partial=True) <add> expected = self.comment <add> self.assertEqual(serializer.is_valid(), True) <add> self.assertEquals(serializer.object, expected) <add> self.assertTrue(serializer.object is expected) <add> self.assertEquals(serializer.data['content'], msg) <add> <ide> def test_model_fields_as_expected(self): <ide> """ <ide> Make sure that the fields returned are the same as defined
3
PHP
PHP
fix cs errors
9b181ecd72bcabc97980f5f45a6e08c54af769f3
<ide><path>src/View/Form/ArrayContext.php <ide> public function isCreate(): bool <ide> * context record. <ide> * - `schemaDefault`: Boolean indicating whether default value from <ide> * context's schema should be used if it's not explicitly provided. <del> * <ide> * @return mixed <ide> */ <ide> public function val(string $field, array $options = [])
1
Go
Go
remove unused variable
12117f349dbf544c4fa3422e389919ea291d1c53
<ide><path>libnetwork/endpoint.go <ide> func (ep *endpoint) buildHostsFiles() error { <ide> } <ide> } <ide> <del> name := container.config.hostName <del> if container.config.domainName != "" { <del> name = name + "." + container.config.domainName <del> } <del> <ide> for _, extraHost := range container.config.extraHosts { <ide> extraContent = append(extraContent, <ide> etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
1
PHP
PHP
fix incorrect fixture
70bd04385cb72ab2fec79255eab52a88d4b1b9fa
<ide><path>lib/Cake/Test/Fixture/PersonFixture.php <ide> class PersonFixture extends TestFixture { <ide> 'name' => ['type' => 'string', 'null' => false, 'length' => 32], <ide> 'mother_id' => ['type' => 'integer', 'null' => false], <ide> 'father_id' => ['type' => 'integer', 'null' => false], <del> '_indexes' => ['mother_id' => ['unique' => 0, 'columns' => ['mother_id', 'father_id']]], <del> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']], 'PRIMARY' => ['type' => 'unique', 'columns' => 'id']] <add> '_constraints' => [ <add> 'primary' => ['type' => 'primary', 'columns' => ['id']], <add> 'mother_idx' => ['type' => 'unique', 'columns' => ['mother_id', 'father_id']] <add> ] <ide> ); <ide> <ide> /**
1
Text
Text
add missing verb
877d00d9ba581b310dace838e985e4e3e150d439
<ide><path>docs/docs/02.1-jsx-in-depth.md <ide> var myDivElement = <div className="foo" />; <ide> React.render(myDivElement, document.body); <ide> ``` <ide> <del>To render a React Component, just a local variable that starts with an upper-case letter: <add>To render a React Component, just create a local variable that starts with an upper-case letter: <ide> <ide> ```javascript <ide> var MyComponent = React.createClass({/*...*/});
1