content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
remove duplicate "the"
bf82c8a7089f36d740336079a2ec7f7498b902c9
<ide><path>src/loader.js <ide> function setupModuleLoader(window) { <ide> * <ide> * @param {!string} name The name of the module to create or retrieve. <ide> * @param {Array.<string>=} requires If specified then new module is being created. If <del> * unspecified then the the module is being retrieved for further configuration. <add> * unspecified then the module is being retrieved for further configuration. <ide> * @param {Function} configFn Optional configuration function for the module. Same as <ide> * {@link angular.Module#config Module#config()}. <ide> * @returns {module} new module with the {@link angular.Module} api.
1
PHP
PHP
remove wrong return
1caf1cac4bbcd5870b9cee200abee0ecf8c43d42
<ide><path>lib/Cake/Core/Configure.php <ide> public static function load($key, $config = 'default', $merge = true) { <ide> } <ide> } <ide> <del> return self::write($values); <add> self::write($values); <ide> } <ide> <ide> /**
1
Python
Python
remove duplicate code on dbapi hook
f248a215aa341608e2bc7d9083ca9d18ab756ac4
<ide><path>airflow/hooks/dbapi.py <ide> def test_connection(self): <ide> """Tests the connection by executing a select 1 query""" <ide> status, message = False, '' <ide> try: <del> with closing(self.get_conn()) as conn: <del> with closing(conn.cursor()) as cur: <del> cur.execute("select 1") <del> if cur.fetchone(): <del> status = True <del> message = 'Connection successfully tested' <add> if self.get_first("select 1"): <add> status = True <add> message = 'Connection successfully tested' <ide> except Exception as e: <ide> status = False <ide> message = str(e)
1
Python
Python
add a test case for it
0f235de8573d1070401244c1270d8d25e99c573d
<ide><path>libcloud/test/storage/test_s3.py <ide> def upload_file(self, object_name=None, content_type=None, <ide> finally: <ide> self.driver_type._upload_object = old_func <ide> <add> def test_upload_object_invalid_hash_kms_encryption(self): <add> # Hash check should be skipped when AWS KMS server side encryption is <add> # used <add> def upload_file(self, object_name=None, content_type=None, <add> request_path=None, request_method=None, <add> headers=None, file_path=None, stream=None): <add> headers = {'etag': 'blahblah', 'x-amz-server-side-encryption': 'aws:kms'} <add> return {'response': make_response(200, headers=headers), <add> 'bytes_transferred': 1000, <add> 'data_hash': 'hash343hhash89h932439jsaa81'} <add> <add> old_func = self.driver_type._upload_object <add> self.driver_type._upload_object = upload_file <add> file_path = os.path.abspath(__file__) <add> container = Container(name='foo_bar_container', extra={}, <add> driver=self.driver) <add> object_name = 'foo_test_upload' <add> try: <add> self.driver.upload_object(file_path=file_path, container=container, <add> object_name=object_name, <add> verify_hash=True) <add> finally: <add> self.driver_type._upload_object = old_func <add> <add> <ide> def test_upload_object_success(self): <ide> def upload_file(self, object_name=None, content_type=None, <ide> request_path=None, request_method=None,
1
PHP
PHP
use new style route placeholders
c6b9a2eb1be5760c1800cc48ec478c059b1992ac
<ide><path>src/Routing/Route/Route.php <ide> class Route <ide> { <ide> /** <ide> * An array of named segments in a Route. <del> * `/:controller/:action/:id` has 3 key elements <add> * `/{controller}/{action}/{id}` has 3 key elements <ide> * <ide> * @var array <ide> */
1
Javascript
Javascript
update showcase for chillin
4b332ee53fc117ec48b7ae41717b11e27fb4aa15
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://play.google.com/store/apps/details?id=com.cbssports.fantasy.franchisefootball2015', <ide> author: 'CBS Sports', <ide> }, <add> { <add> name: 'Chillin\'', <add> icon: 'http://www.chillin.io/img/logo175x175.png', <add> linkAppStore: 'https://itunes.apple.com/us/app/chillin/id1059803303?ls=1&mt=8', <add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.chillinmobile', <add> author: 'Chillin LLC', <add> }, <ide> { <ide> name: 'Choke - Rap Battle With Friends', <ide> icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/3e/83/85/3e8385d8-140f-da38-a100-1393cef3e816/icon175x175.png',
1
Text
Text
add item to eslint hooks plugin changelog
e936034eecf3d882cb133a11a1b4afd98d0195c5
<ide><path>packages/eslint-plugin-react-hooks/CHANGELOG.md <add>## 4.0.1 <add>* Declare support for ESLint 7. ([@MichaelDeBoey](https://github.com/MichaelDeBoey) in [#18878](https://github.com/facebook/react/pull/18878)) <add> <ide> ## 4.0.0 <ide> <ide> * **New Violations:** Consider `PascalCase.useFoo()` calls as Hooks. ([@cyan33](https://github.com/cyan33) in [#18722](https://github.com/facebook/react/pull/18722))
1
PHP
PHP
allow registration of guesser callback'
150a63d491c89f73a8153c4548406e776e5f150a
<ide><path>src/Illuminate/Auth/Access/Gate.php <ide> class Gate implements GateContract <ide> */ <ide> protected $stringCallbacks = []; <ide> <add> /** <add> * The callback to be used to guess policy names. <add> * <add> * @var callable|null <add> */ <add> protected $guessPolicyNamesUsingCallback; <add> <ide> /** <ide> * Create a new gate instance. <ide> * <ide> public function getPolicyFor($class) <ide> */ <ide> protected function guessPolicyName($class) <ide> { <add> if ($this->guessPolicyNamesUsingCallback) { <add> return call_user_func($this->guessPolicyNamesUsingCallback, $class); <add> } <add> <ide> $classDirname = str_replace('/', '\\', dirname(str_replace('\\', '/', $class))); <ide> <ide> return $classDirname.'\\Policies\\'.class_basename($class).'Policy'; <ide> } <ide> <add> /** <add> * Specify a callback to be used to guess policy names. <add> * <add> * @param callable $callback <add> * @return $this <add> */ <add> public function guessPolicyNamesUsing(callable $callback) <add> { <add> $this->guessPolicyNamesUsingCallback = $callback; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Build a policy class instance of the given type. <ide> *
1
Text
Text
add deprecation note to blog post and changelog
085bf8635c40e78b4650e3dc4bffc8f96d3a77a7
<ide><path>CHANGELOG.md <ide> <ide> #### Breaking Changes <ide> <add>* Deprecated patterns that warned in 0.12 no longer work: most prominently, calling component classes without using JSX or React.createElement and using non-component functions with JSX or createElement <ide> * Mutating `props` after an element is created is deprecated and will cause warnings in development mode; future versions of React will incorporate performance optimizations assuming that props aren't mutated <ide> * Static methods (defined in `statics`) are no longer autobound to the component class <ide> * `ref` resolution order has changed slightly such that a ref to a component is available immediately after its `componentDidMount` method is called; this change should be observable only if your component calls a parent component's callback within your `componentDidMount`, which is an anti-pattern and should be avoided regardless <ide><path>docs/_posts/2015-03-10-react-v0.13.md <ide> We've also published version `0.13.0` of the `react` and `react-tools` packages <ide> <ide> #### Breaking Changes <ide> <add>* Deprecated patterns that warned in 0.12 no longer work: most prominently, calling component classes without using JSX or React.createElement and using non-component functions with JSX or createElement <ide> * Mutating `props` after an element is created is deprecated and will cause warnings in development mode; future versions of React will incorporate performance optimizations assuming that props aren't mutated <ide> * Static methods (defined in `statics`) are no longer autobound to the component class <ide> * `ref` resolution order has changed slightly such that a ref to a component is available immediately after its `componentDidMount` method is called; this change should be observable only if your component calls a parent component's callback within your `componentDidMount`, which is an anti-pattern and should be avoided regardless
2
Javascript
Javascript
use relative paths in entry files
45381cffe54447d5eb781f49a61ffdc120056307
<ide><path>src/react-entry.js <del>export * from 'lib/react'; <add>export * from './lib/react'; <ide><path>src/react-native-entry.js <del>export * from 'lib/react-native'; <add>export * from './lib/react-native';
2
Text
Text
add a missing slash
34830a05c940ec2bbabe3358df50c2d48593ca74
<ide><path>readme.md <ide> export default () => ( <ide> // pages/index.js <ide> import Link from 'next/link' <ide> export default () => ( <del> <div>Click <Link href='/about'><img src="/static/image.png"></Link></div> <add> <div>Click <Link href='/about'><img src="/static/image.png" /></Link></div> <ide> ) <ide> ``` <ide>
1
Text
Text
add initial version of maintaining-http.md
ac3c33c1646bf46104c15ae035982c06364da9b8
<ide><path>doc/contributing/maintaining-http.md <add># Maintaining HTTP <add> <add>Support for HTTP is a key priority in terms of ensuring the continued success of <add>Node.js as captured in the project's <add>[technical priorities](https://github.com/nodejs/node/blob/HEAD/doc/contributing/technical-priorities.md). <add> <add>The current high level strategy is based on the discussion in the <add>[Next-10](https://github.com/nodejs/next-10) <add>[mini-summit](https://github.com/nodejs/next-10/blob/main/meetings/summit-jan-2022.md) <add>on modern HTTP which was held on Jan 27 2022. <add> <add>## High level strategy <add> <add>The key elements of our strategy for future HTTP APIs are: <add> <add>* APIs should be HTTP protocol independent (support HTTP1, HTTP2, etc.). <add>* APIs should be transport protocol independent (TCP, QUIC, etc.). <add>* APIs should provide good defaults that perform well. <add>* Client/server APIs should be consistent and allow easy integration. <add>* Common requirements like piping out from client API to server APIs should be <add> easy. <add>* For both the Client and Server there is a need for multiple APIs, with each <add> targeting a different level of abstraction. <add> <add>Unfortunately our existing HTTP APIs ( <add>[HTTP](https://nodejs.org/docs/latest/api/http.html), <add>[HTTPS](https://nodejs.org/docs/latest/api/https.html), and <add>[HTTP2](https://nodejs.org/docs/latest/api/http2.html)) <add>do not align with our high level strategy. While these APIs <add>are widely used and we do not plan to deprecate or remove them, <add>they are not the focus of active development or performance improvements. <add>Bug fixes however are still important for all of these APIs. <add> <add>With respect to the HTTP protocols themselves, our current assessment in <add>terms of priority within existing or new APIs is: <add> <add>* HTTP 2 is in “maintenance mode” for both protocol and APIs. <add>* HTTP 1 is a stable protocol, but innovation is still possible with the APIs. <add>* HTTP 3 is an important protocol and we need to add support for it. <add> <add>The current strategy is to build out 2 new client APIs and 2 new Server APIs <add>in line with the high level strategy above. <add> <add>While transport-level APIs are important (e.g. socket level), the HTTP APIs <add>should not be tied to a specific transport-level API. Therefore, <add>transport-level APIs are out of the scope of our HTTP strategy/maintenance <add>information. <add> <add>### Client APIs <add> <add>For client APIs we want a high-level API and a low-level API when <add>more control is required. The current plan is for the following APIs: <add> <add>* High-level API - <add> [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) <add> based API built on top of [undici](https://www.npmjs.com/package/undici). <add>* Low-level API - a subset of the APIs exposed by <add> [undici](https://www.npmjs.com/package/undici). The exact shape and <add> set of these APIs is still to be worked out. The current plan is to <add> pull undici into Node.js core without exposing its APIs in the Node.js <add> API so that it can initially be used to support the higher level <add> Fetch-based API. As this gets worked out we will discuss which <add> APIs to expose in the Node.js API surface. <add> <add>### Server APIs <add> <add>For the server APIs we do not yet have a clear path, other than wanting <add>to align them with the APIs built for the client. <add> <add>## Maintaining the HTTP APIs <add> <add>### HTTP, HTTPS <add> <add>The low-level implementation of the <add>[HTTP](https://nodejs.org/docs/latest/api/http.html) <add>and [HTTPS](https://nodejs.org/docs/latest/api/https.html) APIs <add>are maintained in the [llttp](https://github.com/nodejs/llhttp) <add>repository. Updates are pulled into Node.js under <add>[deps/llhttp](https://github.com/nodejs/node/tree/HEAD/deps/llhttp) <add> <add>The low-level implementation is made available in the Node.js API through <add>JavaScript code in the [lib](https://github.com/nodejs/node/tree/HEAD/lib) <add>directory and C++ code in the <add>[src](https://github.com/nodejs/node/tree/HEAD/src) directory. <add> <add>### HTTP2 <add> <add>The low-level implementation of <add>[HTTP2](https://nodejs.org/docs/latest/api/http2.html) <add>is based on [nghttp2](https://nghttp2.org/). Updates are pulled into Node.js <add>under [deps/nghttp2](https://github.com/nodejs/node/tree/HEAD/deps/nghttp2) <add>as needed. <add> <add>The low-level implementation is made available in the Node.js API through <add>JavaScript code in the [lib](https://github.com/nodejs/node/tree/HEAD/lib) <add>directory and C++ code in the <add>[src](https://github.com/nodejs/node/tree/HEAD/src) directory.
1
Java
Java
update javadoc in defaultresponseerrorhandler
4978eeff7fe399dff75a800679e50fee4afba130
<ide><path>spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java <ide> public void handleError(ClientHttpResponse response) throws IOException { <ide> } <ide> <ide> /** <del> * Return error message with details from the response body, possibly truncated: <add> * Return error message with details from the response body: <ide> * <pre> <del> * 404 Not Found: [{'id': 123, 'message': 'my very long... (500 bytes)] <add> * 404 Not Found: [{'id': 123, 'message': 'my message'}] <ide> * </pre> <ide> */ <ide> private String getErrorMessage(
1
PHP
PHP
modify mssql driver order
fe290321349916223a800bf2f300d818d94d537a
<ide><path>src/Illuminate/Database/Connectors/SqlServerConnector.php <ide> protected function getDsn(array $config) <ide> // First we will create the basic DSN setup as well as the port if it is in <ide> // in the configuration options. This will give us the basic DSN we will <ide> // need to establish the PDO connections and return them back for use. <del> if (in_array('dblib', $this->getAvailableDrivers())) { <del> return $this->getDblibDsn($config); <del> } elseif ($this->prefersOdbc($config)) { <add> if ($this->prefersOdbc($config)) { <ide> return $this->getOdbcDsn($config); <ide> } <ide> <del> return $this->getSqlSrvDsn($config); <add> if (in_array('sqlsrv', $this->getAvailableDrivers())) { <add> return $this->getSqlSrvDsn($config); <add> } else { <add> return $this->getDblibDsn($config); <add> } <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseConnectorTest.php <ide> public function testSqlServerConnectCallsCreateConnectionWithOptionalArguments() <ide> $this->assertSame($result, $connection); <ide> } <ide> <add> public function testSqlServerConnectCallsCreateConnectionWithPreferredODBC() <add> { <add> if (! in_array('odbc', PDO::getAvailableDrivers())) { <add> $this->markTestSkipped('PHP was compiled without PDO ODBC support.'); <add> } <add> <add> $config = ['odbc' => true, 'odbc_datasource_name' => 'server=localhost;database=test;']; <add> $dsn = $this->getDsn($config); <add> $connector = $this->getMockBuilder('Illuminate\Database\Connectors\SqlServerConnector')->setMethods(['createConnection', 'getOptions'])->getMock(); <add> $connection = m::mock('stdClass'); <add> $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(['options'])); <add> $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->will($this->returnValue($connection)); <add> $result = $connector->connect($config); <add> <add> $this->assertSame($result, $connection); <add> } <add> <ide> protected function getDsn(array $config) <ide> { <ide> extract($config, EXTR_SKIP); <ide> <del> if (in_array('dblib', PDO::getAvailableDrivers())) { <del> $port = isset($config['port']) ? ':'.$port : ''; <del> $appname = isset($config['appname']) ? ';appname='.$config['appname'] : ''; <del> $charset = isset($config['charset']) ? ';charset='.$config['charset'] : ''; <add> $availableDrivers = PDO::getAvailableDrivers(); <ide> <del> return "dblib:host={$host}{$port};dbname={$database}{$charset}{$appname}"; <del> } else { <add> if (in_array('odbc', $availableDrivers) && <add> ($config['odbc'] ?? null) === true) { <add> return isset($config['odbc_datasource_name']) <add> ? 'odbc:'.$config['odbc_datasource_name'] : ''; <add> } <add> <add> if (in_array('sqlsrv', $availableDrivers)) { <ide> $port = isset($config['port']) ? ','.$port : ''; <ide> $appname = isset($config['appname']) ? ';APP='.$config['appname'] : ''; <ide> $readonly = isset($config['readonly']) ? ';ApplicationIntent=ReadOnly' : ''; <ide> $pooling = (isset($config['pooling']) && $config['pooling'] == false) ? ';ConnectionPooling=0' : ''; <ide> <ide> return "sqlsrv:Server={$host}{$port};Database={$database}{$readonly}{$pooling}{$appname}"; <add> } else { <add> $port = isset($config['port']) ? ':'.$port : ''; <add> $appname = isset($config['appname']) ? ';appname='.$config['appname'] : ''; <add> $charset = isset($config['charset']) ? ';charset='.$config['charset'] : ''; <add> <add> return "dblib:host={$host}{$port};dbname={$database}{$charset}{$appname}"; <ide> } <ide> } <ide> }
2
Javascript
Javascript
update alert style
b7843c6047484412c21803cf4472857a411239b3
<ide><path>server/middlewares/email-not-verified-notice.js <ide> export default function emailNotVerifiedNotice() { <ide> const { user } = req; <ide> if (user && (!user.email || user.email === '' || !user.emailVerified)) { <ide> req.flash( <del> 'danger', <add> 'info', <ide> dedent` <ide> New privacy laws now require that we have an email address where we can reach <ide> you. Please verify your email address below and click the link we send you to
1
Javascript
Javascript
use array.find vs array.filter()[0]
529b0ffe94da05f93345c8edcde406ea899c7c95
<ide><path>lib/optimize/ChunkModuleIdRangePlugin.js <ide> class ChunkModuleIdRangePlugin { <ide> const options = this.options; <ide> compiler.plugin("compilation", (compilation) => { <ide> compilation.plugin("module-ids", (modules) => { <del> const chunk = this.chunks.filter((chunk) => { <del> return chunk.name === options.name; <del> })[0]; <add> const chunk = this.chunks.find((chunk) => chunk.name === options.name); <ide> if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found"); <ide> let currentId = options.start; <ide> let chunkModules;
1
Ruby
Ruby
prefer each instead of for in
ec1993c33f8b1493cc4f55102d9c4dee178306a2
<ide><path>activemodel/lib/active_model/observing.rb <ide> def add_observer(observer) <ide> <ide> # Notify list of observers of a change. <ide> def notify_observers(*arg) <del> for observer in observer_instances <del> observer.update(*arg) <del> end <add> observer_instances.each { |observer| observer.update(*arg) } <ide> end <ide> <ide> # Total number of observers.
1
Python
Python
move source, info, and who to numpy
db349674856abc7b2652546e937c85dbbbebbf9c
<ide><path>numpy/lib/utils.py <ide> import sys, os <add>import inspect <add>import types <add>import pydoc <ide> from numpy.core.numerictypes import obj2sctype <ide> from numpy.core.multiarray import dtype <add>from numpy.core import product, ndarray <ide> <ide> __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', <ide> 'issubdtype', 'deprecate', 'get_numarray_include', <del> 'get_include', 'ctypes_load_library'] <add> 'get_include', 'ctypes_load_library', 'info', <add> 'source', 'who'] <ide> <ide> def issubclass_(arg1, arg2): <ide> try: <ide> def newfunc(*args,**kwds): <ide> newfunc.__dict__.update(d) <ide> return newfunc <ide> <del> <ide> get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include') <ide> <ide> <add>#----------------------------------------------------------------------------- <add># Function for output and information on the variables used. <add>#----------------------------------------------------------------------------- <add> <add> <add>def who(vardict=None): <add> """Print the scipy arrays in the given dictionary (or globals() if None). <add> """ <add> if vardict is None: <add> frame = sys._getframe().f_back <add> vardict = frame.f_globals <add> sta = [] <add> cache = {} <add> for name in vardict.keys(): <add> if isinstance(vardict[name],ndarray): <add> var = vardict[name] <add> idv = id(var) <add> if idv in cache.keys(): <add> namestr = name + " (%s)" % cache[idv] <add> original=0 <add> else: <add> cache[idv] = name <add> namestr = name <add> original=1 <add> shapestr = " x ".join(map(str, var.shape)) <add> bytestr = str(var.itemsize*product(var.shape)) <add> sta.append([namestr, shapestr, bytestr, var.dtype.name, <add> original]) <add> <add> maxname = 0 <add> maxshape = 0 <add> maxbyte = 0 <add> totalbytes = 0 <add> for k in range(len(sta)): <add> val = sta[k] <add> if maxname < len(val[0]): <add> maxname = len(val[0]) <add> if maxshape < len(val[1]): <add> maxshape = len(val[1]) <add> if maxbyte < len(val[2]): <add> maxbyte = len(val[2]) <add> if val[4]: <add> totalbytes += int(val[2]) <add> <add> if len(sta) > 0: <add> sp1 = max(10,maxname) <add> sp2 = max(10,maxshape) <add> sp3 = max(10,maxbyte) <add> prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') <add> print prval + "\n" + "="*(len(prval)+5) + "\n" <add> <add> for k in range(len(sta)): <add> val = sta[k] <add> print "%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), <add> val[1], ' '*(sp2-len(val[1])+5), <add> val[2], ' '*(sp3-len(val[2])+5), <add> val[3]) <add> print "\nUpper bound on total bytes = %d" % totalbytes <add> return <add> <add>#----------------------------------------------------------------------------- <add> <add> <add># NOTE: pydoc defines a help function which works simliarly to this <add># except it uses a pager to take over the screen. <add> <add># combine name and arguments and split to multiple lines of <add># width characters. End lines on a comma and begin argument list <add># indented with the rest of the arguments. <add>def _split_line(name, arguments, width): <add> firstwidth = len(name) <add> k = firstwidth <add> newstr = name <add> sepstr = ", " <add> arglist = arguments.split(sepstr) <add> for argument in arglist: <add> if k == firstwidth: <add> addstr = "" <add> else: <add> addstr = sepstr <add> k = k + len(argument) + len(addstr) <add> if k > width: <add> k = firstwidth + 1 + len(argument) <add> newstr = newstr + ",\n" + " "*(firstwidth+2) + argument <add> else: <add> newstr = newstr + addstr + argument <add> return newstr <add> <add>_namedict = None <add>_dictlist = None <add> <add># Traverse all module directories underneath globals <add># to see if something is defined <add>def _makenamedict(module='numpy'): <add> module = __import__(module, globals(), locals(), []) <add> thedict = {module.__name__:module.__dict__} <add> dictlist = [module.__name__] <add> totraverse = [module.__dict__] <add> while 1: <add> if len(totraverse) == 0: <add> break <add> thisdict = totraverse.pop(0) <add> for x in thisdict.keys(): <add> if isinstance(thisdict[x],types.ModuleType): <add> modname = thisdict[x].__name__ <add> if modname not in dictlist: <add> moddict = thisdict[x].__dict__ <add> dictlist.append(modname) <add> totraverse.append(moddict) <add> thedict[modname] = moddict <add> return thedict, dictlist <add> <add> <add>def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): <add> """Get help information for a function, class, or module. <add> <add> Example: <add> >>> from numpy import * <add> >>> info(polyval) <add> polyval(p, x) <add> <add> Evaluate the polymnomial p at x. <add> <add> Description: <add> If p is of length N, this function returns the value: <add> p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] <add> """ <add> global _namedict, _dictlist <add> <add> if hasattr(object,'_ppimport_importer') or \ <add> hasattr(object, '_ppimport_module'): <add> object = object._ppimport_module <add> elif hasattr(object, '_ppimport_attr'): <add> object = object._ppimport_attr <add> <add> if object is None: <add> info(info) <add> elif isinstance(object, types.StringType): <add> if _namedict is None: <add> _namedict, _dictlist = _makenamedict(toplevel) <add> numfound = 0 <add> objlist = [] <add> for namestr in _dictlist: <add> try: <add> obj = _namedict[namestr][object] <add> if id(obj) in objlist: <add> print >> output, "\n *** Repeat reference found in %s *** " % namestr <add> else: <add> objlist.append(id(obj)) <add> print >> output, " *** Found in %s ***" % namestr <add> info(obj) <add> print >> output, "-"*maxwidth <add> numfound += 1 <add> except KeyError: <add> pass <add> if numfound == 0: <add> print >> output, "Help for %s not found." % object <add> else: <add> print >> output, "\n *** Total of %d references found. ***" % numfound <add> <add> elif inspect.isfunction(object): <add> name = object.func_name <add> arguments = apply(inspect.formatargspec, inspect.getargspec(object)) <add> <add> if len(name+arguments) > maxwidth: <add> argstr = _split_line(name, arguments, maxwidth) <add> else: <add> argstr = name + arguments <add> <add> print >> output, " " + argstr + "\n" <add> print >> output, inspect.getdoc(object) <add> <add> elif inspect.isclass(object): <add> name = object.__name__ <add> if hasattr(object, '__init__'): <add> arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) <add> arglist = arguments.split(', ') <add> if len(arglist) > 1: <add> arglist[1] = "("+arglist[1] <add> arguments = ", ".join(arglist[1:]) <add> else: <add> arguments = "()" <add> else: <add> arguments = "()" <add> <add> if len(name+arguments) > maxwidth: <add> argstr = _split_line(name, arguments, maxwidth) <add> else: <add> argstr = name + arguments <add> <add> print >> output, " " + argstr + "\n" <add> doc1 = inspect.getdoc(object) <add> if doc1 is None: <add> if hasattr(object,'__init__'): <add> print >> output, inspect.getdoc(object.__init__) <add> else: <add> print >> output, inspect.getdoc(object) <add> <add> methods = pydoc.allmethods(object) <add> if methods != []: <add> print >> output, "\n\nMethods:\n" <add> for meth in methods: <add> if meth[0] == '_': <add> continue <add> thisobj = getattr(object, meth, None) <add> if thisobj is not None: <add> methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None") <add> print >> output, " %s -- %s" % (meth, methstr) <add> <add> elif type(object) is types.InstanceType: ## check for __call__ method <add> print >> output, "Instance of class: ", object.__class__.__name__ <add> print >> output <add> if hasattr(object, '__call__'): <add> arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) <add> arglist = arguments.split(', ') <add> if len(arglist) > 1: <add> arglist[1] = "("+arglist[1] <add> arguments = ", ".join(arglist[1:]) <add> else: <add> arguments = "()" <add> <add> if hasattr(object,'name'): <add> name = "%s" % object.name <add> else: <add> name = "<name>" <add> if len(name+arguments) > maxwidth: <add> argstr = _split_line(name, arguments, maxwidth) <add> else: <add> argstr = name + arguments <add> <add> print >> output, " " + argstr + "\n" <add> doc = inspect.getdoc(object.__call__) <add> if doc is not None: <add> print >> output, inspect.getdoc(object.__call__) <add> print >> output, inspect.getdoc(object) <add> <add> else: <add> print >> output, inspect.getdoc(object) <add> <add> elif inspect.ismethod(object): <add> name = object.__name__ <add> arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) <add> arglist = arguments.split(', ') <add> if len(arglist) > 1: <add> arglist[1] = "("+arglist[1] <add> arguments = ", ".join(arglist[1:]) <add> else: <add> arguments = "()" <add> <add> if len(name+arguments) > maxwidth: <add> argstr = _split_line(name, arguments, maxwidth) <add> else: <add> argstr = name + arguments <add> <add> print >> output, " " + argstr + "\n" <add> print >> output, inspect.getdoc(object) <add> <add> elif hasattr(object, '__doc__'): <add> print >> output, inspect.getdoc(object) <add> <add> <add>def source(object, output=sys.stdout): <add> """Write source for this object to output. <add> """ <add> try: <add> print >> output, "In file: %s\n" % inspect.getsourcefile(object) <add> print >> output, inspect.getsource(object) <add> except: <add> print >> output, "Not available for this object." <add> <ide><path>numpy/numarray/alter_code1.py <ide> This module converts code written for Numeric to run with numpy <ide> <ide> Makes the following changes: <del> * Changes import statements (warns of use of from Numeric import *) <del> * Changes import statements (using numerix) ... <add> * Changes import statements <add> <add> Stubs for <add> convolve --> numarray.convolve <add> image --> numarray.image <add> nd_image --> numarray.nd_image <add> <ide> * Makes search and replace changes to: <del> - .typecode() <del> - .iscontiguous() <del> - .byteswapped() <del> - .itemsize() <del> - .toscalar() <del> * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] <del> * Replace xxx.spacesaver() with True <del> * Convert xx.savespace(?) to pass + ## xx.savespace(?) <del> <del> * Converts uses of 'b' to 'B' in the typecode-position of <del> functions: <del> eye, tri (in position 4) <del> ones, zeros, identity, empty, array, asarray, arange, <del> fromstring, indices, array_constructor (in position 2) <del> <del> and methods: <del> astype --- only argument <add> - .imaginary --> .imag <add> - .flat --> .ravel() (most of the time) <add> - .byteswapped() --> .byteswap(False) <add> - .byteswap() --> .byteswap(True) <add> - .info() --> numarray.info(self) <add> - .isaligned() --> .flags.aligned <add> - .isbyteswapped() --> (not .dtype.isnative) <add> - .typecode() --> .dtype.char <add> - .iscontiguous() --> .flags.contiguous <add> - .is_c_array() --> .flags.carray and .dtype.isnative <add> - .is_fortran_contiguous() --> .flags.fortran <add> - .is_f_array() --> .dtype.isnative and .flags.farray <add> - .itemsize() --> .itemsize <add> - .nelements() --> .size <add> - self.new(None) --> emtpy_like(self) <add> - self.new(type) --> empty(self.shape, type) <add> - .repeat(r) --> .repeat(r, axis=0) <add> - .size() --> .size <add> - .type() -- numarray.type(self.dtype) <add> - .typecode() --> .dtype.char <add> - .stddev() --> .std() <add> - .togglebyteorder() --> self.dtype=self.dtype.newbyteorder() <add> - .getshape() --> .shape <add> - .setshape(obj) --> .shape=obj <add> - .getflat() --> .ravel() <add> - .getreal() --> .real <add> - .setreal() --> .real = <add> - .getimag() --> .imag <add> - .setimag() --> .imag = <add> - .getimaginary() --> .imag <add> - .setimaginary() --> .imag <add> <ide> """ <ide> __all__ = ['fromfile', 'fromstr'] <ide> <ide><path>numpy/numarray/convolve.py <add>try: <add> from stsci.convolve import * <add>except ImportError: <add> try: <add> from scipy.stsci.convolve import * <add> except ImportError: <add> msg = \ <add>"""The convolve package is not installed. <add> <add>It can be downloaded by checking out the latest source from <add>http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and <add>installing all of SciPy from http://www.scipy.org. <add>""" <add> raise ImportError(msg) <ide><path>numpy/numarray/image.py <add>try: <add> from stsci.image import * <add>except ImportError: <add> try: <add> from scipy.stsci.image import * <add> except ImportError: <add> msg = \ <add>"""The image package is not installed <add> <add>It can be downloaded by checking out the latest source from <add>http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and <add>installing all of SciPy from http://www.scipy.org. <add>""" <add> raise ImportError(msg) <add> <ide><path>numpy/numarray/nd_image.py <add>try: <add> from ndimage import * <add>except ImportError: <add> try: <add> from scipy.ndimage import * <add> except ImportError: <add> msg = \ <add>"""The nd_image package is not installed <add> <add>It can be downloaded by checking out the latest source from <add>http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage or by downloading and <add>installing all of SciPy from http://www.scipy.org. <add>""" <add> raise ImportError(msg)
5
PHP
PHP
shorten behavior methods
0fa5a8428bbe232dea75f595019f52280c702aa1
<ide><path>src/ORM/Behavior.php <ide> public function implementedEvents() { <ide> * @return array <ide> */ <ide> public function implementedFinders() { <del> if (isset($this->_config['implementedFinders'])) { <del> return $this->_config['implementedFinders']; <add> $methods = $this->config('implementedFinders'); <add> if (isset($methods)) { <add> return $methods; <ide> } <ide> <del> $reflectionMethods = $this->_reflectionCache(); <del> return $reflectionMethods['finders']; <add> return $this->_reflectionCache()['finders']; <ide> } <ide> <ide> /** <ide> public function implementedFinders() { <ide> * @return array <ide> */ <ide> public function implementedMethods() { <del> if (isset($this->_config['implementedMethods'])) { <del> return $this->_config['implementedMethods']; <add> $methods = $this->config('implementedMethods'); <add> if (isset($methods)) { <add> return $methods; <ide> } <ide> <del> $reflectionMethods = $this->_reflectionCache(); <del> return $reflectionMethods['methods']; <add> return $this->_reflectionCache()['methods']; <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove cache.loglevel in test cases
6e2d4e0a1664e795359b7a437553e4cebb3761c2
<ide><path>test/TestCases.template.js <ide> const describeCases = config => { <ide> __filename: "mock" <ide> }, <ide> cache: config.cache && { <del> loglevel: "warning", <ide> cacheDirectory, <ide> ...config.cache <ide> },
1
Go
Go
fix error-type for starting a running container
c030885e7afef7ef14ba8709837a4a4e8e2127d8
<ide><path>libcontainerd/local/local_windows.go <ide> func (c *client) Start(_ context.Context, id, _ string, withStdin bool, attachSt <ide> case ctr == nil: <ide> return -1, errors.WithStack(errdefs.NotFound(errors.New("no such container"))) <ide> case ctr.init != nil: <del> return -1, errors.WithStack(errdefs.Conflict(errors.New("container already started"))) <add> return -1, errors.WithStack(errdefs.NotModified(errors.New("container already started"))) <ide> } <ide> <ide> logger := c.logger.WithField("container", id)
1
Text
Text
unify place of stability notes
d5882a95449b7970a9c928a3e6076e09c019212a
<ide><path>doc/api/assert.md <ide> changes: <ide> deprecated and emits a warning. <ide> --> <ide> <add>> Stability: 0 - Deprecated: Use `assert.fail([message])` or other assert <add>> functions instead. <add> <ide> * `actual` {any} <ide> * `expected` {any} <ide> * `message` {string|Error} <ide> * `operator` {string} **Default:** `'!='` <ide> * `stackStartFn` {Function} **Default:** `assert.fail` <ide> <del>> Stability: 0 - Deprecated: Use `assert.fail([message])` or other assert <del>> functions instead. <del> <ide> If `message` is falsy, the error message is set as the values of `actual` and <ide> `expected` separated by the provided `operator`. If just the two `actual` and <ide> `expected` arguments are provided, `operator` will default to `'!='`. If <ide><path>doc/api/events.md <ide> added: v0.9.12 <ide> deprecated: v4.0.0 <ide> --> <ide> <add>> Stability: 0 - Deprecated: Use [`emitter.listenerCount()`][] instead. <add> <ide> * `emitter` {EventEmitter} The emitter to query <ide> * `eventName` {string|symbol} The event name <ide> <del>> Stability: 0 - Deprecated: Use [`emitter.listenerCount()`][] instead. <del> <ide> A class method that returns the number of listeners for the given `eventName` <ide> registered on the given `emitter`. <ide> <ide><path>doc/api/http.md <ide> added: v0.3.0 <ide> deprecated: REPLACEME <ide> --> <ide> <del>* {net.Socket} <del> <ide> > Stability: 0 - Deprecated. Use [`response.socket`][]. <ide> <add>* {net.Socket} <add> <ide> See [`response.socket`][]. <ide> <ide> ### response.end([data[, encoding]][, callback]) <ide><path>doc/api/modules.md <ide> added: v10.12.0 <ide> deprecated: v12.2.0 <ide> --> <ide> <add>> Stability: 0 - Deprecated: Please use [`createRequire()`][] instead. <add> <ide> * `filename` {string} Filename to be used to construct the relative require <ide> function. <ide> * Returns: {require} Require function <ide> <del>> Stability: 0 - Deprecated: Please use [`createRequire()`][] instead. <del> <ide> ```js <ide> const { createRequireFromPath } = require('module'); <ide> const requireUtil = createRequireFromPath('../src/utils/'); <ide><path>doc/api/repl.md <ide> added: v0.8.9 <ide> deprecated: v9.0.0 <ide> --> <ide> <add>> Stability: 0 - Deprecated. <add> <ide> * `keyword` {string} the potential keyword to parse and execute <ide> * `rest` {any} any parameters to the keyword command <ide> * Returns: {boolean} <ide> <del>> Stability: 0 - Deprecated. <del> <ide> An internal method used to parse and execute `REPLServer` keywords. <ide> Returns `true` if `keyword` is a valid keyword, otherwise `false`. <ide> <ide><path>doc/api/util.md <ide> added: v0.7.5 <ide> deprecated: v6.0.0 <ide> --> <ide> <add>> Stability: 0 - Deprecated: Use [`Object.assign()`] instead. <add> <ide> * `target` {Object} <ide> * `source` {Object} <ide> <del>> Stability: 0 - Deprecated: Use [`Object.assign()`] instead. <del> <ide> The `util._extend()` method was never intended to be used outside of internal <ide> Node.js modules. The community found and used it anyway. <ide>
6
Javascript
Javascript
use common.fixtures module
b5e8ae4ff8f869ac0b38b44049d992fdbfb21331
<ide><path>test/parallel/test-fs-buffer.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> assert.throws(() => { <ide> fs.accessSync(true); <ide> }, /path must be a string or Buffer/); <ide> <del>const dir = Buffer.from(common.fixturesDir); <add>const dir = Buffer.from(fixtures.fixturesDir); <ide> fs.readdir(dir, 'hex', common.mustCall((err, hexList) => { <ide> assert.ifError(err); <ide> fs.readdir(dir, common.mustCall((err, stringList) => {
1
Javascript
Javascript
use consistent dates in inspect()
93d6b5fb68eae8b0912579980e17ebf0723ab2cc
<ide><path>lib/util.js <ide> function formatValue(ctx, value, recurseTimes) { <ide> return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); <ide> } <ide> if (isDate(value)) { <del> return ctx.stylize(Date.prototype.toString.call(value), 'date'); <add> return ctx.stylize(Date.prototype.toISOString.call(value), 'date'); <ide> } <ide> if (isError(value)) { <ide> return formatError(value); <ide> function formatValue(ctx, value, recurseTimes) { <ide> <ide> // Make dates with properties first say the date <ide> if (isDate(value)) { <del> base = ' ' + Date.prototype.toUTCString.call(value); <add> base = ' ' + Date.prototype.toISOString.call(value); <ide> } <ide> <ide> // Make error with message first say the error <ide><path>test/parallel/test-util-inspect.js <ide> assert.equal(util.inspect(undefined), 'undefined'); <ide> assert.equal(util.inspect(null), 'null'); <ide> assert.equal(util.inspect(/foo(bar\n)?/gi), '/foo(bar\\n)?/gi'); <ide> assert.equal(util.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT')), <del> new Date('2010-02-14T12:48:40+01:00').toString()); <add> new Date('2010-02-14T12:48:40+01:00').toISOString()); <ide> <ide> assert.equal(util.inspect('\n\u0001'), "'\\n\\u0001'"); <ide> <ide> assert.equal(util.inspect(value), '{ /123/gi aprop: 42 }'); <ide> // Dates with properties <ide> value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); <ide> value.aprop = 42; <del>assert.equal(util.inspect(value), '{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }' <add>assert.equal(util.inspect(value), '{ 2010-02-14T11:48:40.000Z aprop: 42 }' <ide> ); <ide> <ide> // test the internal isDate implementation <ide> assert.doesNotThrow(function() { <ide> util.inspect(d); <ide> }); <ide> <add>assert.doesNotThrow(function() { <add> var d = new Date(); <add> d.toISOString = null; <add> util.inspect(d); <add>}); <add> <ide> assert.doesNotThrow(function() { <ide> var r = /regexp/; <ide> r.toString = null;
2
PHP
PHP
fix singularization of databases
13468937cce7869990d017eadfecf6e5a859cc99
<ide><path>lib/Cake/Test/Case/Utility/InflectorTest.php <ide> public function testInflectingSingulars() { <ide> $this->assertEquals(Inflector::singularize('cafes'), 'cafe'); <ide> $this->assertEquals(Inflector::singularize('roofs'), 'roof'); <ide> $this->assertEquals(Inflector::singularize('foes'), 'foe'); <add> $this->assertEquals(Inflector::singularize('databases'), 'database'); <ide> <ide> $this->assertEquals(Inflector::singularize(''), ''); <ide> } <ide><path>lib/Cake/Utility/Inflector.php <ide> class Inflector { <ide> '/(drive)s$/i' => '\1', <ide> '/([^fo])ves$/i' => '\1fe', <ide> '/(^analy)ses$/i' => '\1sis', <del> '/(analy|ba|diagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis', <add> '/(analy|diagno|^ba|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis', <ide> '/([ti])a$/i' => '\1um', <ide> '/(p)eople$/i' => '\1\2erson', <ide> '/(m)en$/i' => '\1an',
2
Javascript
Javascript
flowify some libraries
18b6d5c20d577888cdd8fbe65eb8e14ddc3547d9
<ide><path>Libraries/BatchedBridge/BatchedBridgedModules/NativeModules.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule NativeModules <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide><path>Libraries/BatchedBridge/BatchedBridgedModules/RCTAlertManager.ios.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule RCTAlertManager <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide><path>Libraries/BatchedBridge/BatchedBridgedModules/RCTEventEmitter.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule RCTEventEmitter <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide><path>Libraries/BatchedBridge/BatchedBridgedModules/RCTJSTimers.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule RCTJSTimers <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide><path>Libraries/CameraRoll/CameraRoll.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule CameraRoll <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide> var GROUP_TYPES_OPTIONS = [ <ide> 'SavedPhotos', // default <ide> ]; <ide> <del>deepFreezeAndThrowOnMutationInDev(GROUP_TYPES_OPTIONS); <add>// Flow treats Object and Array as disjoint types, currently. <add>deepFreezeAndThrowOnMutationInDev((GROUP_TYPES_OPTIONS: any)); <ide> <ide> /** <ide> * Shape of the param arg for the `getPhotos` function. <ide><path>Libraries/Device/RCTDeviceEventEmitter.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule RCTDeviceEventEmitter <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide><path>Libraries/Geolocation/Geolocation.ios.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <ide> * @providesModule Geolocation <add> * @flow <ide> */ <ide> 'use strict'; <ide> <ide> var updatesEnabled = false; <ide> */ <ide> var Geolocation = { <ide> <del> getCurrentPosition: function(geo_success, geo_error, geo_options) { <add> getCurrentPosition: function( <add> geo_success: Function, <add> geo_error?: Function, <add> geo_options?: Object) { <ide> invariant( <ide> typeof geo_success === 'function', <ide> 'Must provide a valid geo_success callback.' <ide> var Geolocation = { <ide> ); <ide> }, <ide> <del> watchPosition: function(success, error, options) { <add> watchPosition: function(success: Function, error?: Function, options?: Object): number { <ide> if (!updatesEnabled) { <ide> RCTLocationObserver.startObserving(options || {}); <ide> updatesEnabled = true; <ide> var Geolocation = { <ide> return watchID; <ide> }, <ide> <del> clearWatch: function(watchID) { <add> clearWatch: function(watchID: number) { <ide> var sub = subscriptions[watchID]; <ide> if (!sub) { <ide> // Silently exit when the watchID is invalid or already cleared <ide> // This is consistent with timers <ide> return; <ide> } <add> <ide> sub[0].remove(); <del> sub[1] && sub[1].remove(); <add> // array element refinements not yet enabled in Flow <add> var sub1 = sub[1]; sub1 && sub1.remove(); <ide> subscriptions[watchID] = undefined; <ide> var noWatchers = true; <ide> for (var ii = 0; ii < subscriptions.length; ii++) { <ide> var Geolocation = { <ide> RCTLocationObserver.stopObserving(); <ide> updatesEnabled = false; <ide> for (var ii = 0; ii < subscriptions.length; ii++) { <del> if (subscriptions[ii]) { <add> var sub = subscriptions[ii]; <add> if (sub) { <ide> warning('Called stopObserving with existing subscriptions.'); <del> subscriptions[ii].remove(); <add> sub[0].remove(); <add> // array element refinements not yet enabled in Flow <add> var sub1 = sub[1]; sub1 && sub1.remove(); <ide> } <ide> } <ide> subscriptions = [];
7
PHP
PHP
remove the div option from submit()
35e01a131f558af6573e3001b8b5289ead11ecfc
<ide><path>src/View/Helper/FormHelper.php <ide> class FormHelper extends Helper { <ide> 'formGroup' => '{{label}}{{input}}', <ide> 'checkboxFormGroup' => '{{input}}{{label}}', <ide> 'groupContainer' => '<div class="input {{type}}{{required}}">{{content}}</div>', <del> 'groupContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{{error}}</div>' <add> 'groupContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{{error}}</div>', <add> 'submitContainer' => '<div class="submit">{{content}}</div>', <ide> ]; <ide> <ide> /** <ide> public function postLink($title, $url = null, $options = array(), $confirmMessag <ide> * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit' <ide> * - Other attributes will be assigned to the input element. <ide> * <del> * ### Options <del> * <del> * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to <del> * FormHelper::input(). <del> * - Other attributes will be assigned to the input element. <del> * <ide> * @param string $caption The label appearing on the button OR if string contains :// or the <ide> * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension <ide> * exists, AND the first character is /, image is relative to webroot, <ide> public function submit($caption = null, $options = array()) { <ide> if (!is_string($caption) && empty($caption)) { <ide> $caption = __d('cake', 'Submit'); <ide> } <del> $div = true; <del> <del> if (isset($options['div'])) { <del> $div = $options['div']; <del> unset($options['div']); <del> } <del> $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false); <del> $divOptions = array('tag' => 'div'); <del> <del> if ($div === true) { <del> $divOptions['class'] = 'submit'; <del> } elseif ($div === false) { <del> unset($divOptions); <del> } elseif (is_string($div)) { <del> $divOptions['class'] = $div; <del> } elseif (is_array($div)) { <del> $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div); <del> } <add> $options += array('type' => 'submit', 'secure' => false); <ide> <ide> if (isset($options['name'])) { <ide> $this->_secure($options['secure'], $this->_secureFieldName($options)); <ide> public function submit($caption = null, $options = array()) { <ide> } <ide> $out = $tag; <ide> <del> if (isset($divOptions)) { <del> $tag = $divOptions['tag']; <del> unset($divOptions['tag']); <del> $out = $this->Html->tag($tag, $out, $divOptions); <del> } <del> return $out; <add> return $this->formatTemplate('submitContainer', [ <add> 'content' => $tag <add> ]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testSubmitButton() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $result = $this->Form->submit('Test Submit', array('div' => array('tag' => 'span'))); <del> $expected = array( <del> 'span' => array('class' => 'submit'), <del> 'input' => array('type' => 'submit', 'value' => 'Test Submit'), <del> '/span' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->submit('Test Submit', array('class' => 'save', 'div' => false)); <del> $expected = array('input' => array('type' => 'submit', 'value' => 'Test Submit', 'class' => 'save')); <del> $this->assertTags($result, $expected); <del> <ide> $result = $this->Form->submit('Next >'); <ide> $expected = array( <ide> 'div' => array('class' => 'submit'),
2
Text
Text
translate angular resources to pt-br
98199763f686e9d92e72d55a731814152690caf3
<ide><path>guide/portuguese/angular/angular-resources/index.md <ide> --- <ide> title: Angular Resources <del>localeTitle: Recursos angulares <add>localeTitle: Recursos para Angular <ide> --- <del>Uma coleção de recursos angulares úteis <add>Uma coleção de recursos úteis para Angular <ide> <ide> ## Angular 1.x <ide> <del>### Páginas gerais <add>### Geral <ide> <del>* [Angular JS](https://angularjs.org/) - The Angular JS Homepage <del>* [AngularJS Style Guide](https://github.com/johnpapa/angular-styleguide/tree/master/a1) - Boas Práticas Detalhadas para o Desenvolvimento Angular <add>* [Angular JS](https://angularjs.org/) - Página Inicial do Angular JS <add>* [AngularJS Style Guide](https://github.com/johnpapa/angular-styleguide/tree/master/a1) - Boas Práticas para o Desenvolvimento Angular <ide> <ide> ### Vídeos <ide> <del>* [Roteamento no Angular JS](https://www.youtube.com/watch?v=5uhZCc0j9RY) - Roteamento do Cliente em 15 minutos <del>* [Angular ToDo App](https://www.youtube.com/watch?v=WuiHuZq_cg4) - Um aplicativo Angular ToDo em 12 minutos <add>* [Rotas no Angular JS](https://www.youtube.com/watch?v=5uhZCc0j9RY) - Rotas Client-Side em 15 minutos <add>* [App ToDo Angular](https://www.youtube.com/watch?v=WuiHuZq_cg4) - Um aplicativo To-Do em Angular em 12 minutos <ide> <ide> ### Cursos <ide> <del>* [Cursos de Egghead.io AngularJS ($)](https://egghead.io/browse/frameworks/angularjs) <add>* [Cursos de AngularJS do Egghead.io ($)](https://egghead.io/browse/frameworks/angularjs) <ide> <ide> ## Angular 2.x + <ide> <del>### Páginas gerais <add>### Geral <ide> <del>* [Angular](https://angular.io/) - a página inicial angular <del>* [Guia de Estilo Angular](https://angular.io/guide/styleguide) - Melhores Práticas Detalhadas para o Desenvolvimento Angular <add>* [Angular](https://angular.io/) - Página Inicial do Angular <add>* [Guia de Estilo Angular](https://angular.io/guide/styleguide) - Melhores Práticas para o Desenvolvimento com Angular <ide> <del>### Páginas de tópicos específicos <add>### Páginas de Tópicos Específicos <ide> <del>* [Diretivas](http://www.sitepoint.com/practical-guide-angularjs-directives/) - Excelente guia em detalhes sobre diretivas angulares (parte 1) <add>* [Diretivas](http://www.sitepoint.com/practical-guide-angularjs-directives/) - Excelente guia que explica em detalhes as Diretivas Angular (parte 1) <ide> <ide> ### Cursos <ide> <del>* [Cursos Angulares Egghead.io ($)](https://egghead.io/browse/frameworks/angular) <del>* [FrontendMasters - Criando Aplicativos Awesomer com Angular](https://frontendmasters.com/courses/building-apps-angular) <del>* [Angular final - lema de Todd](https://ultimateangular.com/) <add>* [Cursos de Angular do Egghead.io ($)](https://egghead.io/browse/frameworks/angular) <add>* [FrontendMasters - Criando Aplicativos Incríveis com Angular](https://frontendmasters.com/courses/building-apps-angular) <add>* [Ultimate Angular - Todd Motto](https://ultimateangular.com/) <ide> * [Angular 6 (anteriormente Angular 2) - O Guia Completo ($) Maximilian Schwarzmüller](https://www.udemy.com/the-complete-guide-to-angular-2/) <ide> <ide> ## Blogs <ide> <ide> * [Alligator.io](https://alligator.io/angular/) <del>* [Angular em Profundidade](https://blog.angularindepth.com/tagged/angular) <ide>\ No newline at end of file <add>* [Angular in Depth](https://blog.angularindepth.com/tagged/angular)
1
Text
Text
remove travis status image
58159e308b2356265faed168909122c4ef0f61d4
<ide><path>README.md <del>Evented I/O for V8 javascript. [![Build Status](https://secure.travis-ci.org/joyent/node.png)](http://travis-ci.org/joyent/node) <add>Evented I/O for V8 javascript. <ide> === <ide> <ide> ### To build:
1
Ruby
Ruby
use arg size for parallel iteration
b1051c5dfa0a5d9f7bb672ce9223167d1b5415a9
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def optimize_routes_generation?(t) <ide> <ide> def parameterize_args(args) <ide> params = {} <del> @required_parts.zip(args.map(&:to_param)) { |k,v| params[k] = v } <add> @arg_size.times { |i| params[@required_parts[i]] = args[i].to_param } <ide> params <ide> end <ide>
1
Javascript
Javascript
fix incorrect cast
9735d25967126e9f4d22a7d90d50ea40169b55a6
<ide><path>lib/stats/DefaultStatsFactoryPlugin.js <ide> <ide> "use strict"; <ide> <add>const ModuleDependency = require("../dependencies/ModuleDependency"); <ide> const formatLocation = require("../formatLocation"); <ide> const { LogType } = require("../logging/Logger"); <ide> const AggressiveSplittingPlugin = require("../optimize/AggressiveSplittingPlugin"); <ide> const identifierUtils = require("../util/identifier"); <ide> /** @typedef {import("../ModuleProfile")} ModuleProfile */ <ide> /** @typedef {import("../RequestShortener")} RequestShortener */ <ide> /** @typedef {import("../WebpackError")} WebpackError */ <del>/** @typedef {import("../dependencies/ModuleDependency")} ModuleDependency */ <ide> /** @template T @typedef {import("../util/comparators").Comparator<T>} Comparator<T> */ <ide> /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ <ide> /** @typedef {import("./StatsFactory")} StatsFactory */ <ide> const SIMPLE_EXTRACTORS = { <ide> }, <ide> moduleReason: { <ide> _: (object, reason, { runtime }, { requestShortener }) => { <del> const depAsAny = /** @type {ModuleDependency|undefined} */ (reason.dependency); <add> const dep = reason.dependency; <add> const moduleDep = <add> dep && dep instanceof ModuleDependency ? dep : undefined; <ide> Object.assign(object, { <ide> moduleIdentifier: reason.originModule <ide> ? reason.originModule.identifier() <ide> const SIMPLE_EXTRACTORS = { <ide> type: reason.dependency ? reason.dependency.type : null, <ide> active: reason.isActive(runtime), <ide> explanation: reason.explanation, <del> userRequest: (depAsAny && depAsAny.userRequest) || null <add> userRequest: (moduleDep && moduleDep.userRequest) || null <ide> }); <ide> if (reason.dependency) { <ide> const locInfo = formatLocation(reason.dependency.loc); <ide><path>lib/wasm/WebAssemblyJavascriptGenerator.js <ide> const Generator = require("../Generator"); <ide> const InitFragment = require("../InitFragment"); <ide> const RuntimeGlobals = require("../RuntimeGlobals"); <ide> const Template = require("../Template"); <add>const ModuleDependency = require("../dependencies/ModuleDependency"); <ide> const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); <ide> const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); <ide> <ide> const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDe <ide> /** @typedef {import("../Generator").GenerateContext} GenerateContext */ <ide> /** @typedef {import("../NormalModule")} NormalModule */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <del>/** @typedef {import("../dependencies/ModuleDependency")} ModuleDependency */ <ide> <ide> const TYPES = new Set(["webassembly"]); <ide> <ide> class WebAssemblyJavascriptGenerator extends Generator { <ide> const initParams = []; <ide> let index = 0; <ide> for (const dep of module.dependencies) { <del> const depAsAny = /** @type {ModuleDependency} */ (dep); <add> const moduleDep = <add> dep && dep instanceof ModuleDependency ? dep : undefined; <ide> if (moduleGraph.getModule(dep)) { <ide> let importData = importedModules.get(moduleGraph.getModule(dep)); <ide> if (importData === undefined) { <ide> class WebAssemblyJavascriptGenerator extends Generator { <ide> (importData = { <ide> importVar: `m${index}`, <ide> index, <del> request: (depAsAny && depAsAny.userRequest) || undefined, <add> request: (moduleDep && moduleDep.userRequest) || undefined, <ide> names: new Set(), <ide> reexports: [] <ide> })
2
Python
Python
add unittests for the endpoint decorator
8a73097fe528430eb77ac26c81ba85229a8af553
<ide><path>tests/flask_tests.py <ide> def index(): <ide> assert c.get('/foo/').data == 'index' <ide> assert c.get('/foo/bar').data == 'bar' <ide> <add> def test_endpoint_decorator(self): <add> from werkzeug.routing import Submount, Rule <add> app = flask.Flask(__name__) <add> app.url_map.add(Submount('/foo', [ <add> Rule('/bar', endpoint='bar'), <add> Rule('/', endpoint='index') <add> ])) <add> <add> @app.endpoint('bar') <add> def bar(): <add> return 'bar' <add> <add> @app.endpoint('index') <add> def index(): <add> return 'index' <add> <add> c = app.test_client() <add> assert c.get('/foo/').data == 'index' <add> assert c.get('/foo/bar').data == 'bar' <add> <ide> def test_session(self): <ide> app = flask.Flask(__name__) <ide> app.secret_key = 'testkey' <ide> def test_safe_access(self): <ide> finally: <ide> os.path = old_path <ide> <add> def test_endpoint_decorator(self): <add> from werkzeug.routing import Submount, Rule <add> from flask import Module <add> <add> app = flask.Flask(__name__) <add> app.url_map.add(Submount('/foo', [ <add> Rule('/bar', endpoint='bar'), <add> Rule('/', endpoint='index') <add> ])) <add> module = Module(__name__, __name__) <add> <add> @module.endpoint('bar') <add> def bar(): <add> return 'bar' <add> <add> @module.endpoint('index') <add> def index(): <add> return 'index' <add> <add> app.register_module(module) <add> <add> c = app.test_client() <add> assert c.get('/foo/').data == 'index' <add> assert c.get('/foo/bar').data == 'bar' <add> <ide> <ide> class SendfileTestCase(unittest.TestCase): <ide>
1
Ruby
Ruby
update collectionproxy#clear documentation
8281194fee1a049826c50f9e0a095ea1abb91277
<ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> def <<(*records) <ide> end <ide> alias_method :push, :<< <ide> <del> # Removes every object from the collection. This does not destroy <del> # the objects, it sets their foreign keys to +NULL+. Returns +self+ <del> # so methods can be chained. <add> # Equivalent to +delete_all+. The difference is that returns +self+, instead <add> # of an array with the deleted objects, so methods can be chained. <ide> # <ide> # class Person < ActiveRecord::Base <ide> # has_many :pets
1
Javascript
Javascript
expand test coverage of fs.js
efbda74686e51525517ec2f89b75039d1db57e59
<ide><path>test/parallel/test-fs-truncate-sync.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const fs = require('fs'); <add>const tmp = common.tmpDir; <add> <add>common.refreshTmpDir(); <add> <add>const filename = path.resolve(tmp, 'truncate-sync-file.txt'); <add> <add>fs.writeFileSync(filename, 'hello world', 'utf8'); <add> <add>const fd = fs.openSync(filename, 'r+'); <add> <add>fs.truncateSync(fd, 5); <add>assert(fs.readFileSync(fd).equals(Buffer.from('hello'))); <add> <add>fs.closeSync(fd); <add>fs.unlinkSync(filename); <ide><path>test/parallel/test-fs-truncate.js <ide> function testFtruncate(cb) { <ide> assert(fs.readFileSync(file4).equals(Buffer.from('Hi\u0000\u0000'))); <ide> })); <ide> } <add> <add>{ <add> const file5 = path.resolve(tmp, 'truncate-file-5.txt'); <add> fs.writeFileSync(file5, 'Hi'); <add> const fd = fs.openSync(file5, 'r+'); <add> process.on('exit', () => fs.closeSync(fd)); <add> fs.ftruncate(fd, undefined, common.mustCall(function(err) { <add> assert.ifError(err); <add> assert(fs.readFileSync(file5).equals(Buffer.from(''))); <add> })); <add>}
2
Text
Text
add note about fs.close() about undefined behavior
b376965e503f7cdfc5b2888bd1425f44f79013a9
<ide><path>doc/api/fs.md <ide> changes: <ide> Asynchronous close(2). No arguments other than a possible exception are given <ide> to the completion callback. <ide> <add>Calling `fs.close()` on any file descriptor (`fd`) that is currently in use <add>through any other `fs` operation may lead to undefined behavior. <add> <ide> ## fs.closeSync(fd) <ide> <!-- YAML <ide> added: v0.1.21 <ide> added: v0.1.21 <ide> <ide> Synchronous close(2). Returns `undefined`. <ide> <add>Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use <add>through any other `fs` operation may lead to undefined behavior. <add> <ide> ## fs.constants <ide> <ide> * {Object}
1
Ruby
Ruby
skip casks before extracting
bf46814dddade04338d85aea51d9446830c01e0a
<ide><path>Library/Homebrew/dev-cmd/bump-unversioned-casks.rb <ide> def self.bump_unversioned_casks <ide> <ide> ohai "Checking #{cask.full_name}" <ide> <add> unless single_app_cask?(cask) || single_pkg_cask?(cask) <add> opoo "Skipping, cask #{cask} it not a single-app or PKG cask." <add> next <add> end <add> <ide> last_state = state.fetch(cask.full_name, {}) <ide> last_check_time = last_state["check_time"]&.yield_self { |t| Time.parse(t) } <ide>
1
Python
Python
add timeout to outdated too
331f2372a7b28bbaf2c64f9bc9c142122c981910
<ide><path>glances/outdated.py <ide> def _update_pypi_version(self): <ide> self.data[u'refresh_date'] = datetime.now() <ide> <ide> try: <del> res = requests.get(self.PYPI_API_URL) <add> res = requests.get(self.PYPI_API_URL, timeout=3) <ide> except Exception as e: <ide> logger.debug("Cannot get the Glances version from the PyPI RESTful API ({})".format(e)) <ide> else:
1
Ruby
Ruby
add some attribute readers to migration module
25647f70215e38635d16038e71f47730f2717021
<ide><path>railties/lib/generators/active_record/migration/templates/migration.rb <del>class <%= @migration_class_name %> < ActiveRecord::Migration <add>class <%= migration_class_name %> < ActiveRecord::Migration <ide> def self.up<% attributes.each do |attribute| %> <ide> <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end -%> <ide> <%- end %> <ide><path>railties/lib/generators/active_record/model/templates/migration.rb <del>class <%= @migration_class_name %> < ActiveRecord::Migration <add>class <%= migration_class_name %> < ActiveRecord::Migration <ide> def self.up <ide> create_table :<%= table_name %> do |t| <ide> <% for attribute in attributes -%> <ide><path>railties/lib/generators/active_record/session_migration/templates/migration.rb <del>class <%= @migration_class_name %> < ActiveRecord::Migration <add>class <%= migration_class_name %> < ActiveRecord::Migration <ide> def self.up <ide> create_table :<%= session_table_name %> do |t| <ide> t.string :session_id, :null => false <ide><path>railties/lib/generators/migration.rb <ide> module Generators <ide> # just by implementing the next migration number method. <ide> # <ide> module Migration <add> def self.included(base) #:nodoc: <add> base.send :attr_reader, :migration_number, <add> :migration_file_name, <add> :migration_class_name <add> end <ide> <ide> # Creates a migration template at the given destination. The difference <ide> # to the default template method is that the migration number is appended
4
PHP
PHP
apply parameters to entire localization array
9e25f7d21721a0c13d04679fa59a68a8c788fdbc
<ide><path>src/Illuminate/Translation/Translator.php <ide> protected function getLine($namespace, $group, $locale, $item, array $replace) <ide> if (is_string($line)) { <ide> return $this->makeReplacements($line, $replace); <ide> } elseif (is_array($line) && count($line) > 0) { <add> foreach($line as $key => $val) { <add> $line[$key] = $this->makeReplacements($val, $replace); <add> } <ide> return $line; <ide> } <ide> }
1
PHP
PHP
fix method name in shouldbestrict method
1066e3955bfd0a7877707786efbf4fda9d450502
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function shouldBeStrict(bool $shouldBeStrict = true) <ide> <ide> static::preventLazyLoading(); <ide> static::preventSilentlyDiscardingAttributes(); <del> static::preventsAccessingMissingAttributes(); <add> static::preventAccessingMissingAttributes(); <ide> } <ide> <ide> /**
1
Mixed
Java
implement lazy discovery for viewmanagers
da30b047037a1b4a97159b22abfd5244ecfaee19
<ide><path>Libraries/ReactNative/UIManager.js <ide> if (Platform.OS === 'ios') { <ide> }); <ide> } <ide> }); <del>} else if ( <del> Platform.OS === 'android' && <del> UIManager.AndroidLazyViewManagersEnabled <del>) { <add>} else if (Platform.OS === 'android' && UIManager.ViewManagerNames) { <ide> UIManager.ViewManagerNames.forEach(viewManagerName => { <ide> defineLazyObjectProperty(UIManager, viewManagerName, { <del> get: () => NativeModules[viewManagerName.replace(/^(RCT|RK)/, '')], <add> get: () => UIManager.getConstantsForViewManager(viewManagerName), <ide> }); <ide> }); <ide> } <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java <ide> protected void setUp() throws Exception { <ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList( <ide> new ReactViewManager()); <ide> final UIManagerModule mUIManager = <del> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), 0); <ide> UiThreadUtil.runOnUiThread( <ide> new Runnable() { <ide> @Override <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java <ide> protected void setUp() throws Exception { <ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList( <ide> new ReactViewManager()); <ide> final UIManagerModule mUIManager = <del> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), 0); <ide> UiThreadUtil.runOnUiThread( <ide> new Runnable() { <ide> @Override <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSReturnValuesTestCase.java <ide> protected void setUp() throws Exception { <ide> <ide> final UIManagerModule mUIManager = <ide> new UIManagerModule( <del> getContext(), new ArrayList<ViewManager>(), new UIImplementationProvider(), false, 0); <add> getContext(), new ArrayList<ViewManager>(), new UIImplementationProvider(), 0); <ide> <ide> mAssertModule = new AssertModule(); <ide> <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystUIManagerTestCase.java <ide> protected void setUp() throws Exception { <ide> new ReactTextViewManager(), <ide> new ReactRawTextManager()); <ide> uiManager = <del> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), 0); <ide> UiThreadUtil.runOnUiThread(new Runnable() { <ide> @Override <ide> public void run() { <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java <ide> protected void setUp() throws Exception { <ide> getContext(), <ide> viewManagers, <ide> new UIImplementationProvider(), <del> false, <ide> 0); <ide> UiThreadUtil.runOnUiThread( <ide> new Runnable() { <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java <ide> protected void setUp() throws Exception { <ide> new ReactViewManager(), <ide> new ReactProgressBarViewManager()); <ide> mUIManager = <del> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), 0); <ide> UiThreadUtil.runOnUiThread( <ide> new Runnable() { <ide> @Override <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java <ide> protected void setUp() throws Exception { <ide> <ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager()); <ide> final UIManagerModule uiManager = <del> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(getContext(), viewManagers, new UIImplementationProvider(), 0); <ide> UiThreadUtil.runOnUiThread( <ide> new Runnable() { <ide> @Override <ide><path>ReactAndroid/src/main/java/com/facebook/react/CompositeReactPackage.java <ide> <ide> package com.facebook.react; <ide> <add>import com.facebook.react.bridge.NativeModule; <add>import com.facebook.react.bridge.ReactApplicationContext; <add>import com.facebook.react.uimanager.ViewManager; <ide> import java.util.ArrayList; <add>import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.List; <add>import java.util.ListIterator; <ide> import java.util.Map; <ide> import java.util.Set; <del> <del>import com.facebook.react.bridge.JavaScriptModule; <del>import com.facebook.react.bridge.NativeModule; <del>import com.facebook.react.bridge.ReactApplicationContext; <del>import com.facebook.react.uimanager.ViewManager; <add>import javax.annotation.Nullable; <ide> <ide> /** <ide> * {@code CompositeReactPackage} allows to create a single package composed of views and modules <ide> * from several other packages. <ide> */ <del>public class CompositeReactPackage extends ReactInstancePackage { <add>public class CompositeReactPackage extends ReactInstancePackage <add> implements ViewManagerOnDemandReactPackage { <ide> <ide> private final List<ReactPackage> mChildReactPackages = new ArrayList<>(); <ide> <ide> public CompositeReactPackage(ReactPackage arg1, ReactPackage arg2, ReactPackage. <ide> mChildReactPackages.add(arg1); <ide> mChildReactPackages.add(arg2); <ide> <del> for (ReactPackage reactPackage: args) { <del> mChildReactPackages.add(reactPackage); <del> } <add> Collections.addAll(mChildReactPackages, args); <ide> } <ide> <ide> /** <ide> public List<NativeModule> createNativeModules(ReactApplicationContext reactConte <ide> moduleMap.put(nativeModule.getName(), nativeModule); <ide> } <ide> } <del> return new ArrayList(moduleMap.values()); <add> return new ArrayList<>(moduleMap.values()); <ide> } <ide> <ide> /** <ide> public List<NativeModule> createNativeModules( <ide> moduleMap.put(nativeModule.getName(), nativeModule); <ide> } <ide> } <del> return new ArrayList(moduleMap.values()); <add> return new ArrayList<>(moduleMap.values()); <ide> } <ide> <ide> /** <ide> public List<ViewManager> createViewManagers(ReactApplicationContext reactContext <ide> viewManagerMap.put(viewManager.getName(), viewManager); <ide> } <ide> } <del> return new ArrayList(viewManagerMap.values()); <add> return new ArrayList<>(viewManagerMap.values()); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public List<String> getViewManagerNames(ReactApplicationContext reactContext) { <add> Set<String> uniqueNames = new HashSet<>(); <add> for (ReactPackage reactPackage : mChildReactPackages) { <add> if (reactPackage instanceof ViewManagerOnDemandReactPackage) { <add> List<String> names = <add> ((ViewManagerOnDemandReactPackage) reactPackage).getViewManagerNames(reactContext); <add> if (names != null) { <add> uniqueNames.addAll(names); <add> } <add> } <add> } <add> return new ArrayList<>(uniqueNames); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public @Nullable ViewManager createViewManager( <add> ReactApplicationContext reactContext, String viewManagerName) { <add> ListIterator<ReactPackage> iterator = mChildReactPackages.listIterator(mChildReactPackages.size()); <add> while (iterator.hasPrevious()) { <add> ReactPackage reactPackage = iterator.previous(); <add> if (reactPackage instanceof ViewManagerOnDemandReactPackage) { <add> ViewManager viewManager = <add> ((ViewManagerOnDemandReactPackage) reactPackage).createViewManager(reactContext, viewManagerName); <add> if (viewManager != null) { <add> return viewManager; <add> } <add> } <add> } <add> return null; <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java <ide> import com.facebook.systrace.Systrace; <ide> import java.util.ArrayList; <ide> import java.util.List; <add>import javax.annotation.Nullable; <ide> import javax.inject.Provider; <ide> /** <ide> * This module should be removed following the completion of an experiment into splitting this into <ide> public ReactModuleInfoProvider getReactModuleInfoProvider() { <ide> return LazyReactPackage.getReactModuleInfoProviderViaReflection(this); <ide> } <ide> <del> private UIManagerModule createUIManager(ReactApplicationContext reactContext) { <add> private UIManagerModule createUIManager(final ReactApplicationContext reactContext) { <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_START); <ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createUIManagerModule"); <ide> try { <del> List<ViewManager> viewManagersList = mReactInstanceManager.createAllViewManagers( <del> reactContext); <del> return new UIManagerModule( <del> reactContext, <del> viewManagersList, <del> mUIImplementationProvider, <del> mLazyViewManagersEnabled, <del> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> if (mLazyViewManagersEnabled) { <add> UIManagerModule.ViewManagerResolver resolver = new UIManagerModule.ViewManagerResolver() { <add> @Override <add> public @Nullable ViewManager getViewManager(String viewManagerName) { <add> return mReactInstanceManager.createViewManager(viewManagerName); <add> } <add> @Override <add> public List<String> getViewManagerNames() { <add> return mReactInstanceManager.getViewManagerNames(); <add> } <add> }; <add> <add> return new UIManagerModule( <add> reactContext, <add> resolver, <add> mUIImplementationProvider, <add> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> } else { <add> return new UIManagerModule( <add> reactContext, <add> mReactInstanceManager.createAllViewManagers(reactContext), <add> mUIImplementationProvider, <add> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> } <ide> } finally { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_END); <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> import java.util.Collections; <ide> import java.util.HashSet; <ide> import java.util.List; <add>import java.util.Set; <ide> import javax.annotation.Nullable; <ide> <ide> /** <ide> public static ReactInstanceManagerBuilder builder() { <ide> mMinTimeLeftInFrameForNonBatchedOperationMs = minTimeLeftInFrameForNonBatchedOperationMs; <ide> mUseSeparateUIBackgroundThread = useSeparateUIBackgroundThread; <ide> mMinNumShakes = minNumShakes; <del> <del> if (!splitPackagesEnabled) { <del> CoreModulesPackage coreModulesPackage = <add> synchronized (mPackages) { <add> if (!splitPackagesEnabled) { <add> CoreModulesPackage coreModulesPackage = <ide> new CoreModulesPackage( <add> this, <add> mBackBtnHandler, <add> mUIImplementationProvider, <add> mLazyViewManagersEnabled, <add> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> mPackages.add(coreModulesPackage); <add> } else { <add> PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: Use Split Packages"); <add> mPackages.add(new BridgeCorePackage(this, mBackBtnHandler)); <add> if (mUseDeveloperSupport) { <add> mPackages.add(new DebugCorePackage()); <add> } <add> if (!useOnlyDefaultPackages) { <add> mPackages.add(new ReactNativeCorePackage( <ide> this, <del> mBackBtnHandler, <ide> mUIImplementationProvider, <ide> mLazyViewManagersEnabled, <del> mMinTimeLeftInFrameForNonBatchedOperationMs); <del> mPackages.add(coreModulesPackage); <del> } else { <del> PrinterHolder.getPrinter() <del> .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: Use Split Packages"); <del> mPackages.add(new BridgeCorePackage(this, mBackBtnHandler)); <del> if (mUseDeveloperSupport) { <del> mPackages.add(new DebugCorePackage()); <del> } <del> if (!useOnlyDefaultPackages) { <del> mPackages.add( <del> new ReactNativeCorePackage( <del> this, <del> mUIImplementationProvider, <del> mLazyViewManagersEnabled, <del> mMinTimeLeftInFrameForNonBatchedOperationMs)); <add> mMinTimeLeftInFrameForNonBatchedOperationMs)); <add> } <ide> } <add> mPackages.addAll(packages); <ide> } <del> mPackages.addAll(packages); <ide> <ide> // Instantiate ReactChoreographer in UI thread. <ide> ReactChoreographer.initialize(); <ide> public void registerAdditionalPackages(List<ReactPackage> packages) { <ide> <ide> // CatalystInstance hasn't been created, so add packages for later evaluation <ide> if (!hasStartedCreatingInitialContext()) { <del> for (ReactPackage p : packages) { <del> if (!mPackages.contains(p)) { <del> mPackages.add(p); <add> synchronized (mPackages) { <add> for (ReactPackage p : packages) { <add> if (!mPackages.contains(p)) { <add> mPackages.add(p); <add> } <ide> } <ide> } <ide> return; <ide> public List<ViewManager> createAllViewManagers( <ide> ReactMarker.logMarker(CREATE_VIEW_MANAGERS_START); <ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createAllViewManagers"); <ide> try { <del> List<ViewManager> allViewManagers = new ArrayList<>(); <del> for (ReactPackage reactPackage : mPackages) { <del> allViewManagers.addAll(reactPackage.createViewManagers(catalystApplicationContext)); <add> synchronized (mPackages) { <add> List<ViewManager> allViewManagers = new ArrayList<>(); <add> for (ReactPackage reactPackage : mPackages) { <add> allViewManagers.addAll(reactPackage.createViewManagers(catalystApplicationContext)); <add> } <add> return allViewManagers; <ide> } <del> return allViewManagers; <ide> } finally { <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> ReactMarker.logMarker(CREATE_VIEW_MANAGERS_END); <ide> } <ide> } <ide> <add> public @Nullable ViewManager createViewManager(String viewManagerName) { <add> ReactApplicationContext context = <add> Assertions.assertNotNull((ReactApplicationContext) getCurrentReactContext()); <add> synchronized (mPackages) { <add> for (ReactPackage reactPackage : mPackages) { <add> if (reactPackage instanceof ViewManagerOnDemandReactPackage) { <add> ViewManager viewManager = <add> ((ViewManagerOnDemandReactPackage) reactPackage) <add> .createViewManager(context, viewManagerName); <add> if (viewManager != null) { <add> return viewManager; <add> } <add> } <add> } <add> } <add> return null; <add> } <add> <add> public List<String> getViewManagerNames() { <add> ReactApplicationContext context = <add> Assertions.assertNotNull((ReactApplicationContext) getCurrentReactContext()); <add> synchronized (mPackages) { <add> Set<String> uniqueNames = new HashSet<>(); <add> for (ReactPackage reactPackage : mPackages) { <add> if (reactPackage instanceof ViewManagerOnDemandReactPackage) { <add> List<String> names = <add> ((ViewManagerOnDemandReactPackage) reactPackage).getViewManagerNames(context); <add> if (names != null) { <add> uniqueNames.addAll(names); <add> } <add> } <add> } <add> return new ArrayList<>(uniqueNames); <add> } <add> } <add> <ide> /** <ide> * Add a listener to be notified of react instance events. <ide> */ <ide> private NativeModuleRegistry processPackages( <ide> ReactMarker.logMarker(PROCESS_PACKAGES_START); <ide> <ide> // TODO(6818138): Solve use-case of native modules overriding <del> for (ReactPackage reactPackage : packages) { <del> if (checkAndUpdatePackageMembership && mPackages.contains(reactPackage)) { <del> continue; <del> } <del> Systrace.beginSection( <del> TRACE_TAG_REACT_JAVA_BRIDGE, <del> "createAndProcessCustomReactPackage"); <del> try { <del> if (checkAndUpdatePackageMembership) { <del> mPackages.add(reactPackage); <add> synchronized (mPackages) { <add> for (ReactPackage reactPackage : packages) { <add> if (checkAndUpdatePackageMembership && mPackages.contains(reactPackage)) { <add> continue; <add> } <add> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createAndProcessCustomReactPackage"); <add> try { <add> if (checkAndUpdatePackageMembership) { <add> mPackages.add(reactPackage); <add> } <add> processPackage(reactPackage, nativeModuleRegistryBuilder); <add> } finally { <add> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <del> processPackage(reactPackage, nativeModuleRegistryBuilder); <del> } finally { <del> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> ReactMarker.logMarker(PROCESS_PACKAGES_END); <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactNativeCorePackage.java <ide> import com.facebook.systrace.Systrace; <ide> import java.util.ArrayList; <ide> import java.util.List; <add>import javax.annotation.Nullable; <ide> import javax.inject.Provider; <ide> <ide> /** <ide> public ReactModuleInfoProvider getReactModuleInfoProvider() { <ide> return reactModuleInfoProvider; <ide> } <ide> <del> private UIManagerModule createUIManager(ReactApplicationContext reactContext) { <add> private UIManagerModule createUIManager(final ReactApplicationContext reactContext) { <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_START); <ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createUIManagerModule"); <ide> try { <del> List<ViewManager> viewManagersList = mReactInstanceManager.createAllViewManagers( <del> reactContext); <del> return new UIManagerModule( <del> reactContext, <del> viewManagersList, <del> mUIImplementationProvider, <del> mLazyViewManagersEnabled, <del> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> if (mLazyViewManagersEnabled) { <add> UIManagerModule.ViewManagerResolver viewManagerResolver = <add> new UIManagerModule.ViewManagerResolver() { <add> @Override <add> public @Nullable ViewManager getViewManager(String viewManagerName) { <add> return mReactInstanceManager.createViewManager(viewManagerName); <add> } <add> <add> @Override <add> public List<String> getViewManagerNames() { <add> return mReactInstanceManager.getViewManagerNames(); <add> } <add> }; <add> <add> return new UIManagerModule( <add> reactContext, <add> viewManagerResolver, <add> mUIImplementationProvider, <add> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> } else { <add> return new UIManagerModule( <add> reactContext, <add> mReactInstanceManager.createAllViewManagers(reactContext), <add> mUIImplementationProvider, <add> mMinTimeLeftInFrameForNonBatchedOperationMs); <add> } <ide> } finally { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_END); <ide><path>ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <add>package com.facebook.react; <add> <add>import com.facebook.react.bridge.ReactApplicationContext; <add>import com.facebook.react.uimanager.ViewManager; <add>import java.util.List; <add>import javax.annotation.Nullable; <add> <add>public interface ViewManagerOnDemandReactPackage { <add> /** <add> * Provides a list of names of ViewManagers with which these modules can be accessed from JS. <add> * Typically, this is ViewManager.getName(). <add> */ <add> List<String> getViewManagerNames(ReactApplicationContext reactContext); <add> /** <add> * Creates and returns a ViewManager with a specific name {@param viewManagerName}. It's up to <add> * an implementing package how to interpret the name. <add> */ <add> @Nullable ViewManager createViewManager(ReactApplicationContext reactContext, String viewManagerName); <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementationProvider.java <ide> <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.uimanager.UIImplementationProvider; <add>import com.facebook.react.uimanager.UIManagerModule; <ide> import com.facebook.react.uimanager.ViewManager; <ide> import com.facebook.react.uimanager.events.EventDispatcher; <ide> import java.util.List; <ide> public FlatUIImplementation createUIImplementation( <ide> mMemoryImprovementEnabled, <ide> minTimeLeftInFrameForNonBatchedOperationMs); <ide> } <add> <add> @Override <add> public FlatUIImplementation createUIImplementation( <add> ReactApplicationContext reactContext, <add> UIManagerModule.ViewManagerResolver viewManagerResolver, <add> EventDispatcher eventDispatcher, <add> int minTimeLeftInFrameForNonBatchedOperationMs) { <add> throw new UnsupportedOperationException( <add> "Lazy version of FlatUIImplementations are not supported"); <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java <ide> public class UIImplementation { <ide> <ide> private long mLastCalculateLayoutTime = 0; <ide> <add> public UIImplementation( <add> ReactApplicationContext reactContext, <add> UIManagerModule.ViewManagerResolver viewManagerResolver, <add> EventDispatcher eventDispatcher, <add> int minTimeLeftInFrameForNonBatchedOperationMs) { <add> this( <add> reactContext, <add> new ViewManagerRegistry(viewManagerResolver), <add> eventDispatcher, <add> minTimeLeftInFrameForNonBatchedOperationMs); <add> } <add> <ide> public UIImplementation( <ide> ReactApplicationContext reactContext, <ide> List<ViewManager> viewManagers, <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java <ide> public class UIImplementationProvider { <ide> public UIImplementation createUIImplementation( <ide> ReactApplicationContext reactContext, <del> List<ViewManager> viewManagers, <add> UIManagerModule.ViewManagerResolver viewManagerResolver, <ide> EventDispatcher eventDispatcher, <ide> int minTimeLeftInFrameForNonBatchedOperationMs) { <ide> return new UIImplementation( <del> reactContext, viewManagers, eventDispatcher, minTimeLeftInFrameForNonBatchedOperationMs); <add> reactContext, <add> viewManagerResolver, <add> eventDispatcher, <add> minTimeLeftInFrameForNonBatchedOperationMs); <add> } <add> <add> public UIImplementation createUIImplementation( <add> ReactApplicationContext reactContext, <add> List<ViewManager> viewManagerList, <add> EventDispatcher eventDispatcher, <add> int minTimeLeftInFrameForNonBatchedOperationMs) { <add> return new UIImplementation( <add> reactContext, <add> viewManagerList, <add> eventDispatcher, <add> minTimeLeftInFrameForNonBatchedOperationMs); <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.debug.holder.PrinterHolder; <ide> import com.facebook.debug.tags.ReactDebugOverlayTags; <add>import com.facebook.proguard.annotations.DoNotStrip; <ide> import com.facebook.react.animation.Animation; <add>import com.facebook.react.bridge.Arguments; <ide> import com.facebook.react.bridge.Callback; <ide> import com.facebook.react.bridge.GuardedRunnable; <ide> import com.facebook.react.bridge.LifecycleEventListener; <ide> import com.facebook.react.bridge.ReactMethod; <ide> import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.bridge.ReadableMap; <add>import com.facebook.react.bridge.WritableMap; <ide> import com.facebook.react.common.ReactConstants; <ide> import com.facebook.react.module.annotations.ReactModule; <ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener; <ide> public class UIManagerModule extends ReactContextBaseJavaModule implements <ide> OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter { <ide> <add> /** <add> * Enables lazy discovery of a specific {@link ViewManager} by its name. <add> */ <add> public interface ViewManagerResolver { <add> /** <add> * {@class UIManagerModule} class uses this method to get a ViewManager by its name. <add> * This is the same name that comes from JS by {@code UIManager.ViewManagerName} call. <add> */ <add> @Nullable ViewManager getViewManager(String viewManagerName); <add> <add> /** <add> * Provides a list of view manager names to register in JS as {@code UIManager.ViewManagerName} <add> */ <add> List<String> getViewManagerNames(); <add> } <ide> <ide> /** <ide> * Resolves a name coming from native side to a name of the event that is exposed to JS. <ide> public interface CustomEventNamesResolver { <ide> <ide> private final EventDispatcher mEventDispatcher; <ide> private final Map<String, Object> mModuleConstants; <add> private final Map<String, Object> mCustomDirectEvents; <ide> private final UIImplementation mUIImplementation; <ide> private final MemoryTrimCallback mMemoryTrimCallback = new MemoryTrimCallback(); <ide> <ide> private int mBatchId = 0; <ide> <ide> public UIManagerModule( <ide> ReactApplicationContext reactContext, <del> List<ViewManager> viewManagerList, <add> ViewManagerResolver viewManagerResolver, <ide> UIImplementationProvider uiImplementationProvider, <del> boolean lazyViewManagersEnabled, <ide> int minTimeLeftInFrameForNonBatchedOperationMs) { <ide> super(reactContext); <ide> DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext); <ide> mEventDispatcher = new EventDispatcher(reactContext); <del> mModuleConstants = createConstants(viewManagerList, lazyViewManagersEnabled); <add> mModuleConstants = createConstants(viewManagerResolver); <add> mCustomDirectEvents = UIManagerModuleConstants.getDirectEventTypeConstants(); <ide> mUIImplementation = <ide> uiImplementationProvider.createUIImplementation( <ide> reactContext, <del> viewManagerList, <add> viewManagerResolver, <ide> mEventDispatcher, <ide> minTimeLeftInFrameForNonBatchedOperationMs); <ide> <ide> reactContext.addLifecycleEventListener(this); <ide> } <ide> <add> public UIManagerModule( <add> ReactApplicationContext reactContext, <add> List<ViewManager> viewManagersList, <add> UIImplementationProvider uiImplementationProvider, <add> int minTimeLeftInFrameForNonBatchedOperationMs) { <add> super(reactContext); <add> DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext); <add> mEventDispatcher = new EventDispatcher(reactContext); <add> mModuleConstants = createConstants(viewManagersList); <add> mCustomDirectEvents = <add> (Map<String, Object>) mModuleConstants.get( <add> UIManagerModuleConstantsHelper.CUSTOM_DIRECT_EVENTS_KEY); <add> mUIImplementation = <add> uiImplementationProvider.createUIImplementation( <add> reactContext, <add> viewManagersList, <add> mEventDispatcher, <add> minTimeLeftInFrameForNonBatchedOperationMs); <add> <add> reactContext.addLifecycleEventListener(this); <add> } <ide> /** <ide> * This method gives an access to the {@link UIImplementation} object that can be used to execute <ide> * operations on the view hierarchy. <ide> public void onCatalystInstanceDestroy() { <ide> ViewManagerPropertyUpdater.clear(); <ide> } <ide> <del> private static Map<String, Object> createConstants( <del> List<ViewManager> viewManagerList, <del> boolean lazyViewManagersEnabled) { <add> private static Map<String, Object> createConstants(ViewManagerResolver viewManagerResolver) { <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START); <ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants"); <ide> try { <del> return UIManagerModuleConstantsHelper.createConstants( <del> viewManagerList, <del> lazyViewManagersEnabled); <add> return UIManagerModuleConstantsHelper.createConstants(viewManagerResolver); <ide> } finally { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END); <ide> } <ide> } <ide> <add> private static Map<String, Object> createConstants(List<ViewManager> viewManagers) { <add> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants"); <add> try { <add> return UIManagerModuleConstantsHelper.createConstants(viewManagers); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END); <add> } <add> } <add> <add> @DoNotStrip <add> @ReactMethod(isBlockingSynchronousMethod = true) <add> public @Nullable WritableMap getConstantsForViewManager(final String viewManagerName) { <add> ViewManager targetView = <add> viewManagerName != null ? mUIImplementation.resolveViewManager(viewManagerName) : null; <add> if (targetView == null) { <add> return null; <add> } <add> <add> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "constants for ViewManager") <add> .arg("ViewManager", targetView.getName()) <add> .arg("Lazy", true) <add> .flush(); <add> try { <add> Map<String, Object> viewManagerConstants = <add> UIManagerModuleConstantsHelper.createConstantsForViewManager( <add> targetView, <add> UIManagerModuleConstants.getBubblingEventTypeConstants(), <add> UIManagerModuleConstants.getDirectEventTypeConstants(), <add> null, <add> mCustomDirectEvents); <add> return viewManagerConstants != null ? Arguments.makeNativeMap(viewManagerConstants) : null; <add> } finally { <add> SystraceMessage.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> } <add> <ide> /** <ide> * Resolves Direct Event name exposed to JS from the one known to the Native side. <ide> */ <ide> public CustomEventNamesResolver getDirectEventNamesResolver() { <ide> return new CustomEventNamesResolver() { <ide> @Override <ide> public @Nullable String resolveCustomEventName(String eventName) { <del> Map<String, Map> directEventTypes = <del> (Map<String, Map>) getConstants().get( <del> UIManagerModuleConstantsHelper.CUSTOM_DIRECT_EVENT_TYPES_KEY); <del> if (directEventTypes != null) { <del> Map<String, String> customEventType = (Map<String, String>) directEventTypes.get(eventName); <del> if (customEventType != null) { <del> return customEventType.get("registrationName"); <del> } <add> Map<String, String> customEventType = <add> (Map<String, String>) mCustomDirectEvents.get(eventName); <add> if (customEventType != null) { <add> return customEventType.get("registrationName"); <ide> } <ide> return eventName; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java <ide> <ide> package com.facebook.react.uimanager; <ide> <del>import java.util.List; <del>import java.util.Map; <add>import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; <ide> <ide> import com.facebook.react.common.MapBuilder; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <del> <del>import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; <add>import java.util.List; <add>import java.util.Map; <add>import javax.annotation.Nullable; <ide> <ide> /** <ide> * Helps generate constants map for {@link UIManagerModule} by collecting and merging constants from <ide> * registered view managers. <ide> */ <ide> /* package */ class UIManagerModuleConstantsHelper { <ide> <del> /* package */ static final String CUSTOM_BUBBLING_EVENT_TYPES_KEY = "customBubblingEventTypes"; <del> /* package */ static final String CUSTOM_DIRECT_EVENT_TYPES_KEY = "customDirectEventTypes"; <add> /* package */ static final String CUSTOM_BUBBLING_EVENTS_KEY = "customBubblingEventTypes"; <add> /* package */ static final String CUSTOM_DIRECT_EVENTS_KEY = "customDirectEventTypes"; <add> <add> /** <add> * Generates a lazy discovery enabled version of {@link UIManagerModule} constants. It only <add> * contains a list of view manager names, so that JS side is aware of the managers there are. <add> * Actual ViewManager instantiation happens when {@code UIManager.SpecificViewManager} call happens. <add> * The View Manager is then registered on the JS side with the help of <add> * {@code UIManagerModule.getConstantsForViewManager}. <add> */ <add> /* package */ static Map<String, Object> createConstants( <add> UIManagerModule.ViewManagerResolver resolver) { <add> Map<String, Object> constants = UIManagerModuleConstants.getConstants(); <add> constants.put("ViewManagerNames", resolver.getViewManagerNames()); <add> return constants; <add> } <ide> <ide> /** <ide> * Generates map of constants that is then exposed by {@link UIManagerModule}. <ide> * {@link UIManagerModuleConstants}. <ide> * TODO(6845124): Create a test for this <ide> */ <del> /* package */ static Map<String, Object> createConstants( <del> List<ViewManager> viewManagers, boolean lazyViewManagersEnabled) { <add> /* package */ static Map<String, Object> createConstants(List<ViewManager> viewManagers) { <ide> Map<String, Object> constants = UIManagerModuleConstants.getConstants(); <ide> <ide> // Generic/default event types: <ide> allDirectEventTypes.putAll(genericDirectEventTypes); <ide> <ide> for (ViewManager viewManager : viewManagers) { <add> final String viewManagerName = viewManager.getName(); <add> <ide> SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "constants for ViewManager") <del> .arg("ViewManager", viewManager.getName()) <del> .flush(); <del> try { <del> Map viewManagerConstants = MapBuilder.newHashMap(); <del> Map viewManagerBubblingEvents = viewManager.getExportedCustomBubblingEventTypeConstants(); <del> if (viewManagerBubblingEvents != null) { <del> recursiveMerge(allBubblingEventTypes, viewManagerBubblingEvents); <del> recursiveMerge(viewManagerBubblingEvents, genericBubblingEventTypes); <del> } else { <del> viewManagerBubblingEvents = genericBubblingEventTypes; <del> } <del> viewManagerConstants.put("bubblingEventTypes", viewManagerBubblingEvents); <del> <del> Map viewManagerDirectEvents = viewManager.getExportedCustomDirectEventTypeConstants(); <del> if (viewManagerDirectEvents != null) { <del> recursiveMerge(allDirectEventTypes, viewManagerDirectEvents); <del> recursiveMerge(viewManagerDirectEvents, genericDirectEventTypes); <del> } else { <del> viewManagerDirectEvents = genericDirectEventTypes; <del> } <del> viewManagerConstants.put("directEventTypes", viewManagerDirectEvents); <add> .arg("ViewManager", viewManagerName) <add> .arg("Lazy", false) <add> .flush(); <ide> <del> Map customViewConstants = viewManager.getExportedViewConstants(); <del> if (customViewConstants != null) { <del> viewManagerConstants.put("Constants", customViewConstants); <del> } <del> Map viewManagerCommands = viewManager.getCommandsMap(); <del> if (viewManagerCommands != null) { <del> viewManagerConstants.put("Commands", viewManagerCommands); <del> } <del> Map<String, String> viewManagerNativeProps = viewManager.getNativeProps(); <del> if (!viewManagerNativeProps.isEmpty()) { <del> viewManagerConstants.put("NativeProps", viewManagerNativeProps); <del> } <add> try { <add> Map viewManagerConstants = createConstantsForViewManager( <add> viewManager, <add> genericBubblingEventTypes, <add> genericDirectEventTypes, <add> allBubblingEventTypes, <add> allDirectEventTypes); <ide> if (!viewManagerConstants.isEmpty()) { <del> constants.put(viewManager.getName(), viewManagerConstants); <add> constants.put(viewManagerName, viewManagerConstants); <ide> } <ide> } finally { <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> <ide> // Used by https://fburl.com/6nskr82o <del> constants.put(CUSTOM_BUBBLING_EVENT_TYPES_KEY, allBubblingEventTypes); <del> constants.put(CUSTOM_DIRECT_EVENT_TYPES_KEY, allDirectEventTypes); <del> constants.put("AndroidLazyViewManagersEnabled", lazyViewManagersEnabled); <del> <add> constants.put(CUSTOM_BUBBLING_EVENTS_KEY, allBubblingEventTypes); <add> constants.put(CUSTOM_DIRECT_EVENTS_KEY, allDirectEventTypes); <ide> return constants; <ide> } <ide> <add> /* package */ static Map<String, Object> createConstantsForViewManager( <add> ViewManager viewManager, <add> Map defaultBubblingEvents, <add> Map defaultDirectEvents, <add> @Nullable Map cumulativeBubblingEventTypes, <add> @Nullable Map cumulativeDirectEventTypes) { <add> Map<String, Object> viewManagerConstants = MapBuilder.newHashMap(); <add> <add> Map viewManagerBubblingEvents = viewManager.getExportedCustomBubblingEventTypeConstants(); <add> if (viewManagerBubblingEvents != null) { <add> if (cumulativeBubblingEventTypes != null) { <add> recursiveMerge(cumulativeBubblingEventTypes, viewManagerBubblingEvents); <add> } <add> recursiveMerge(viewManagerBubblingEvents, defaultBubblingEvents); <add> } else { <add> viewManagerBubblingEvents = defaultBubblingEvents; <add> } <add> viewManagerConstants.put("bubblingEventTypes", viewManagerBubblingEvents); <add> <add> Map viewManagerDirectEvents = viewManager.getExportedCustomDirectEventTypeConstants(); <add> if (viewManagerDirectEvents != null) { <add> if (cumulativeDirectEventTypes != null) { <add> recursiveMerge(cumulativeDirectEventTypes, viewManagerBubblingEvents); <add> } <add> recursiveMerge(viewManagerDirectEvents, defaultDirectEvents); <add> } else { <add> viewManagerDirectEvents = defaultDirectEvents; <add> } <add> viewManagerConstants.put("directEventTypes", viewManagerDirectEvents); <add> <add> Map customViewConstants = viewManager.getExportedViewConstants(); <add> if (customViewConstants != null) { <add> viewManagerConstants.put("Constants", customViewConstants); <add> } <add> Map viewManagerCommands = viewManager.getCommandsMap(); <add> if (viewManagerCommands != null) { <add> viewManagerConstants.put("Commands", viewManagerCommands); <add> } <add> Map<String, String> viewManagerNativeProps = viewManager.getNativeProps(); <add> if (!viewManagerNativeProps.isEmpty()) { <add> viewManagerConstants.put("NativeProps", viewManagerNativeProps); <add> } <add> <add> return viewManagerConstants; <add> } <add> <ide> /** <ide> * Merges {@param source} map into {@param dest} map recursively <ide> */ <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerRegistry.java <ide> <ide> package com.facebook.react.uimanager; <ide> <del>import java.util.HashMap; <add>import com.facebook.react.common.MapBuilder; <ide> import java.util.List; <ide> import java.util.Map; <add>import javax.annotation.Nullable; <ide> <ide> /** <ide> * Class that stores the mapping between native view name used in JS and the corresponding instance <ide> * of {@link ViewManager}. <ide> */ <del>public class ViewManagerRegistry { <add>public final class ViewManagerRegistry { <ide> <ide> private final Map<String, ViewManager> mViewManagers; <add> private final @Nullable UIManagerModule.ViewManagerResolver mViewManagerResolver; <add> <add> public ViewManagerRegistry(UIManagerModule.ViewManagerResolver viewManagerResolver) { <add> mViewManagers = MapBuilder.newHashMap(); <add> mViewManagerResolver = viewManagerResolver; <add> } <ide> <ide> public ViewManagerRegistry(List<ViewManager> viewManagerList) { <del> mViewManagers = new HashMap<>(); <add> Map<String, ViewManager> viewManagerMap = MapBuilder.newHashMap(); <ide> for (ViewManager viewManager : viewManagerList) { <del> mViewManagers.put(viewManager.getName(), viewManager); <add> viewManagerMap.put(viewManager.getName(), viewManager); <ide> } <add> <add> mViewManagers = viewManagerMap; <add> mViewManagerResolver = null; <ide> } <ide> <ide> public ViewManagerRegistry(Map<String, ViewManager> viewManagerMap) { <del> mViewManagers = viewManagerMap; <add> mViewManagers = <add> viewManagerMap != null ? viewManagerMap : MapBuilder.<String, ViewManager>newHashMap(); <add> mViewManagerResolver = null; <ide> } <ide> <ide> public ViewManager get(String className) { <ide> ViewManager viewManager = mViewManagers.get(className); <ide> if (viewManager != null) { <ide> return viewManager; <del> } else { <del> throw new IllegalViewOperationException("No ViewManager defined for class " + className); <ide> } <add> if (mViewManagerResolver != null) { <add> viewManager = mViewManagerResolver.getViewManager(className); <add> if (viewManager != null) { <add> mViewManagers.put(className, viewManager); <add> return viewManager; <add> } <add> } <add> throw new IllegalViewOperationException("No ViewManager defined for class " + className); <ide> } <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java <ide> public void testNativePropsIncludeCorrectTypes() { <ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ViewManagerUnderTest()); <ide> ReactApplicationContext reactContext = new ReactApplicationContext(RuntimeEnvironment.application); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), 0); <ide> Map<String, String> constants = <ide> (Map) valueAtPath(uiManagerModule.getConstants(), "SomeView", "NativeProps"); <ide> assertThat(constants).isEqualTo( <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java <ide> public void setUp() { <ide> public void testNoCustomConstants() { <ide> List<ViewManager> viewManagers = Arrays.asList(mock(ViewManager.class)); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat(constants) <ide> .containsKey(CUSTOM_BUBBLING_EVENT_TYPES) <ide> public void testCustomBubblingEvents() { <ide> when(mockViewManager.getExportedCustomBubblingEventTypeConstants()) <ide> .thenReturn(MapBuilder.of("onTwirl", TWIRL_BUBBLING_EVENT_MAP)); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat((Map) constants.get(CUSTOM_BUBBLING_EVENT_TYPES)) <ide> .contains(MapEntry.entry("onTwirl", TWIRL_BUBBLING_EVENT_MAP)) <ide> public void testCustomDirectEvents() { <ide> when(mockViewManager.getExportedCustomDirectEventTypeConstants()) <ide> .thenReturn(MapBuilder.of("onTwirl", TWIRL_DIRECT_EVENT_MAP)); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)) <ide> .contains(MapEntry.entry("onTwirl", TWIRL_DIRECT_EVENT_MAP)) <ide> public void testCustomViewConstants() { <ide> when(mockViewManager.getExportedViewConstants()) <ide> .thenReturn(MapBuilder.of("PhotoSizeType", MapBuilder.of("Small", 1, "Large", 2))); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat(constants).containsKey("RedPandaPhotoOfTheDayView"); <ide> assertThat((Map) constants.get("RedPandaPhotoOfTheDayView")).containsKey("Constants"); <ide> public void testNativeProps() { <ide> when(mockViewManager.getNativeProps()) <ide> .thenReturn(MapBuilder.of("fooProp", "number")); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat((String) valueAtPath(constants, "SomeView", "NativeProps", "fooProp")) <ide> .isEqualTo("number"); <ide> public void testMergeConstants() { <ide> <ide> List<ViewManager> viewManagers = Arrays.asList(managerX, managerY); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, false, 0); <add> new UIManagerModule(mReactContext, viewManagers, mUIImplementationProvider, 0); <ide> Map<String, Object> constants = uiManagerModule.getConstants(); <ide> assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)).containsKey("onTwirl"); <ide> <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java <ide> private UIManagerModule getUIManagerModule() { <ide> new ReactTextViewManager(), <ide> new ReactRawTextManager()); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(mReactContext, viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(mReactContext, viewManagers, new UIImplementationProvider(), 0); <ide> uiManagerModule.onHostResume(); <ide> return uiManagerModule; <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java <ide> public UIManagerModule getUIManagerModule() { <ide> new ReactRawTextManager(), <ide> }); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), 0); <ide> uiManagerModule.onHostResume(); <ide> return uiManagerModule; <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java <ide> public UIManagerModule getUIManagerModule() { <ide> new ReactTextInputManager(), <ide> }); <ide> UIManagerModule uiManagerModule = <del> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), false, 0); <add> new UIManagerModule(reactContext, viewManagers, new UIImplementationProvider(), 0); <ide> uiManagerModule.onHostResume(); <ide> return uiManagerModule; <ide> }
24
Java
Java
change spel equality operators to use .equals
2a05e6afa116ab56378521b5e8c834ba92c25b85
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpEQ.java <ide> */ <ide> public class OpEQ extends Operator { <ide> <add> <ide> public OpEQ(int pos, SpelNodeImpl... operands) { <ide> super("==", pos, operands); <ide> } <ide> public BooleanTypedValue getValueInternal(ExpressionState state) <ide> throws EvaluationException { <ide> Object left = getLeftOperand().getValueInternal(state).getValue(); <ide> Object right = getRightOperand().getValueInternal(state).getValue(); <del> if (left instanceof Number && right instanceof Number) { <del> Number op1 = (Number) left; <del> Number op2 = (Number) right; <del> if (op1 instanceof Double || op2 instanceof Double) { <del> return BooleanTypedValue.forValue(op1.doubleValue() == op2.doubleValue()); <del> } <del> else if (op1 instanceof Float || op2 instanceof Float) { <del> return BooleanTypedValue.forValue(op1.floatValue() == op2.floatValue()); <del> } <del> else if (op1 instanceof Long || op2 instanceof Long) { <del> return BooleanTypedValue.forValue(op1.longValue() == op2.longValue()); <del> } <del> else { <del> return BooleanTypedValue.forValue(op1.intValue() == op2.intValue()); <del> } <del> } <del> if (left != null && (left instanceof Comparable)) { <del> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, <del> right) == 0); <del> } <del> else { <del> return BooleanTypedValue.forValue(left == right); <del> } <add> return BooleanTypedValue.forValue(equalityCheck(state, left, right)); <ide> } <ide> <ide> } <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpGT.java <ide> */ <ide> public class OpGT extends Operator { <ide> <add> <ide> public OpGT(int pos, SpelNodeImpl... operands) { <ide> super(">", pos, operands); <ide> } <ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati <ide> if (leftNumber instanceof Double || rightNumber instanceof Double) { <ide> return BooleanTypedValue.forValue(leftNumber.doubleValue() > rightNumber.doubleValue()); <ide> } <add> else if (leftNumber instanceof Float || rightNumber instanceof Float) { <add> return BooleanTypedValue.forValue(leftNumber.floatValue() > rightNumber.floatValue()); <add> } <ide> else if (leftNumber instanceof Long || rightNumber instanceof Long) { <ide> return BooleanTypedValue.forValue(leftNumber.longValue() > rightNumber.longValue()); <ide> } <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java <ide> */ <ide> public class OpLT extends Operator { <ide> <add> <ide> public OpLT(int pos, SpelNodeImpl... operands) { <ide> super("<", pos, operands); <ide> } <ide> public BooleanTypedValue getValueInternal(ExpressionState state) <ide> throws EvaluationException { <ide> Object left = getLeftOperand().getValueInternal(state).getValue(); <ide> Object right = getRightOperand().getValueInternal(state).getValue(); <del> // TODO could leave all of these to the comparator - just seems quicker to do some here <add> <ide> if (left instanceof Number && right instanceof Number) { <ide> Number leftNumber = (Number) left; <ide> Number rightNumber = (Number) right; <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpNE.java <ide> */ <ide> public class OpNE extends Operator { <ide> <add> <ide> public OpNE(int pos, SpelNodeImpl... operands) { <ide> super("!=", pos, operands); <ide> } <ide> <ide> <ide> @Override <ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException { <del> <ide> Object left = getLeftOperand().getValueInternal(state).getValue(); <ide> Object right = getRightOperand().getValueInternal(state).getValue(); <del> <del> if (left instanceof Number && right instanceof Number) { <del> Number op1 = (Number) left; <del> Number op2 = (Number) right; <del> <del> if (op1 instanceof Double || op2 instanceof Double) { <del> return BooleanTypedValue.forValue(op1.doubleValue() != op2.doubleValue()); <del> } <del> <del> if (op1 instanceof Float || op2 instanceof Float) { <del> return BooleanTypedValue.forValue(op1.floatValue() != op2.floatValue()); <del> } <del> <del> if (op1 instanceof Long || op2 instanceof Long) { <del> return BooleanTypedValue.forValue(op1.longValue() != op2.longValue()); <del> } <del> <del> return BooleanTypedValue.forValue(op1.intValue() != op2.intValue()); <del> } <del> <del> if (left != null && (left instanceof Comparable)) { <del> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, <del> right) != 0); <del> } <del> <del> return BooleanTypedValue.forValue(left != right); <add> return BooleanTypedValue.forValue(!equalityCheck(state, left, right)); <ide> } <ide> <ide> } <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java <ide> <ide> package org.springframework.expression.spel.ast; <ide> <add>import org.springframework.expression.spel.ExpressionState; <add> <ide> /** <ide> * Common supertype for operators that operate on either one or two operands. In the case <ide> * of multiply or divide there would be two operands, but for unary plus or minus, there <ide> */ <ide> public abstract class Operator extends SpelNodeImpl { <ide> <del> String operatorName; <add> private final String operatorName; <ide> <ide> <ide> public Operator(String payload,int pos,SpelNodeImpl... operands) { <ide> public String toStringAST() { <ide> return sb.toString(); <ide> } <ide> <add> protected boolean equalityCheck(ExpressionState state, Object left, Object right) { <add> if (left instanceof Number && right instanceof Number) { <add> Number op1 = (Number) left; <add> Number op2 = (Number) right; <add> <add> if (op1 instanceof Double || op2 instanceof Double) { <add> return (op1.doubleValue() == op2.doubleValue()); <add> } <add> <add> if (op1 instanceof Float || op2 instanceof Float) { <add> return (op1.floatValue() == op2.floatValue()); <add> } <add> <add> if (op1 instanceof Long || op2 instanceof Long) { <add> return (op1.longValue() == op2.longValue()); <add> } <add> <add> return (op1.intValue() == op2.intValue()); <add> } <add> <add> if (left != null && (left instanceof Comparable)) { <add> return (state.getTypeComparator().compare(left, right) == 0); <add> } <add> <add> return (left == null ? right == null : left.equals(right)); <add> } <add> <ide> } <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java <ide> public void SPR_10486() throws Exception { <ide> equalTo((Object) "name")); <ide> } <ide> <add> @Test <add> public void testOperatorEq_SPR9194() { <add> TestClass2 one = new TestClass2("abc"); <add> TestClass2 two = new TestClass2("abc"); <add> Map<String,TestClass2> map = new HashMap<String,TestClass2>(); <add> map.put("one",one); <add> map.put("two",two); <add> <add> SpelExpressionParser parser = new SpelExpressionParser(); <add> Expression classNameExpression = parser.parseExpression("['one'] == ['two']"); <add> assertTrue(classNameExpression.getValue(map,Boolean.class)); <add> } <add> <ide> <ide> private static enum ABC {A, B, C} <ide> <ide> public void setName(String name) { <ide> } <ide> <ide> } <add> <add> static class TestClass2 { // SPR-9194 <add> String string; <add> <add> public TestClass2(String string) { <add> this.string = string; <add> } <add> <add> public boolean equals(Object o) { <add> if (o instanceof TestClass2) { <add> return string.equals(((TestClass2)o).string); <add> } <add> return false; <add> } <add> <add> } <ide> }
6
Text
Text
fix heading level of logging drivers
f855d5dde70f1f3e4390e53576a3ca9b5a9db8ba
<ide><path>docs/sources/reference/run.md <ide> familiar with using LXC directly. <ide> <ide> You can specify a different logging driver for the container than for the daemon. <ide> <del>### Logging driver: none <add>#### Logging driver: none <ide> <ide> Disables any logging for the container. `docker logs` won't be available with <ide> this driver. <ide> <del>### Log driver: json-file <add>#### Logging driver: json-file <ide> <ide> Default logging driver for Docker. Writes JSON messages to file. `docker logs` <ide> command is available only for this logging driver <ide> <del>## Logging driver: syslog <add>#### Logging driver: syslog <ide> <ide> Syslog logging driver for Docker. Writes log messages to syslog. `docker logs` <ide> command is not available for this logging driver
1
Text
Text
add fanduel to the list of users in the wild.
6788428a8636e7ab15e556f8e48bcd82a1a5470e
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Etsy](https://www.etsy.com) [[@mchalek](https://github.com/mchalek)] <ide> 1. [Everlane](https://everlane.com) [[@NickBenthem](https://github.com/NickBenthem)] <ide> 1. [Experity (formerly DocuTAP)](https://www.experityhealth.com/) [[@cloneluke](https://github.com/cloneluke) & [@tobyjoliver](https://github.com/tobyjoliver)] <add>1. [FanDuel](https://www.fanduel.com/) <ide> 1. [Fathom Health](https://www.fathomhealth.co/) <ide> 1. [Firestone Inventing](https://www.hsmap.com/) [[@zihengCat](https://github.com/zihengCat)] <ide> 1. [Flipp](https://www.flipp.com) [[@sethwilsonwishabi](https://github.com/sethwilsonwishabi)]
1
Python
Python
fix non-float32 efficientnet calls
68fef62d2788cea69f75101447af2bcb3405186c
<ide><path>keras/applications/efficientnet.py <ide> def round_repeats(repeats): <ide> # normalize the input, we need to divide another sqrt(var) to match the <ide> # original implementation. <ide> # See https://github.com/tensorflow/tensorflow/issues/49930 for more details <del> x = x / tf.math.sqrt(IMAGENET_STDDEV_RGB) <add> x = layers.Rescaling(1. / tf.math.sqrt(IMAGENET_STDDEV_RGB))(x) <ide> <ide> x = layers.ZeroPadding2D( <ide> padding=imagenet_utils.correct_pad(x, 3),
1
PHP
PHP
add supported type
28908d83d9f3b078ae01ed21a42b87edf1fd393d
<ide><path>config/hashing.php <ide> | passwords for your application. By default, the bcrypt algorithm is <ide> | used; however, you remain free to modify this option if you wish. <ide> | <del> | Supported: "bcrypt", "argon" <add> | Supported: "bcrypt", "argon", "argon2id" <ide> | <ide> */ <ide>
1
Python
Python
rephrase the start_from_epoch arg documantation
d568b3071d5a1475596fb2f9eafd6f08a8937371
<ide><path>keras/callbacks.py <ide> class EarlyStopping(Callback): <ide> of the performance relative to the `baseline`. If no epoch <ide> improves on `baseline`, training will run for `patience` <ide> epochs and restore weights from the best epoch in that set. <del> start_from_epoch: Number of initial epochs to wait before starting <add> start_from_epoch: Number of epochs to wait before starting <ide> to monitor improvement. This allows a warm-up period in which <ide> no improvement is expected and thus training will not be stopped. <ide>
1
Ruby
Ruby
fix rails dbconsole for jdbcmysql adapter
dac5399af04c84c6021ee2bc169a3d17944a5fa2
<ide><path>railties/lib/rails/commands/dbconsole.rb <ide> def start <ide> ENV['RAILS_ENV'] = options[:environment] || environment <ide> <ide> case config["adapter"] <del> when /^mysql/ <add> when /^(jdbc)?mysql/ <ide> args = { <ide> 'host' => '--host', <ide> 'port' => '--port',
1
Python
Python
fix documentation for request._authenticate
fe95ab675bef1b185324be4b1b7fc7100c41c823
<ide><path>rest_framework/request.py <ide> def _authenticate(self): <ide> """ <ide> Attempt to authenticate the request using each authentication instance <ide> in turn. <del> Returns a three-tuple of (authenticator, user, authtoken). <ide> """ <ide> for authenticator in self.authenticators: <ide> try:
1
Python
Python
improve code quality #820
89d3cb09d883e552a894ebfcd7a66758ce042d74
<ide><path>glances/compat.py <ide> def is_admin(): <ide> else: <ide> # Check for root on Posix <ide> return os.getuid() == 0 <add> <add> <add>def key_exist_value_not_none(k, d): <add> # Return True if: <add> # - key k exists <add> # - d[k] is not None <add> return k in d and d[k] is not None <add> <add> <add>def key_exist_value_not_none_not_v(k, d, v=''): <add> # Return True if: <add> # - key k exists <add> # - d[k] is not None <add> # - d[k] != v <add> return k in d and d[k] is not None and d[k] != v <ide><path>glances/plugins/glances_processlist.py <ide> # <ide> # This file is part of Glances. <ide> # <del># Copyright (C) 2019 Nicolargo <nicolas@nicolargo.com> <add># Copyright (C) 2021 Nicolargo <nicolas@nicolargo.com> <ide> # <ide> # Glances is free software; you can redistribute it and/or modify <ide> # it under the terms of the GNU Lesser General Public License as published by <ide> <ide> from glances.logger import logger <ide> from glances.globals import WINDOWS <add>from glances.compat import key_exist_value_not_none_not_v <ide> from glances.processes import glances_processes, sort_stats <ide> from glances.plugins.glances_core import Plugin as CorePlugin <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> def get_nice_alert(self, value): <ide> pass <ide> return 'DEFAULT' <ide> <del> def get_process_curses_data(self, p, selected, args): <del> """Get curses data to display for a process. <del> <del> - p is the process to display <del> - selected is a tag=True if the selected process <del> """ <del> ret = [self.curse_new_line()] <del> # When a process is selected: <del> # * display a special caracter at the beginning of the line <del> # * underline the command name <del> if args.is_standalone: <del> ret.append(self.curse_add_line('>' if selected else ' ', 'SELECTED')) <del> # CPU <del> if 'cpu_percent' in p and p['cpu_percent'] is not None and p['cpu_percent'] != '': <add> def _get_process_curses_cpu(self, p, selected, args): <add> """Return process CPU curses""" <add> ret = '' <add> if key_exist_value_not_none_not_v('cpu_percent', p, ''): <ide> cpu_layout = self.layout_stat['cpu'] if p['cpu_percent'] < 100 else self.layout_stat['cpu_no_digit'] <ide> if args.disable_irix and self.nb_log_core != 0: <ide> msg = cpu_layout.format( <ide> def get_process_curses_data(self, p, selected, args): <ide> msg = cpu_layout.format(p['cpu_percent']) <ide> alert = self.get_alert(p['cpu_percent'], <ide> highlight_zero=False, <del> is_max=(p['cpu_percent'] == self.max_values['cpu_percent']), <add> is_max=(p['cpu_percent'] == <add> self.max_values['cpu_percent']), <ide> header="cpu") <del> ret.append(self.curse_add_line(msg, alert)) <add> ret = self.curse_add_line(msg, alert) <ide> else: <ide> msg = self.layout_header['cpu'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # MEM <del> if 'memory_percent' in p and p['memory_percent'] is not None and p['memory_percent'] != '': <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_mem(self, p, selected, args): <add> """Return process MEM curses""" <add> ret = '' <add> if key_exist_value_not_none_not_v('memory_percent', p, ''): <ide> msg = self.layout_stat['mem'].format(p['memory_percent']) <ide> alert = self.get_alert(p['memory_percent'], <ide> highlight_zero=False, <del> is_max=(p['memory_percent'] == self.max_values['memory_percent']), <add> is_max=(p['memory_percent'] == <add> self.max_values['memory_percent']), <ide> header="mem") <del> ret.append(self.curse_add_line(msg, alert)) <add> ret = self.curse_add_line(msg, alert) <ide> else: <ide> msg = self.layout_header['mem'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # VMS/RSS <del> if 'memory_info' in p and p['memory_info'] is not None and p['memory_info'] != '': <del> # VMS <del> msg = self.layout_stat['virt'].format(self.auto_unit(p['memory_info'][1], low_precision=False)) <del> ret.append(self.curse_add_line(msg, optional=True)) <del> # RSS <del> msg = self.layout_stat['res'].format(self.auto_unit(p['memory_info'][0], low_precision=False)) <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_vms(self, p, selected, args): <add> """Return process VMS curses""" <add> ret = '' <add> if key_exist_value_not_none_not_v('memory_info', p, ''): <add> msg = self.layout_stat['virt'].format( <add> self.auto_unit(p['memory_info'][1], low_precision=False)) <add> ret = self.curse_add_line(msg, optional=True) <ide> else: <ide> msg = self.layout_header['virt'].format('?') <del> ret.append(self.curse_add_line(msg)) <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_rss(self, p, selected, args): <add> """Return process RSS curses""" <add> ret = '' <add> if key_exist_value_not_none_not_v('memory_info', p, ''): <add> msg = self.layout_stat['res'].format( <add> self.auto_unit(p['memory_info'][0], low_precision=False)) <add> ret = self.curse_add_line(msg, optional=True) <add> else: <ide> msg = self.layout_header['res'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # PID <del> msg = self.layout_stat['pid'].format(p['pid'], width=self.__max_pid_size()) <del> ret.append(self.curse_add_line(msg)) <del> # USER <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_username(self, p, selected, args): <add> """Return process username curses""" <add> ret = '' <ide> if 'username' in p: <ide> # docker internal users are displayed as ints only, therefore str() <ide> # Correct issue #886 on Windows OS <ide> msg = self.layout_stat['user'].format(str(p['username'])[:9]) <del> ret.append(self.curse_add_line(msg)) <add> ret = self.curse_add_line(msg) <ide> else: <ide> msg = self.layout_header['user'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # TIME+ <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_time(self, p, selected, args): <add> """Return process time curses""" <add> ret = '' <ide> try: <ide> # Sum user and system time <ide> user_system_time = p['cpu_times'][0] + p['cpu_times'][1] <ide> def get_process_curses_data(self, p, selected, args): <ide> # See: https://github.com/nicolargo/glances/issues/622 <ide> # logger.debug("Cannot get TIME+ ({})".format(e)) <ide> msg = self.layout_header['time'].format('?') <del> ret.append(self.curse_add_line(msg, optional=True)) <add> ret = self.curse_add_line(msg, optional=True) <ide> else: <ide> hours, minutes, seconds = seconds_to_hms(user_system_time) <ide> if hours > 99: <ide> def get_process_curses_data(self, p, selected, args): <ide> msg = '{}:{}'.format(minutes, seconds) <ide> msg = self.layout_stat['time'].format(msg) <ide> if hours > 0: <del> ret.append(self.curse_add_line(msg, <del> decoration='CPU_TIME', <del> optional=True)) <add> ret = self.curse_add_line(msg, <add> decoration='CPU_TIME', <add> optional=True) <ide> else: <del> ret.append(self.curse_add_line(msg, optional=True)) <del> # THREAD <add> ret = self.curse_add_line(msg, optional=True) <add> return ret <add> <add> def _get_process_curses_thread(self, p, selected, args): <add> """Return process thread curses""" <add> ret = '' <ide> if 'num_threads' in p: <ide> num_threads = p['num_threads'] <ide> if num_threads is None: <ide> num_threads = '?' <ide> msg = self.layout_stat['thread'].format(num_threads) <del> ret.append(self.curse_add_line(msg)) <add> ret = self.curse_add_line(msg) <ide> else: <ide> msg = self.layout_header['thread'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # NICE <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_nice(self, p, selected, args): <add> """Return process nice curses""" <add> ret = '' <ide> if 'nice' in p: <ide> nice = p['nice'] <ide> if nice is None: <ide> nice = '?' <ide> msg = self.layout_stat['nice'].format(nice) <del> ret.append(self.curse_add_line(msg, <del> decoration=self.get_nice_alert(nice))) <add> ret = self.curse_add_line(msg, <add> decoration=self.get_nice_alert(nice)) <ide> else: <ide> msg = self.layout_header['nice'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # STATUS <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_status(self, p, selected, args): <add> """Return process status curses""" <add> ret = '' <ide> if 'status' in p: <ide> status = p['status'] <ide> msg = self.layout_stat['status'].format(status) <ide> if status == 'R': <del> ret.append(self.curse_add_line(msg, decoration='STATUS')) <add> ret = self.curse_add_line(msg, decoration='STATUS') <ide> else: <del> ret.append(self.curse_add_line(msg)) <add> ret = self.curse_add_line(msg) <ide> else: <ide> msg = self.layout_header['status'].format('?') <del> ret.append(self.curse_add_line(msg)) <del> # IO read/write <del> if 'io_counters' in p and p['io_counters'][4] == 1 and p['time_since_update'] != 0: <add> ret = self.curse_add_line(msg) <add> return ret <add> <add> def _get_process_curses_io_read(self, p, selected, args): <add> """Return process IO Read curses""" <add> ret = '' <add> if 'io_counters' in p and \ <add> p['io_counters'][4] == 1 and \ <add> p['time_since_update'] != 0: <ide> # Display rate if stats is available and io_tag ([4]) == 1 <ide> # IO read <del> io_rs = int((p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update']) <add> io_rs = int((p['io_counters'][0] - p['io_counters'] <add> [2]) / p['time_since_update']) <ide> if io_rs == 0: <ide> msg = self.layout_stat['ior'].format("0") <ide> else: <del> msg = self.layout_stat['ior'].format(self.auto_unit(io_rs, <del> low_precision=True)) <del> ret.append(self.curse_add_line(msg, optional=True, additional=True)) <del> # IO write <del> io_ws = int((p['io_counters'][1] - p['io_counters'][3]) / p['time_since_update']) <add> msg = self.layout_stat['ior'].format( <add> self.auto_unit(io_rs, <add> low_precision=True)) <add> ret = self.curse_add_line(msg, optional=True, additional=True) <add> else: <add> msg = self.layout_header['ior'].format("?") <add> ret = self.curse_add_line(msg, optional=True, additional=True) <add> return ret <add> <add> def _get_process_curses_io_write(self, p, selected, args): <add> """Return process IO Write curses""" <add> ret = '' <add> if 'io_counters' in p and \ <add> p['io_counters'][4] == 1 and \ <add> p['time_since_update'] != 0: <add> # Display rate if stats is available and io_tag ([4]) == 1 <add> # IO read <add> io_ws = int((p['io_counters'][0] - p['io_counters'] <add> [2]) / p['time_since_update']) <ide> if io_ws == 0: <ide> msg = self.layout_stat['iow'].format("0") <ide> else: <del> msg = self.layout_stat['iow'].format(self.auto_unit(io_ws, <del> low_precision=True)) <del> ret.append(self.curse_add_line(msg, optional=True, additional=True)) <add> msg = self.layout_stat['iow'].format( <add> self.auto_unit(io_ws, <add> low_precision=True)) <add> ret = self.curse_add_line(msg, optional=True, additional=True) <ide> else: <del> msg = self.layout_header['ior'].format("?") <del> ret.append(self.curse_add_line(msg, optional=True, additional=True)) <ide> msg = self.layout_header['iow'].format("?") <del> ret.append(self.curse_add_line(msg, optional=True, additional=True)) <add> ret = self.curse_add_line(msg, optional=True, additional=True) <add> return ret <add> <add> def get_process_curses_data(self, p, selected, args): <add> """Get curses data to display for a process. <add> <add> - p is the process to display <add> - selected is a tag=True if the selected process <add> """ <add> ret = [self.curse_new_line()] <add> # When a process is selected: <add> # * display a special caracter at the beginning of the line <add> # * underline the command name <add> if args.is_standalone: <add> ret.append(self.curse_add_line('>' if selected else ' ', 'SELECTED')) <add> <add> # CPU <add> ret.append(self._get_process_curses_cpu(p, selected, args)) <add> <add> # MEM <add> ret.append(self._get_process_curses_mem(p, selected, args)) <add> ret.append(self._get_process_curses_vms(p, selected, args)) <add> ret.append(self._get_process_curses_rss(p, selected, args)) <add> <add> # PID <add> msg = self.layout_stat['pid'].format(p['pid'], width=self.__max_pid_size()) <add> ret.append(self.curse_add_line(msg)) <add> <add> # USER <add> ret.append(self._get_process_curses_username(p, selected, args)) <add> <add> # TIME+ <add> ret.append(self._get_process_curses_time(p, selected, args)) <add> <add> # THREAD <add> ret.append(self._get_process_curses_thread(p, selected, args)) <add> <add> # NICE <add> ret.append(self._get_process_curses_nice(p, selected, args)) <add> <add> # STATUS <add> ret.append(self._get_process_curses_status(p, selected, args)) <add> <add> # IO read/write <add> ret.append(self._get_process_curses_io_read(p, selected, args)) <add> ret.append(self._get_process_curses_io_write(p, selected, args)) <ide> <ide> # Command line <ide> # If no command line for the process is available, fallback to <ide> def msg_curse(self, args=None, max_width=None): <ide> ret.extend(self.get_process_curses_data( <ide> p, i == args.cursor_position, args)) <ide> i += 1 <del> <add> <ide> # A filter is set Display the stats summaries <ide> if glances_processes.process_filter is not None: <ide> if args.reset_minmax_tag:
2
Ruby
Ruby
move misplaced test
df2d96a7f05aebca3e9d2367c2a248125b24dca6
<add><path>actionmailer/test/adv_attr_test.rb <del><path>actionpack/test/adv_attr_test.rb <del>require File.dirname(__FILE__) + '/abstract_unit' <add>require 'abstract_unit' <ide> require 'action_mailer/adv_attr_accessor' <ide> <ide> class AdvAttrTest < Test::Unit::TestCase <ide> def test_adv_attr <ide> <ide> assert_raise(ArgumentError) {bob.name 'x', 'y'} <ide> end <del> <del> <del>end <ide>\ No newline at end of file <add>end
1
Ruby
Ruby
add title for key lengths for multiple keys
5df94c6ffd82a7d42f36e36892281a4b28ce2ebc
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def rename_column(table_name, column_name, new_column_name) <ide> # <ide> # CREATE INDEX by_name ON accounts(name(10)) <ide> # <add> # ====== Creating an index with specific key lengths for multiple keys <add> # <ide> # add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15}) <ide> # <ide> # generates:
1
Mixed
Python
update example for compatibility
2e81b9d8d76a4d41a13f74eb5e0f4a65d8143cab
<ide><path>examples/summarization/bart/README.md <del>### Get the CNN/Daily Mail Data <add>### Get the CNN Data <ide> To be able to reproduce the authors' results on the CNN/Daily Mail dataset you first need to download both CNN and Daily Mail datasets [from Kyunghyun Cho's website](https://cs.nyu.edu/~kcho/DMQA/) (the links next to "Stories") in the same folder. Then uncompress the archives by running: <ide> <ide> ```bash <ide> unzip stanford-corenlp-full-2018-10-05.zip <ide> cd stanford-corenlp-full-2018-10-05 <ide> export CLASSPATH=stanford-corenlp-3.9.2.jar:stanford-corenlp-3.9.2-models.jar <ide> ``` <add>Then run `ptb_tokenize` on `test.target` and your generated hypotheses. <ide> ### Rouge Setup <ide> Install `files2rouge` following the instructions at [here](https://github.com/pltrdy/files2rouge). <ide> I also needed to run `sudo apt-get install libxml-parser-perl` <ide><path>examples/summarization/bart/evaluate_cnn.py <ide> def generate_summaries(lns, out_file, batch_size=8, device=DEFAULT_DEVICE): <ide> attention_mask=dct["attention_mask"].to(device), <ide> num_beams=4, <ide> length_penalty=2.0, <del> max_length=140, <del> min_length=55, <add> max_length=142, # +2 from original because we start at step=1 and stop before max_length <add> min_length=56, # +1 from original because we start at step=1 <ide> no_repeat_ngram_size=3, <add> early_stopping=True, <add> do_sample=False, <ide> ) <ide> dec = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summaries] <ide> for hypothesis in dec: <ide><path>src/transformers/modeling_bart.py <ide> Initializing with a config file does not load the weights associated with the model, only the configuration. <ide> Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. <ide> <add>""" <add>BART_GENERATION_EXAMPLE = r""" <add> Examples:: <add> <add> from transformers import BartTokenizer, BartForConditionalGeneration, BartConfig <add> # see ``examples/summarization/bart/evaluate_cnn.py`` for a longer example <add> model = BartForConditionalGeneration.from_pretrained('bart-large-cnn') <add> tokenizer = BartTokenizer.from_pretrained('bart-large-cnn') <add> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs." <add> inputs = tokenizer.batch_encode_plus([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='pt') <add> # Generate Summary <add> summary_ids = model.generate(inputs['input_ids'], attention_mask=inputs['attention_mask'], num_beams=4, max_length=5) <add> print([tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summary_ids]) <add> <ide> """ <ide> <ide> BART_INPUTS_DOCSTRING = r""" <ide> def get_output_embeddings(self): <ide> <ide> <ide> @add_start_docstrings( <del> "The BART Model with a language modeling head. Can be used for summarization.", BART_START_DOCSTRING, <add> "The BART Model with a language modeling head. Can be used for summarization.", <add> BART_START_DOCSTRING + BART_GENERATION_EXAMPLE, <ide> ) <ide> class BartForConditionalGeneration(PretrainedBartModel): <ide> base_model_prefix = "model"
3
Javascript
Javascript
use object assignation for getstate()
35f68af6e7e92bfb8b082fe3ec645e1c52842be5
<ide><path>examples/shopping-cart/src/actions/index.js <ide> export const addToCart = productId => (dispatch, getState) => { <ide> } <ide> } <ide> <del>export const checkout = (products) => (dispatch, getState) => { <del> const cart = getState().cart <add>export const checkout = products => (dispatch, getState) => { <add> const { cart } = getState() <ide> <ide> dispatch({ <ide> type: types.CHECKOUT_REQUEST
1
Text
Text
fix documentation for release-checklist
586e72218ceeb90d31900af198d5c865e4b3e6e4
<ide><path>hack/RELEASE-CHECKLIST.md <ide> If you don't have an upstream remote, you can add one easily using something <ide> like: <ide> <ide> ```bash <add>export GITHUBUSER="YOUR_GITHUB_USER" <ide> git remote add origin https://github.com/dotcloud/docker.git <del>git remote add YOURUSER git@github.com:YOURUSER/docker.git <add>git remote add $GITHUBUSER git@github.com:$GITHUBUSER/docker.git <ide> ``` <ide> <ide> ### 1. Pull from master and create a release branch <ide> <add>Note: Even for major releases, all of X, Y and Z in vX.Y.Z must be specified (e.g. v1.0.0). <add> <ide> ```bash <ide> export VERSION=vX.Y.Z <del>git checkout release <del>git fetch <del>git reset --hard origin/release <add>git fetch origin <add>git branch -D release || true <add>git checkout --track origin/release <ide> git checkout -b bump_$VERSION <ide> git merge origin/master <ide> ``` <ide> <ide> ### 2. Update CHANGELOG.md <ide> <del>You can run this command for reference: <add>You can run this command for reference with git 2.0: <add> <add>```bash <add>git fetch --tags <add>LAST_VERSION=$(git tag -l --sort=-version:refname "v*" | grep -E 'v[0-9\.]+$' | head -1) <add>git log --stat $LAST_VERSION..bump_$VERSION <add>``` <ide> <add>If you don't have git 2.0 but have a sort command that supports `-V`: <ide> ```bash <del>LAST_VERSION=$(git tag | grep -E 'v[0-9\.]+$' | sort -nr | head -n 1) <del>git log --stat $LAST_VERSION..HEAD <add>git fetch --tags <add>LAST_VERSION=$(git tag -l | grep -E 'v[0-9\.]+$' | sort -rV | head -1) <add>git log --stat $LAST_VERSION..bump_$VERSION <ide> ``` <ide> <add>If releasing a major version (X or Y increased in vX.Y.Z), simply listing notable user-facing features is sufficient. <add>```markdown <add>#### Notable features since <last major version> <add>* New docker command to do something useful <add>* Remote API change (deprecating old version) <add>* Performance improvements in some usecases <add>* ... <add>``` <add> <add>For minor releases (only Z increases in vX.Y.Z), provide a list of user-facing changes. <ide> Each change should be listed under a category heading formatted as `#### CATEGORY`. <ide> <ide> `CATEGORY` should describe which part of the project is affected. <ide> a count, add a simple `| wc -l`. <ide> echo ${VERSION#v} > VERSION <ide> ``` <ide> <del>### 4. Run all tests <del> <del>```bash <del>make test <del>``` <del> <del>### 5. Test the docs <add>### 4. Test the docs <ide> <ide> Make sure that your tree includes documentation for any modified or <ide> new features, syntax or semantic changes. <ide> To make a shared test at http://beta-docs.docker.io: <ide> make AWS_S3_BUCKET=beta-docs.docker.io docs-release <ide> ``` <ide> <del>### 6. Commit and create a pull request to the "release" branch <add>### 5. Commit and create a pull request to the "release" branch <ide> <ide> ```bash <add>export GITHUBUSER="YOUR_GITHUB_USER" <ide> git add VERSION CHANGELOG.md <ide> git commit -m "Bump version to $VERSION" <del>git push origin bump_$VERSION <del>echo "https://github.com/dotcloud/docker/compare/release...bump_$VERSION" <add>git push $GITHUBUSER bump_$VERSION <add>echo "https://github.com/$GITHUBUSER/docker/compare/dotcloud:master...$GITHUBUSER:bump_$VERSION?expand=1" <ide> ``` <ide> <ide> That last command will give you the proper link to visit to ensure that you <ide> open the PR against the "release" branch instead of accidentally against <ide> "master" (like so many brave souls before you already have). <ide> <del>### 7. Get 2 other maintainers to validate the pull request <add>### 6. Get 2 other maintainers to validate the pull request <ide> <del>### 8. Publish binaries <add>### 7. Publish binaries <ide> <del>To run this you will need access to the release credentials. <del>Get them from [the infrastructure maintainers]( <del>https://github.com/dotcloud/docker/blob/master/hack/infrastructure/MAINTAINERS). <add>To run this you will need access to the release credentials. Get them from the Core maintainers. <add> <add>Replace "..." with the respective credentials: <ide> <ide> ```bash <ide> docker build -t docker . <del>export AWS_S3_BUCKET="test.docker.io" <del>export AWS_ACCESS_KEY="$(cat ~/.aws/access_key)" <del>export AWS_SECRET_KEY="$(cat ~/.aws/secret_key)" <del>export GPG_PASSPHRASE=supersecretsesame <ide> docker run \ <ide> -e AWS_S3_BUCKET=test.docker.io \ <del> -e AWS_ACCESS_KEY \ <del> -e AWS_SECRET_KEY \ <del> -e GPG_PASSPHRASE \ <add> -e AWS_ACCESS_KEY="..." \ <add> -e AWS_SECRET_KEY="..." \ <add> -e GPG_PASSPHRASE="..." \ <ide> -i -t --privileged \ <ide> docker \ <ide> hack/release.sh <ide> ``` <ide> <del>It will run the test suite one more time, build the binaries and packages, <add>It will run the test suite, build the binaries and packages, <ide> and upload to the specified bucket (you should use test.docker.io for <ide> general testing, and once everything is fine, switch to get.docker.io as <ide> noted below). <ide> get.docker.io: <ide> ```bash <ide> docker run \ <ide> -e AWS_S3_BUCKET=get.docker.io \ <del> -e AWS_ACCESS_KEY \ <del> -e AWS_SECRET_KEY \ <del> -e GPG_PASSPHRASE \ <add> -e AWS_ACCESS_KEY="..." \ <add> -e AWS_SECRET_KEY="..." \ <add> -e GPG_PASSPHRASE="..." \ <ide> -i -t --privileged \ <ide> docker \ <ide> hack/release.sh <ide> ``` <ide> <del>### 9. Breakathon <add>### 8. Breakathon <ide> <ide> Spend several days along with the community explicitly investing time and <ide> resources to try and break Docker in every possible way, documenting any <ide> by the book. <ide> Any issues found may still remain issues for this release, but they should be <ide> documented and give appropriate warnings. <ide> <del>### 10. Apply tag <add>### 9. Apply tag <add> <add>It's very important that we don't make the tag until after the official <add>release is uploaded to get.docker.io! <ide> <ide> ```bash <ide> git tag -a $VERSION -m $VERSION bump_$VERSION <ide> git push origin $VERSION <ide> ``` <ide> <del>It's very important that we don't make the tag until after the official <del>release is uploaded to get.docker.io! <del> <del>### 11. Go to github to merge the `bump_$VERSION` branch into release <add>### 10. Go to github to merge the `bump_$VERSION` branch into release <ide> <ide> Don't forget to push that pretty blue button to delete the leftover <ide> branch afterwards! <ide> <del>### 12. Update the docs branch <add>### 11. Update the docs branch <ide> <ide> You will need the `awsconfig` file added to the `docs/` directory to contain the <ide> s3 credentials for the bucket you are deploying to. <ide> <ide> ```bash <del>git checkout docs <add>git checkout -b docs release || git checkout docs <ide> git fetch <ide> git reset --hard origin/release <ide> git push -f origin docs <ide> The docs will appear on http://docs.docker.io/ (though there may be cached <ide> versions, so its worth checking http://docs.docker.io.s3-website-us-west-2.amazonaws.com/). <ide> For more information about documentation releases, see `docs/README.md`. <ide> <del>### 13. Create a new pull request to merge release back into master <add>### 12. Create a new pull request to merge release back into master <ide> <ide> ```bash <ide> git checkout master <ide> git checkout -b merge_release_$VERSION <ide> echo ${VERSION#v}-dev > VERSION <ide> git add VERSION <ide> git commit -m "Change version to $(cat VERSION)" <del>git push origin merge_release_$VERSION <del>echo "https://github.com/dotcloud/docker/compare/master...merge_release_$VERSION" <add>git push $GITHUBUSER merge_release_$VERSION <add>echo "https://github.com/$GITHUBUSER/docker/compare/dotcloud:master...$GITHUBUSER:merge_release_$VERSION?expand=1" <ide> ``` <ide> <ide> Again, get two maintainers to validate, then merge, then push that pretty <ide> blue button to delete your branch. <ide> <del>### 14. Rejoice and Evangelize! <add>### 13. Rejoice and Evangelize! <ide> <ide> Congratulations! You're done. <ide>
1
Python
Python
add test for the default error state
7129ec3ff04e3e598bc18c2323daec78c5521770
<ide><path>numpy/core/tests/test_errstate.py <ide> from numpy.testing import * <ide> <ide> class TestErrstate(TestCase): <add> def test_default(self): <add> err = geterr() <add> self.assertEqual(err, dict( <add> divide='warn', <add> invalid='warn', <add> over='warn', <add> under='ignore', <add> )) <add> <ide> def test_invalid(self): <ide> with errstate(all='raise', under='ignore'): <ide> a = -arange(3)
1
Ruby
Ruby
fix rubocop violations
b9bee5e895e218b17a5f4ad72c3cbf6204fa4145
<ide><path>activerecord/test/schema/postgresql_specific_schema.rb <ide> t.oid :obj_id <ide> end <ide> <del> drop_table 'postgresql_timestamp_with_zones', if_exists: true <del> drop_table 'postgresql_partitioned_table', if_exists: true <del> drop_table 'postgresql_partitioned_table_parent', if_exists: true <add> drop_table "postgresql_timestamp_with_zones", if_exists: true <add> drop_table "postgresql_partitioned_table", if_exists: true <add> drop_table "postgresql_partitioned_table_parent", if_exists: true <ide> <ide> execute "DROP SEQUENCE IF EXISTS companies_nonstd_seq CASCADE" <ide> execute "CREATE SEQUENCE companies_nonstd_seq START 101 OWNED BY companies.id"
1
Javascript
Javascript
add component schema for modal
8e6031cac7a3107e89591060d10883d410acbc07
<ide><path>Libraries/Modal/ModalSchema.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @format <add> * @flow <add> */ <add>'use strict'; <add> <add>import type {SchemaType} from '../../packages/react-native-codegen/src/CodegenSchema.js'; <add> <add>const ModalSchema: SchemaType = { <add> modules: { <add> ModalHostView: { <add> components: { <add> ModalHostView: { <add> interfaceOnly: true, <add> extendsProps: [ <add> { <add> type: 'ReactNativeBuiltInType', <add> knownTypeName: 'ReactNativeCoreViewProps', <add> }, <add> ], <add> events: [ <add> { <add> name: 'onRequestClose', <add> optional: true, <add> bubblingType: 'bubble', <add> typeAnnotation: { <add> type: 'EventTypeAnnotation', <add> argument: { <add> type: 'ObjectTypeAnnotation', <add> properties: [], <add> }, <add> }, <add> }, <add> { <add> name: 'onShow', <add> optional: true, <add> bubblingType: 'bubble', <add> typeAnnotation: { <add> type: 'EventTypeAnnotation', <add> argument: { <add> type: 'ObjectTypeAnnotation', <add> properties: [], <add> }, <add> }, <add> }, <add> { <add> name: 'onDismiss', <add> optional: true, <add> bubblingType: 'bubble', <add> typeAnnotation: { <add> type: 'EventTypeAnnotation', <add> argument: { <add> type: 'ObjectTypeAnnotation', <add> properties: [], <add> }, <add> }, <add> }, <add> { <add> name: 'onOrientationChange', <add> optional: true, <add> bubblingType: 'bubble', <add> typeAnnotation: { <add> type: 'EventTypeAnnotation', <add> argument: { <add> type: 'ObjectTypeAnnotation', <add> properties: [], <add> }, <add> }, <add> }, <add> ], <add> props: [ <add> { <add> name: 'animationType', <add> optional: true, <add> typeAnnotation: { <add> type: 'StringEnumTypeAnnotation', <add> default: 'none', <add> options: [ <add> { <add> name: 'none', <add> }, <add> { <add> name: 'slide', <add> }, <add> { <add> name: 'fade', <add> }, <add> ], <add> }, <add> }, <add> { <add> name: 'presentationStyle', <add> optional: true, <add> typeAnnotation: { <add> type: 'StringEnumTypeAnnotation', <add> default: 'fullScreen', <add> options: [ <add> { <add> name: 'fullScreen', <add> }, <add> { <add> name: 'pageSheet', <add> }, <add> { <add> name: 'formSheet', <add> }, <add> { <add> name: 'overFullScreen', <add> }, <add> ], <add> }, <add> }, <add> { <add> name: 'transparent', <add> optional: true, <add> typeAnnotation: { <add> type: 'BooleanTypeAnnotation', <add> default: false, <add> }, <add> }, <add> { <add> name: 'hardwareAccelerated', <add> optional: true, <add> typeAnnotation: { <add> type: 'BooleanTypeAnnotation', <add> default: false, <add> }, <add> }, <add> { <add> name: 'visible', <add> optional: true, <add> typeAnnotation: { <add> type: 'BooleanTypeAnnotation', <add> default: true, <add> }, <add> }, <add> { <add> name: 'supportedOrientations', <add> optional: true, <add> typeAnnotation: { <add> type: 'StringEnumTypeAnnotation', <add> default: 'portrait', <add> options: [ <add> { <add> name: 'portrait', <add> }, <add> // TODO T43735085: uncomment when hyphen symobls are proplerly supoported in code gen. <add> // { <add> // name: 'portrait-upside-down', <add> // }, <add> { <add> name: 'landscape', <add> }, <add> // { <add> // name: 'landscape_left', <add> // }, <add> // { <add> // name: 'landscape_right', <add> // }, <add> ], <add> }, <add> }, <add> { <add> name: 'identifier', <add> optional: true, <add> typeAnnotation: { <add> type: 'Int32TypeAnnotation', <add> default: 0, <add> }, <add> }, <add> ], <add> }, <add> }, <add> }, <add> }, <add>}; <add> <add>module.exports = ModalSchema;
1
PHP
PHP
apply fixes from styleci
1f1540ab92effba1025b2e74b358c3e75ecf2ac6
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> public function if($name, Closure $callback) <ide> }); <ide> <ide> $this->directive('end'.$name, function () { <del> return "<?php endif; ?>"; <add> return '<?php endif; ?>'; <ide> }); <ide> } <ide>
1
Java
Java
update copyright date
411539ffef01ab5559cf43db0f8118b7e4d10060
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License.
1
PHP
PHP
remove old code that was never documented or used
ac5c52b2e108d2b2eb4bc84d2d7b08c2237c09b7
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> abstract class TestCase extends PHPUnit_Framework_TestCase <ide> { <ide> use ApplicationTrait, AssertionsTrait, CrawlerTrait; <ide> <del> /** <del> * The Eloquent factory instance. <del> * <del> * @var \Illuminate\Database\Eloquent\Factory <del> */ <del> protected $factory; <del> <ide> /** <ide> * The callbacks that should be run before the application is destroyed. <ide> * <ide> public function setUp() <ide> if (!$this->app) { <ide> $this->refreshApplication(); <ide> } <del> <del> if (!$this->factory) { <del> $this->factory = $this->app->make('Illuminate\Database\Eloquent\Factory'); <del> } <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix outbound link [ci skip]
86510227749be0c0db156672fc8f0d8f5401505f
<ide><path>website/src/components/link.js <ide> import React, { Fragment } from 'react' <ide> import PropTypes from 'prop-types' <ide> import { Link as GatsbyLink } from 'gatsby' <del>import { OutboundLink } from 'gatsby-plugin-google-analytics' <ide> import classNames from 'classnames' <ide> <ide> import Icon from './icon' <ide> export default function Link({ <ide> const rel = isInternal ? null : 'noopener nofollow noreferrer' <ide> return ( <ide> <Wrapper> <del> <OutboundLink <del> href={dest} <del> className={linkClassNames} <del> target="_blank" <del> rel={rel} <del> {...other} <del> > <add> <a href={dest} className={linkClassNames} target="_blank" rel={rel} {...other}> <ide> {content} <del> </OutboundLink> <add> </a> <ide> </Wrapper> <ide> ) <ide> }
1
Text
Text
update nlp readme to introduce major components
daa1408c6f3fc01865f64438ce148eaca4c67003
<ide><path>official/nlp/README.md <del># TensorFlow Natural Language Processing Modelling Toolkit <add># TensorFlow NLP Modelling Toolkit <ide> <del>tensorflow/models/official/nlp provides a [modeling library](modeling) for constructing <del>NLP model achitectures, as well as TF2 reference implementations for <del>state-of-the-art models. <add>This codebase provides a Natrual Language Processing modeling toolkit written in <add>[TF2](https://www.tensorflow.org/guide/effective_tf2). It allows researchers and <add>developers to reproduce state-of-the-art model results and train custom models <add>to experiment new research ideas. <ide> <del>The repository contains the following models, with implementations, pre-trained <del>model weights, usage scripts and conversion utilities: <add>## Features <ide> <del>* [Albert](albert) <del>* [Bert](bert) <del>* [NHNet](nhnet) <del>* [XLNet](xlnet) <del>* [Transformer for translation](transformer) <add>* Reusable and modularized modeling building blocks <add>* State-of-the-art reproducible <add>* Easy to customize and extend <add>* End-to-end training <add>* Distributed trainable on both GPUs and TPUs <ide> <del>Addtional features: <add>## Major components <add> <add>### Libraries <add> <add>We provide modeling library to allow users to train custom models for new <add>research ideas. Detailed intructions can be found in READMEs in each folder. <add> <add>* [modeling/](modeling): modeling library that provides building blocks (e.g., Layers, Networks, and Models) that can be assembled into transformer-based achitectures . <add>* [data/](data): binaries and utils for input preprocessing, tokenization, etc. <add> <add>### State-of-the-Art models and examples <add> <add>We provide SoTA model implementations, pre-trained models, training and <add>evaluation examples, and command lines. Detail instructions can be found in the <add>READMEs for specific papers. <add> <add>1. [BERT](bert): [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Devlin et al., 2018 <add>2. [ALBERT](albert): [A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) by Lan et al., 2019 <add>3. [XLNet](xlnet): [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Yang et al., 2019 <add>4. [Transformer for translation](transformer): [Attention Is All You Need](https://arxiv.org/abs/1706.03762) by Vaswani et al., 2017 <add>5. [NHNet](nhnet): [Generating Representative Headlines for News Stories](https://arxiv.org/abs/2001.09386) by Gu et al, 2020 <ide> <del>* Distributed trainable on both multi-GPU and TPU <del>* e2e training for custom models, including both pretraining and finetuning.
1
Javascript
Javascript
fix a bug and speed up graycs_getrgbbuffer
80304b69761910a43a1281b042a424b237ee7681
<ide><path>pdf.js <ide> var DeviceGrayCS = (function() { <ide> }, <ide> getRgbBuffer: function graycs_getRgbBuffer(input, bits) { <ide> var scale = 255 / ((1 << bits) - 1); <del> var length = input.length * 3; <del> var rgbBuf = new Uint8Array(length); <del> for (var i = 0, j = 0; i < length; ++i) { <add> var rgbBuf = new Uint8Array(input.length * 3); <add> for (var i = 0, j = 0; i < input.length; ++i) { <ide> var c = (scale * input[i]) | 0; <ide> rgbBuf[j++] = c; <ide> rgbBuf[j++] = c;
1
Text
Text
fix typo in buffer.md
4f11b8b8ae06bf42b483ec7da69ccf7930291056
<ide><path>doc/api/buffer.md <ide> console.log(uint32array); <ide> <ide> ```js <ide> const buf = Buffer.from('hello', 'utf16le'); <del>const uint16arr = new Uint16Array( <add>const uint16array = new Uint16Array( <ide> buf.buffer, <ide> buf.byteOffset, <ide> buf.length / Uint16Array.BYTES_PER_ELEMENT);
1
PHP
PHP
allow define hidden/visible options dynamically
7667cd511ee7982a7b8bb60234856482c141dfb5
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function relationsToArray() <ide> <ide> foreach ($this->getArrayableRelations() as $key => $value) <ide> { <del> if (in_array($key, $this->hidden)) continue; <add> if (in_array($key, $this->getHidden())) continue; <ide> <ide> // If the values implements the Arrayable interface we can just call this <ide> // toArray method on the instances which will convert both models and <ide> protected function getArrayableRelations() <ide> */ <ide> protected function getArrayableItems(array $values) <ide> { <del> if (count($this->visible) > 0) <add> if (count($this->getVisible()) > 0) <ide> { <del> return array_intersect_key($values, array_flip($this->visible)); <add> return array_intersect_key($values, array_flip($this->getVisible())); <ide> } <ide> <del> return array_diff_key($values, array_flip($this->hidden)); <add> return array_diff_key($values, array_flip($this->getHidden())); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testToArrayUsesMutators() <ide> } <ide> <ide> <add> public function testHidden() <add> { <add> $model = new EloquentModelStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']); <add> $model->setHidden(['age', 'id']); <add> $array = $model->toArray(); <add> $this->assertArrayHasKey('name', $array); <add> $this->assertArrayNotHasKey('age', $array); <add> } <add> <add> <add> public function testVisible() <add> { <add> $model = new EloquentModelStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']); <add> $model->setVisible(['name', 'id']); <add> $array = $model->toArray(); <add> $this->assertArrayHasKey('name', $array); <add> $this->assertArrayNotHasKey('age', $array); <add> } <add> <add> <add> public function testHiddenAreIgnoringWhenVisibleExists() <add> { <add> $model = new EloquentModelStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']); <add> $model->setVisible(['name', 'id']); <add> $model->setHidden(['name', 'age']); <add> $array = $model->toArray(); <add> $this->assertArrayHasKey('name', $array); <add> $this->assertArrayHasKey('id', $array); <add> $this->assertArrayNotHasKey('age', $array); <add> } <add> <add> <add> public function testDynamicHidden() <add> { <add> $model = new EloquentModelDynamicHiddenStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']); <add> $array = $model->toArray(); <add> $this->assertArrayHasKey('name', $array); <add> $this->assertArrayNotHasKey('age', $array); <add> } <add> <add> <add> public function testDynamicVisible() <add> { <add> $model = new EloquentModelDynamicVisibleStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']); <add> $array = $model->toArray(); <add> $this->assertArrayHasKey('name', $array); <add> $this->assertArrayNotHasKey('age', $array); <add> } <add> <add> <ide> public function testFillable() <ide> { <ide> $model = new EloquentModelStub; <ide> public function eighthAttributeValue() <ide> return $this->attributes['eighth']; <ide> } <ide> } <add> <add>class EloquentModelDynamicHiddenStub extends Illuminate\Database\Eloquent\Model { <add> protected $table = 'stub'; <add> protected $guarded = []; <add> public function getHidden() <add> { <add> return ['age', 'id']; <add> } <add>} <add> <add>class EloquentModelDynamicVisibleStub extends Illuminate\Database\Eloquent\Model { <add> protected $table = 'stub'; <add> protected $guarded = []; <add> public function getVisible() <add> { <add> return ['name', 'id']; <add> } <add>}
2
Python
Python
support online masking for xlnet
6cd426d917d10f3f334cb009d12db527ef81750f
<ide><path>official/nlp/xlnet/data_utils.py <ide> # from __future__ import google_type_annotations <ide> from __future__ import print_function <ide> <add>import collections <ide> import json <ide> import os <ide> from absl import logging <ide> <add>import numpy as np <ide> import tensorflow as tf <ide> <add> <ide> special_symbols = { <ide> "<unk>": 0, <ide> "<s>": 1, <ide> SEG_ID_PAD = 3 <ide> <ide> <add>OnlineMaskingConfig = collections.namedtuple("OnlineMaskingConfig", [ <add> "sample_strategy", "max_num_tokens", "min_num_tokens", "max_num_words", <add> "min_num_words"]) <add> <add> <ide> def file_based_input_fn_builder(input_file, name_to_features, batch_size, <ide> is_training): <ide> """Creates an `input_fn` closure.""" <ide> def _dataset_fn(ctx=None): <ide> return _dataset_fn if use_dataset_fn else _dataset_fn() <ide> <ide> <add>def _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, num_predict): <add> """Turn beg and end indices into actual mask.""" <add> non_func_mask = tf.logical_and( <add> tf.not_equal(inputs, SEP_ID), <add> tf.not_equal(inputs, CLS_ID)) <add> all_indices = tf.where( <add> non_func_mask, <add> tf.range(tgt_len, dtype=tf.int64), <add> tf.constant(-1, shape=[tgt_len], dtype=tf.int64)) <add> candidate_matrix = tf.cast( <add> tf.logical_and( <add> all_indices[None, :] >= beg_indices[:, None], <add> all_indices[None, :] < end_indices[:, None]), <add> tf.float32) <add> cumsum_matrix = tf.reshape( <add> tf.cumsum(tf.reshape(candidate_matrix, [-1])), <add> [-1, tgt_len]) <add> masked_matrix = tf.cast(cumsum_matrix <= num_predict, tf.float32) <add> target_mask = tf.reduce_sum(candidate_matrix * masked_matrix, axis=0) <add> is_masked = tf.cast(target_mask, tf.bool) <add> <add> return is_masked, target_mask <add> <add> <add>def _word_span_mask(inputs, tgt_len, num_predict, min_num_words, <add> max_num_words, boundary): <add> """Sample whole word spans as prediction targets.""" <add> # Note: 1.2 is the token-to-word ratio <add> mask_alpha = tgt_len / num_predict / 1.2 <add> round_to_int = lambda x: tf.cast(tf.round(x), tf.int64) <add> <add> # Sample span lengths from a zipf distribution <add> span_len_seq = np.arange(min_num_words, max_num_words + 1) <add> probs = np.array([1.0 / (i + 1) for i in span_len_seq]) <add> probs /= np.sum(probs) <add> logits = tf.constant(np.log(probs), dtype=tf.float32) <add> <add> # Sample `num_predict` words here: note that this is over sampling <add> span_lens = tf.random.categorical( <add> logits=logits[None], <add> num_samples=num_predict, <add> dtype=tf.int64, <add> )[0] + min_num_words <add> <add> # Sample the ratio [0.0, 1.0) of left context lengths <add> span_lens_float = tf.cast(span_lens, tf.float32) <add> left_ratio = tf.random.uniform(shape=[num_predict], minval=0.0, maxval=1.0) <add> left_ctx_len = left_ratio * span_lens_float * (mask_alpha - 1) <add> <add> left_ctx_len = round_to_int(left_ctx_len) <add> right_offset = round_to_int(span_lens_float * mask_alpha) - left_ctx_len <add> <add> beg_indices = (tf.cumsum(left_ctx_len) + <add> tf.cumsum(right_offset, exclusive=True)) <add> end_indices = beg_indices + span_lens <add> <add> # Remove out of range indices <add> max_boundary_index = tf.cast(tf.shape(boundary)[0] - 1, tf.int64) <add> valid_idx_mask = end_indices < max_boundary_index <add> beg_indices = tf.boolean_mask(beg_indices, valid_idx_mask) <add> end_indices = tf.boolean_mask(end_indices, valid_idx_mask) <add> <add> beg_indices = tf.gather(boundary, beg_indices) <add> end_indices = tf.gather(boundary, end_indices) <add> <add> # Shuffle valid indices <add> num_valid = tf.cast(tf.shape(beg_indices)[0], tf.int64) <add> order = tf.random.shuffle(tf.range(num_valid, dtype=tf.int64)) <add> beg_indices = tf.gather(beg_indices, order) <add> end_indices = tf.gather(end_indices, order) <add> <add> return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, <add> num_predict) <add> <add> <add>def _token_span_mask(inputs, tgt_len, num_predict, min_num_tokens, <add> max_num_tokens): <add> """Sample token spans as prediction targets.""" <add> mask_alpha = tgt_len / num_predict <add> round_to_int = lambda x: tf.cast(tf.round(x), tf.int64) <add> <add> # Sample span lengths from a zipf distribution <add> span_len_seq = np.arange(min_num_tokens, max_num_tokens + 1) <add> probs = np.array([1.0 / (i + 1) for i in span_len_seq]) <add> <add> probs /= np.sum(probs) <add> logits = tf.constant(np.log(probs), dtype=tf.float32) <add> span_lens = tf.random.categorical( <add> logits=logits[None], <add> num_samples=num_predict, <add> dtype=tf.int64, <add> )[0] + min_num_tokens <add> <add> # Sample the ratio [0.0, 1.0) of left context lengths <add> span_lens_float = tf.cast(span_lens, tf.float32) <add> left_ratio = tf.random.uniform(shape=[num_predict], minval=0.0, maxval=1.0) <add> left_ctx_len = left_ratio * span_lens_float * (mask_alpha - 1) <add> left_ctx_len = round_to_int(left_ctx_len) <add> <add> # Compute the offset from left start to the right end <add> right_offset = round_to_int(span_lens_float * mask_alpha) - left_ctx_len <add> <add> # Get the actual begin and end indices <add> beg_indices = (tf.cumsum(left_ctx_len) + <add> tf.cumsum(right_offset, exclusive=True)) <add> end_indices = beg_indices + span_lens <add> <add> # Remove out of range indices <add> valid_idx_mask = end_indices < tgt_len <add> beg_indices = tf.boolean_mask(beg_indices, valid_idx_mask) <add> end_indices = tf.boolean_mask(end_indices, valid_idx_mask) <add> <add> # Shuffle valid indices <add> num_valid = tf.cast(tf.shape(beg_indices)[0], tf.int64) <add> order = tf.random.shuffle(tf.range(num_valid, dtype=tf.int64)) <add> beg_indices = tf.gather(beg_indices, order) <add> end_indices = tf.gather(end_indices, order) <add> <add> return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, <add> num_predict) <add> <add> <add>def _whole_word_mask(inputs, tgt_len, num_predict, boundary): <add> """Sample whole words as prediction targets.""" <add> pair_indices = tf.concat([boundary[:-1, None], boundary[1:, None]], axis=1) <add> cand_pair_indices = tf.random.shuffle(pair_indices)[:num_predict] <add> beg_indices = cand_pair_indices[:, 0] <add> end_indices = cand_pair_indices[:, 1] <add> <add> return _idx_pair_to_mask(beg_indices, end_indices, inputs, tgt_len, <add> num_predict) <add> <add> <add>def _single_token_mask(inputs, tgt_len, num_predict): <add> """Sample individual tokens as prediction targets.""" <add> all_indices = tf.range(tgt_len, dtype=tf.int64) <add> non_func_mask = tf.logical_and( <add> tf.not_equal(inputs, SEP_ID), <add> tf.not_equal(inputs, CLS_ID)) <add> non_func_indices = tf.boolean_mask(all_indices, non_func_mask) <add> <add> masked_pos = tf.random.shuffle(non_func_indices) <add> masked_pos = tf.contrib.framework.sort(masked_pos[:num_predict]) <add> target_mask = tf.sparse_to_dense( <add> sparse_indices=masked_pos, <add> output_shape=[tgt_len], <add> sparse_values=1.0, <add> default_value=0.0) <add> <add> is_masked = tf.cast(target_mask, tf.bool) <add> <add> return is_masked, target_mask <add> <add> <add>def _online_sample_masks(inputs, tgt_len, num_predict, online_masking_config, <add> boundary=None): <add> """Sample target positions to predict.""" <add> logging.info("Online sample with strategy: `%s`.", <add> online_masking_config.sample_strategy) <add> if online_masking_config.sample_strategy == "single_token": <add> return _single_token_mask(inputs, tgt_len, num_predict) <add> elif online_masking_config.sample_strategy == "whole_word": <add> assert boundary is not None, "whole word sampling requires `boundary`" <add> return _whole_word_mask(inputs, tgt_len, num_predict, boundary) <add> elif online_masking_config.sample_strategy == "token_span": <add> return _token_span_mask(inputs, tgt_len, num_predict, <add> online_masking_config.min_num_tokens, <add> online_masking_config.max_num_tokens) <add> elif online_masking_config.sample_strategy == "word_span": <add> assert boundary is not None, "word span sampling requires `boundary`" <add> return _word_span_mask(inputs, tgt_len, num_predict, <add> online_masking_config.min_num_words, <add> online_masking_config.max_num_words, <add> boundary) <add> else: <add> raise NotImplementedError <add> <add> <ide> def create_pretrain_dataset(file_names, <ide> bsz_per_core, <ide> seq_len, <ide> reuse_len, <ide> perm_size, <add> leak_ratio, <add> online_masking_config, <ide> num_predict=None, <ide> input_pipeline_context=None): <ide> """Creates pretrain dataset.""" <ide> def parser(record): <ide> <ide> record_spec = { <ide> "input": tf.io.FixedLenFeature([seq_len], tf.int64), <del> "target": tf.io.FixedLenFeature([seq_len], tf.int64), <ide> "seg_id": tf.io.FixedLenFeature([seq_len], tf.int64), <ide> "label": tf.io.FixedLenFeature([1], tf.int64), <del> "is_masked": tf.io.FixedLenFeature([seq_len], tf.int64), <ide> } <ide> <add> if online_masking_config.sample_strategy in ["whole_word", "word_span"]: <add> logging.info("Add `boundary` spec for %s", <add> online_masking_config.sample_strategy) <add> record_spec["boundary"] = tf.io.VarLenFeature(tf.int64) <add> <ide> # retrieve serialized example <ide> example = tf.io.parse_single_example( <ide> serialized=record, features=record_spec) <ide> <ide> inputs = example.pop("input") <del> target = example.pop("target") <del> is_masked = tf.cast(example.pop("is_masked"), tf.bool) <del> <del> non_reuse_len = seq_len - reuse_len <del> # perm_size should not be larger than reuse_len or non_reuse_len otherwise <del> # there will be data leaks. <del> assert perm_size <= reuse_len and perm_size <= non_reuse_len <del> <del> # Creates permutation mask and target mask for the first reuse_len tokens. <del> # The tokens in this part are reused from the last sequence. <del> perm_mask_0, target_0, target_mask_0, input_k_0, input_q_0 = _local_perm( <del> inputs[:reuse_len], target[:reuse_len], is_masked[:reuse_len], <del> perm_size, reuse_len) <del> <del> # Creates permutation mask and target mask for the rest of tokens in <del> # current example, which are concatentation of two new segments. <del> perm_mask_1, target_1, target_mask_1, input_k_1, input_q_1 = _local_perm( <del> inputs[reuse_len:], target[reuse_len:], is_masked[reuse_len:], <del> perm_size, non_reuse_len) <del> <del> perm_mask_0 = tf.concat( <del> [perm_mask_0, tf.ones([reuse_len, non_reuse_len])], axis=1) <del> perm_mask_1 = tf.concat([tf.zeros([non_reuse_len, reuse_len]), perm_mask_1], <del> axis=1) <del> perm_mask = tf.concat([perm_mask_0, perm_mask_1], axis=0) <del> target = tf.concat([target_0, target_1], axis=0) <del> target_mask = tf.concat([target_mask_0, target_mask_1], axis=0) <del> input_k = tf.concat([input_k_0, input_k_1], axis=0) <del> input_q = tf.concat([input_q_0, input_q_1], axis=0) <add> if online_masking_config.sample_strategy in ["whole_word", "word_span"]: <add> boundary = tf.sparse.to_dense(example.pop("boundary")) <add> else: <add> boundary = None <add> is_masked, _ = _online_sample_masks( <add> inputs, seq_len, num_predict, online_masking_config, boundary=boundary) <add> <add> if reuse_len > 0: <add> ##### Use memory <add> # permutate the reuse and non-reuse parts separately <add> non_reuse_len = seq_len - reuse_len <add> assert reuse_len % perm_size == 0 and non_reuse_len % perm_size == 0 <add> <add> # Creates permutation mask and target mask for the first reuse_len tokens. <add> # The tokens in this part are reused from the last sequence. <add> perm_mask_0, target_mask_0, input_k_0, input_q_0 = _local_perm( <add> inputs[:reuse_len], is_masked[:reuse_len], perm_size, reuse_len, <add> leak_ratio) <add> <add> # Creates permutation mask and target mask for the rest of tokens in <add> # current example, which are concatentation of two new segments. <add> perm_mask_1, target_mask_1, input_k_1, input_q_1 = _local_perm( <add> inputs[reuse_len:], is_masked[reuse_len:], perm_size, non_reuse_len, <add> leak_ratio) <add> <add> perm_mask_0 = tf.concat( <add> [perm_mask_0, tf.ones([reuse_len, non_reuse_len])], axis=1) <add> perm_mask_1 = tf.concat( <add> [tf.zeros([non_reuse_len, reuse_len]), perm_mask_1], axis=1) <add> perm_mask = tf.concat([perm_mask_0, perm_mask_1], axis=0) <add> target_mask = tf.concat([target_mask_0, target_mask_1], axis=0) <add> input_k = tf.concat([input_k_0, input_k_1], axis=0) <add> input_q = tf.concat([input_q_0, input_q_1], axis=0) <add> else: <add> ##### Do not use memory <add> assert seq_len % perm_size == 0 <add> # permutate the entire sequence together <add> perm_mask, target_mask, input_k, input_q = _local_perm( <add> inputs, is_masked, perm_size, seq_len, leak_ratio) <add> <add> # reshape back to fixed shape <add> example["perm_mask"] = tf.reshape(perm_mask, [seq_len, seq_len]) <add> example["input_k"] = tf.reshape(input_k, [seq_len]) <add> example["input_q"] = tf.reshape(input_q, [seq_len]) <add> <add> # Directly use raw inputs as the target <add> target = inputs <ide> <ide> if num_predict is not None: <ide> indices = tf.range(seq_len, dtype=tf.int64) <ide> def parser(record): <ide> example["target"] = tf.reshape(target, [num_predict]) <ide> <ide> ##### target mask <del> target_mask = tf.concat([ <del> tf.ones([actual_num_predict], dtype=tf.float32), <del> tf.zeros([pad_len], dtype=tf.float32) <del> ], <del> axis=0) <add> target_mask = tf.concat( <add> [tf.ones([actual_num_predict], dtype=tf.float32), <add> tf.zeros([pad_len], dtype=tf.float32)], <add> axis=0) <ide> example["target_mask"] = tf.reshape(target_mask, [num_predict]) <ide> else: <ide> example["target"] = tf.reshape(target, [seq_len]) <ide> example["target_mask"] = tf.reshape(target_mask, [seq_len]) <ide> <del> # reshape back to fixed shape <del> example["perm_mask"] = tf.reshape(perm_mask, [seq_len, seq_len]) <del> example["input_k"] = tf.reshape(input_k, [seq_len]) <del> example["input_q"] = tf.reshape(input_q, [seq_len]) <del> <ide> for key in list(example.keys()): <ide> val = example[key] <ide> if tf.keras.backend.is_sparse(val): <ide> def parser(record): <ide> parser=parser, <ide> file_paths=file_names, <ide> bsz_per_core=bsz_per_core, <add> sequential=reuse_len > 0, <ide> input_pipeline_context=input_pipeline_context) <ide> <ide> return dataset <ide> <ide> <del>def format_filename(prefix, <del> bsz_per_host, <del> seq_len, <del> bi_data, <del> suffix, <del> mask_alpha=5, <del> mask_beta=1, <del> reuse_len=None, <del> uncased=False, <del> fixed_num_predict=None): <add>def format_filename(prefix, suffix, bsz_per_host, seq_len, reuse_len=None, <add> uncased=False): <ide> """Generates input file name pattern.""" <del> if reuse_len is None: <del> reuse_len_str = "" <add> if reuse_len is not None and reuse_len > 0: <add> reuse_str = "reuse-{}.".format(reuse_len) <add> bsz_str = "hostbsz-{}.".format(bsz_per_host) <ide> else: <del> reuse_len_str = "reuse-{}.".format(reuse_len) <add> reuse_str = "" <add> bsz_str = "" <add> <ide> if not uncased: <del> uncased_str = "" <del> else: <del> uncased_str = "uncased." <del> if bi_data: <del> bi_data_str = "bi" <add> case_str = "" <ide> else: <del> bi_data_str = "uni" <del> if fixed_num_predict is not None: <del> fnp_str = "fnp-{}.".format(fixed_num_predict) <del> else: <del> fnp_str = "" <add> case_str = "uncased." <ide> <del> file_name = "{}.bsz-{}.seqlen-{}.{}{}{}.alpha-{}.beta-{}.{}{}".format( <del> prefix, bsz_per_host, seq_len, reuse_len_str, uncased_str, bi_data_str, <del> mask_alpha, mask_beta, fnp_str, suffix) <add> file_name = "{}.seq-{}.{}{}{}{}".format( <add> prefix, seq_len, reuse_str, bsz_str, case_str, suffix) <ide> <ide> return file_name <ide> <ide> def get_pretrain_input_data(batch_size, <ide> file_path, <ide> reuse_len, <ide> perm_size, <del> mask_alpha, <del> mask_beta, <add> leak_ratio, <ide> num_predict, <del> bi_data, <ide> uncased, <add> online_masking_config, <ide> num_hosts=1): <ide> """Returns input dataset from input file string.""" <ide> <ide> def get_pretrain_input_data(batch_size, <ide> # than passing dataset instance itself. <ide> use_dataset_fn = isinstance(strategy, tf.distribute.experimental.TPUStrategy) <ide> split = "train" <add> bsz_per_host = int(batch_size / num_hosts) <ide> record_glob_base = format_filename( <del> prefix="record_info-{}-*".format(split), <del> bsz_per_host=int(batch_size / num_hosts), <add> prefix="meta.{}.pass-*".format(split), <add> suffix="json*", <add> bsz_per_host=bsz_per_host, <ide> seq_len=seq_len, <del> bi_data=bi_data, <del> suffix="json", <del> mask_alpha=mask_alpha, <del> mask_beta=mask_beta, <ide> reuse_len=reuse_len, <del> uncased=uncased, <del> fixed_num_predict=num_predict) <add> uncased=uncased) <add> <add> def _get_num_batch(info): <add> if "num_batch" in info: <add> return info["num_batch"] <add> elif "num_example" in info: <add> return info["num_example"] / bsz_per_host <add> else: <add> raise ValueError("Do not have sample info.") <ide> <ide> if use_dataset_fn: <ide> if batch_size % strategy.num_replicas_in_sync != 0: <ide> def get_pretrain_input_data(batch_size, <ide> for record_info_path in record_paths: <ide> with tf.io.gfile.GFile(record_info_path, "r") as fp: <ide> info = json.load(fp) <del> cur_record_info["num_batch"] += info["num_batch"] <add> cur_record_info["num_batch"] += int(_get_num_batch(info)) <ide> cur_record_info["filenames"] += info["filenames"] <ide> <ide> # overwrite directory for `cur_record_info` <ide> def _dataset_fn(ctx=None): <ide> seq_len=seq_len, <ide> reuse_len=reuse_len, <ide> perm_size=perm_size, <add> leak_ratio=leak_ratio, <add> online_masking_config=online_masking_config, <ide> num_predict=num_predict, <ide> input_pipeline_context=ctx) <ide> return train_dataset <ide> def _dataset_fn(ctx=None): <ide> def parse_files_to_dataset(parser, <ide> file_paths, <ide> bsz_per_core, <add> sequential, <ide> input_pipeline_context=None): <ide> """Creates the dataset given file paths.""" <ide> <ide> def parse_files_to_dataset(parser, <ide> if len(file_paths) > 1: <ide> dataset = dataset.shuffle(len(file_paths)) <ide> <del> dataset = tf.data.TFRecordDataset(dataset) <add> if sequential: <add> # Note: cannot perform sample-level shuffle here because this will violate <add> # the consecutive requirement of data stream. <add> dataset = tf.data.TFRecordDataset(dataset) <add> else: <add> # `cycle_length` is the number of parallel files that get read. <add> cycle_length = min(8, len(file_paths)) <add> logging.info("Interleave %d files", cycle_length) <add> <add> # `sloppy` mode means that the interleaving is not exact. This adds <add> # even more randomness to the training pipeline. <add> dataset = dataset.apply( <add> tf.data.experimental.parallel_interleave( <add> tf.data.TFRecordDataset, <add> sloppy=True, <add> cycle_length=cycle_length)) <add> buffer_size = 2048 <add> logging.info("Perform sample-level shuffle with size %d", buffer_size) <add> dataset = dataset.shuffle(buffer_size=buffer_size) <add> <ide> # (zihang): since we are doing online preprocessing, the parsed result of <ide> # the same input at each time will be different. Thus, cache processed data <ide> # is not helpful. It will use a lot of memory and lead to contrainer OOM. <ide> def parse_files_to_dataset(parser, <ide> return dataset <ide> <ide> <del>def _local_perm(inputs, targets, is_masked, perm_size, seq_len): <add>def _local_perm(inputs, is_masked, perm_size, seq_len, leak_ratio): <ide> """Samples a permutation of the factorization order. <ide> <ide> Creates perm_mask and target_mask accordingly. <ide> <ide> Args: <ide> inputs: int64 Tensor in shape [seq_len], input ids. <del> targets: int64 Tensor in shape [seq_len], target ids. <ide> is_masked: bool Tensor in shape [seq_len]. True means being selected for <ide> partial prediction. <ide> perm_size: the length of longest permutation. Could be set to be reuse_len. <ide> Should not be larger than reuse_len or there will be data leaks. <ide> seq_len: int, sequence length. <add> leak_ratio: float, percent of masked tokens that are leaked. <ide> <ide> Returns: <ide> perm_mask: float32 Tensor in shape [seq_len, seq_len] consisted of 0 and 1. <ide> def _local_perm(inputs, targets, is_masked, perm_size, seq_len): <ide> means the ith token (in original order) can attend to the jth token <ide> (in original order). Note that non-masked tokens can be attended by all <ide> other tokens, which is different from the description in original paper. <del> new_targets: int64 Tensor in shape [seq_len], target token ids to be <del> predicted in XLNet. <del> In XLNet, target doesn't need to be shifted one position. <ide> target_mask: float32 Tensor in shape [seq_len] consisted of 0 and 1. If <ide> target_mask[i] == 1, <ide> the ith token needs to be predicted and mask will be used as input. This <ide> def _local_perm(inputs, targets, is_masked, perm_size, seq_len): <ide> index = tf.random.shuffle(index) <ide> index = tf.reshape(tf.transpose(index), [-1]) <ide> <del> # `perm_mask` and `target_mask` <ide> # non-functional tokens <del> non_func_tokens = tf.logical_not( <del> tf.logical_or(tf.equal(inputs, SEP_ID), tf.equal(inputs, CLS_ID))) <del> <del> non_mask_tokens = tf.logical_and(tf.logical_not(is_masked), non_func_tokens) <del> masked_or_func_tokens = tf.logical_not(non_mask_tokens) <del> <del> # Set the permutation indices of non-masked (& non-funcional) tokens to the <del> # smallest index (-1): <del> # (1) they can be seen by all other positions <del> # (2) they cannot see masked positions, so there won"t be information leak <del> smallest_index = -tf.ones([seq_len], dtype=tf.int64) <del> rev_index = tf.where(non_mask_tokens, smallest_index, index) <del> <del> # Create `target_mask`: non-funcional and masked tokens <del> # 1: use mask as input and have loss <del> # 0: use token (or [SEP], [CLS]) as input and do not have loss <del> target_tokens = tf.logical_and(masked_or_func_tokens, non_func_tokens) <del> target_mask = tf.cast(target_tokens, tf.float32) <del> <del> # Create `perm_mask` <del> # `target_tokens` cannot see themselves <del> self_rev_index = tf.where(target_tokens, rev_index, rev_index + 1) <del> <del> # 1: cannot attend if i <= j and j is not non-masked (masked_or_func_tokens) <del> # 0: can attend if i > j or j is non-masked <del> perm_mask = tf.logical_and(self_rev_index[:, None] <= rev_index[None, :], <del> masked_or_func_tokens) <del> perm_mask = tf.cast(perm_mask, tf.float32) <del> <del> # new target: [next token] for LM and [curr token] (self) for PLM <del> new_targets = tf.concat([inputs[0:1], targets[:-1]], axis=0) <add> non_func_tokens = tf.logical_not(tf.logical_or( <add> tf.equal(inputs, SEP_ID), <add> tf.equal(inputs, CLS_ID))) <add> masked_tokens = tf.logical_and(is_masked, non_func_tokens) <add> non_masked_or_func_tokens = tf.logical_not(masked_tokens) <add> <add> smallest_index = -2 * tf.ones([seq_len], dtype=tf.int64) <add> <add> # Similar to BERT, randomly leak some masked tokens <add> if leak_ratio > 0: <add> leak_tokens = tf.logical_and( <add> masked_tokens, <add> tf.random.uniform([seq_len], maxval=1.0) < leak_ratio) <add> can_attend_self = tf.logical_or(non_masked_or_func_tokens, leak_tokens) <add> else: <add> can_attend_self = non_masked_or_func_tokens <add> to_index = tf.where(can_attend_self, smallest_index, index) <add> from_index = tf.where(can_attend_self, to_index + 1, to_index) <add> <add> # For masked tokens, can attend if i > j <add> # For context tokens, always can attend each other <add> can_attend = from_index[:, None] > to_index[None, :] <add> <add> # In modeling, 1 indicates cannot attend. Hence, reverse the value here. <add> perm_mask = 1.0 - tf.cast(can_attend, tf.float32) <add> <add> # Only masked tokens are included in the loss <add> target_mask = tf.cast(masked_tokens, tf.float32) <ide> <ide> # construct inputs_k <ide> inputs_k = inputs <ide> <ide> # construct inputs_q <del> inputs_q = target_mask <add> inputs_q = masked_tokens <ide> <del> return perm_mask, new_targets, target_mask, inputs_k, inputs_q <add> return perm_mask, target_mask, inputs_k, inputs_q <ide><path>official/nlp/xlnet/run_pretrain.py <ide> from official.nlp.xlnet import training_utils <ide> from official.utils.misc import tpu_lib <ide> <del>flags.DEFINE_integer( <del> "mask_alpha", default=6, help="How many tokens to form a group.") <del>flags.DEFINE_integer( <del> "mask_beta", default=1, help="How many tokens to mask within each group.") <ide> flags.DEFINE_integer( <ide> "num_predict", <ide> default=None, <ide> help="Number of tokens to predict in partial prediction.") <del>flags.DEFINE_integer("perm_size", 0, help="Window size of permutation.") <ide> <add># FLAGS for pretrain input preprocessing <add>flags.DEFINE_integer("perm_size", 0, help="Window size of permutation.") <add>flags.DEFINE_float("leak_ratio", default=0.1, <add> help="Percent of masked tokens that are leaked.") <add> <add>flags.DEFINE_enum("sample_strategy", default="token_span", <add> enum_values=["single_token", "whole_word", "token_span", <add> "word_span"], <add> help="Stragey used to sample prediction targets.") <add>flags.DEFINE_integer("max_num_tokens", default=5, <add> help="Maximum number of tokens to sample in a span." <add> "Effective when token_span strategy is used.") <add>flags.DEFINE_integer("min_num_tokens", default=1, <add> help="Minimum number of tokens to sample in a span." <add> "Effective when token_span strategy is used.") <add> <add>flags.DEFINE_integer("max_num_words", default=5, <add> help="Maximum number of whole words to sample in a span." <add> "Effective when word_span strategy is used.") <add>flags.DEFINE_integer("min_num_words", default=1, <add> help="Minimum number of whole words to sample in a span." <add> "Effective when word_span strategy is used.") <ide> FLAGS = flags.FLAGS <ide> <ide> <ide> def main(unused_argv): <ide> logging.info("***** Number of cores used : %d", <ide> strategy.num_replicas_in_sync) <ide> logging.info("***** Number of hosts used : %d", num_hosts) <add> online_masking_config = data_utils.OnlineMaskingConfig( <add> sample_strategy=FLAGS.sample_strategy, <add> max_num_tokens=FLAGS.max_num_tokens, <add> min_num_tokens=FLAGS.min_num_tokens, <add> max_num_words=FLAGS.max_num_words, <add> min_num_words=FLAGS.min_num_words) <add> <ide> train_input_fn = functools.partial( <ide> data_utils.get_pretrain_input_data, FLAGS.train_batch_size, FLAGS.seq_len, <ide> strategy, FLAGS.train_tfrecord_path, FLAGS.reuse_len, FLAGS.perm_size, <del> FLAGS.mask_alpha, FLAGS.mask_beta, FLAGS.num_predict, FLAGS.bi_data, <del> FLAGS.uncased, num_hosts) <add> FLAGS.leak_ratio, FLAGS.num_predict, FLAGS.uncased, online_masking_config, <add> num_hosts) <ide> <ide> total_training_steps = FLAGS.train_steps <ide> steps_per_epoch = int(FLAGS.train_data_size / FLAGS.train_batch_size)
2
Ruby
Ruby
add missing url escapes
b80af7837aea59188b9fffc7944dd0c2ecc93a42
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def bump_formula_pr <ide> ] <ide> elsif new_mirrors <ide> replacement_pairs << [ <del> /^( +)(mirror \"#{new_mirrors.last}\"\n)/m, <add> /^( +)(mirror \"#{Regexp.escape(new_mirrors.last)}\"\n)/m, <ide> "\\1\\2\\1version \"#{forced_version}\"\n", <ide> ] <ide> else <ide> replacement_pairs << [ <del> /^( +)(url \"#{new_url}\"\n)/m, <add> /^( +)(url \"#{Regexp.escape(new_url)}\"\n)/m, <ide> "\\1\\2\\1version \"#{forced_version}\"\n", <ide> ] <ide> end
1
Javascript
Javascript
fix duplicate test name
a1aa67ab3db06cb2018f482a721324f38f240529
<ide><path>packages/ember/tests/routing/basic_test.js <ide> test("The Homepage with explicit template name in renderTemplate", function() { <ide> equal(Ember.$('h3:contains(Megatroll)', '#qunit-fixture').length, 1, "The homepage template was rendered"); <ide> }); <ide> <del>test("The Homepage with explicit template name in renderTemplate", function() { <add>test("The Homepage with explicit template name in renderTemplate and controller", function() { <ide> Router.map(function(match) { <ide> this.route("home", { path: "/" }); <ide> });
1
Text
Text
add notes on preparing training data to docs
4ed5d9ad5ac7e1e7c5f22fc8fa1d784052b45249
<ide><path>website/docs/api/data-formats.md <ide> CLI [`train`](/api/cli#train) command. The built-in <ide> of the `.conllu` format used by the <ide> [Universal Dependencies corpora](https://github.com/UniversalDependencies). <ide> <add>Note that while this is the format used to save training data, you do not have <add>to understand the internal details to use it or create training data. See the <add>section on [preparing training data](/usage/training#training-data). <add> <ide> ### JSON training format {#json-input tag="deprecated"} <ide> <ide> <Infobox variant="warning" title="Changed in v3.0"> <ide><path>website/docs/usage/training.md <ide> menu: <ide> - ['Introduction', 'basics'] <ide> - ['Quickstart', 'quickstart'] <ide> - ['Config System', 'config'] <add> - ['Training Data', 'training-data'] <ide> - ['Custom Training', 'config-custom'] <ide> - ['Custom Functions', 'custom-functions'] <ide> - ['Initialization', 'initialization'] <ide> that reference this variable. <ide> <ide> </Infobox> <ide> <add>## Preparing Training Data {#training-data} <add> <add>Training data for NLP projects comes in many different formats. For some common <add>formats such as CoNLL, spaCy provides [converters](/api/cli#convert) you can use <add>from the command line. In other cases you'll have to prepare the training data <add>yourself. <add> <add>When converting training data for use in spaCy, the main thing is to create <add>[`Doc`](/api/doc) objects just like the results you want as output from the <add>pipeline. For example, if you're creating an NER pipeline, loading your <add>annotations and setting them as the `.ents` property on a `Doc` is all you need <add>to worry about. On disk the annotations will be saved as a <add>[`DocBin`](/api/docbin) in the <add>[`.spacy` format](/api/data-formats#binary-training), but the details of that <add>are handled automatically. <add> <add>Here's an example of creating a `.spacy` file from some NER annotations. <add> <add>```python <add>### preprocess.py <add>import spacy <add>from spacy.tokens import DocBin <add> <add>nlp = spacy.blank("en") <add>training_data = [ <add> ("Tokyo Tower is 333m tall.", [(0, 11, "BUILDING")]), <add>] <add># the DocBin will store the example documents <add>db = DocBin() <add>for text, annotations in training_data: <add> doc = nlp(text) <add> ents = [] <add> for start, end, label in annotations: <add> span = doc.char_span(start, end, label=label) <add> ents.append(span) <add> doc.ents = ents <add> db.add(doc) <add>db.to_disk("./train.spacy") <add>``` <add> <add>For more examples of how to convert training data from a wide variety of formats <add>for use with spaCy, look at the preprocessing steps in the <add>[tutorial projects](https://github.com/explosion/projects/tree/v3/tutorials). <add> <add><Accordion title="What about the spaCy JSON format?" id="json-annotations" spaced> <add> <add>In spaCy v2, the recommended way to store training data was in <add>[a particular JSON format](/api/data-formats#json-input), but in v3 this format <add>is deprecated. It's fine as a readable storage format, but there's no need to <add>convert your data to JSON before creating a `.spacy` file. <add> <add></Accordion> <add> <ide> ## Customizing the pipeline and training {#config-custom} <ide> <ide> ### Defining pipeline components {#config-components}
2
Python
Python
add parametrize decorator for nose
0ad966df24b514f0713e2f32e9b6baa4ad883d5f
<ide><path>numpy/testing/nose_tools/decorators.py <ide> def _deprecated_imp(*args, **kwargs): <ide> else: <ide> return f <ide> return deprecate_decorator <add> <add> <add>def parametrize(vars, input): <add> """ <add> Pytest compatibility class. This implements the simplest level of <add> pytest.mark.parametrize for use in nose as an aid in making the transition <add> to pytest. It achieves that by adding a dummy var parameter and ignoring <add> the doc_func parameter of the base class. It does not support variable <add> substitution by name, nor does it support nesting or classes. See the <add> pytest documentation for usage. <add> <add> .. versionadded:: 1.14.0 <add> <add> """ <add> from .parameterized import parameterized <add> <add> return parameterized(input) <ide><path>numpy/testing/nose_tools/parameterized.py <add>""" <add>tl;dr: all code code is licensed under simplified BSD, unless stated otherwise. <add> <add>Unless stated otherwise in the source files, all code is copyright 2010 David <add>Wolever <david@wolever.net>. All rights reserved. <add> <add>Redistribution and use in source and binary forms, with or without <add>modification, are permitted provided that the following conditions are met: <add> <add> 1. Redistributions of source code must retain the above copyright notice, <add> this list of conditions and the following disclaimer. <add> <add> 2. Redistributions in binary form must reproduce the above copyright notice, <add> this list of conditions and the following disclaimer in the documentation <add> and/or other materials provided with the distribution. <add> <add>THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR <add>IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF <add>MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO <add>EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, <add>INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, <add>BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, <add>DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF <add>LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE <add>OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF <add>ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <add> <add>The views and conclusions contained in the software and documentation are those <add>of the authors and should not be interpreted as representing official policies, <add>either expressed or implied, of David Wolever. <add> <add>""" <add>import re <add>import sys <add>import inspect <add>import warnings <add>from functools import wraps <add>from types import MethodType as MethodType <add>from collections import namedtuple <add> <add>try: <add> from collections import OrderedDict as MaybeOrderedDict <add>except ImportError: <add> MaybeOrderedDict = dict <add> <add>from unittest import TestCase <add> <add>PY3 = sys.version_info[0] == 3 <add>PY2 = sys.version_info[0] == 2 <add> <add> <add>if PY3: <add> # Python 3 doesn't have an InstanceType, so just use a dummy type. <add> class InstanceType(): <add> pass <add> lzip = lambda *a: list(zip(*a)) <add> text_type = str <add> string_types = str, <add> bytes_type = bytes <add> def make_method(func, instance, type): <add> if instance is None: <add> return func <add> return MethodType(func, instance) <add>else: <add> from types import InstanceType <add> lzip = zip <add> text_type = unicode <add> bytes_type = str <add> string_types = basestring, <add> def make_method(func, instance, type): <add> return MethodType(func, instance, type) <add> <add>_param = namedtuple("param", "args kwargs") <add> <add>class param(_param): <add> """ Represents a single parameter to a test case. <add> <add> For example:: <add> <add> >>> p = param("foo", bar=16) <add> >>> p <add> param("foo", bar=16) <add> >>> p.args <add> ('foo', ) <add> >>> p.kwargs <add> {'bar': 16} <add> <add> Intended to be used as an argument to ``@parameterized``:: <add> <add> @parameterized([ <add> param("foo", bar=16), <add> ]) <add> def test_stuff(foo, bar=16): <add> pass <add> """ <add> <add> def __new__(cls, *args , **kwargs): <add> return _param.__new__(cls, args, kwargs) <add> <add> @classmethod <add> def explicit(cls, args=None, kwargs=None): <add> """ Creates a ``param`` by explicitly specifying ``args`` and <add> ``kwargs``:: <add> <add> >>> param.explicit([1,2,3]) <add> param(*(1, 2, 3)) <add> >>> param.explicit(kwargs={"foo": 42}) <add> param(*(), **{"foo": "42"}) <add> """ <add> args = args or () <add> kwargs = kwargs or {} <add> return cls(*args, **kwargs) <add> <add> @classmethod <add> def from_decorator(cls, args): <add> """ Returns an instance of ``param()`` for ``@parameterized`` argument <add> ``args``:: <add> <add> >>> param.from_decorator((42, )) <add> param(args=(42, ), kwargs={}) <add> >>> param.from_decorator("foo") <add> param(args=("foo", ), kwargs={}) <add> """ <add> if isinstance(args, param): <add> return args <add> elif isinstance(args, string_types): <add> args = (args, ) <add> try: <add> return cls(*args) <add> except TypeError as e: <add> if "after * must be" not in str(e): <add> raise <add> raise TypeError( <add> "Parameters must be tuples, but %r is not (hint: use '(%r, )')" <add> %(args, args), <add> ) <add> <add> def __repr__(self): <add> return "param(*%r, **%r)" %self <add> <add> <add>class QuietOrderedDict(MaybeOrderedDict): <add> """ When OrderedDict is available, use it to make sure that the kwargs in <add> doc strings are consistently ordered. """ <add> __str__ = dict.__str__ <add> __repr__ = dict.__repr__ <add> <add> <add>def parameterized_argument_value_pairs(func, p): <add> """Return tuples of parameterized arguments and their values. <add> <add> This is useful if you are writing your own doc_func <add> function and need to know the values for each parameter name:: <add> <add> >>> def func(a, foo=None, bar=42, **kwargs): pass <add> >>> p = param(1, foo=7, extra=99) <add> >>> parameterized_argument_value_pairs(func, p) <add> [("a", 1), ("foo", 7), ("bar", 42), ("**kwargs", {"extra": 99})] <add> <add> If the function's first argument is named ``self`` then it will be <add> ignored:: <add> <add> >>> def func(self, a): pass <add> >>> p = param(1) <add> >>> parameterized_argument_value_pairs(func, p) <add> [("a", 1)] <add> <add> Additionally, empty ``*args`` or ``**kwargs`` will be ignored:: <add> <add> >>> def func(foo, *args): pass <add> >>> p = param(1) <add> >>> parameterized_argument_value_pairs(func, p) <add> [("foo", 1)] <add> >>> p = param(1, 16) <add> >>> parameterized_argument_value_pairs(func, p) <add> [("foo", 1), ("*args", (16, ))] <add> """ <add> argspec = inspect.getargspec(func) <add> arg_offset = 1 if argspec.args[:1] == ["self"] else 0 <add> <add> named_args = argspec.args[arg_offset:] <add> <add> result = lzip(named_args, p.args) <add> named_args = argspec.args[len(result) + arg_offset:] <add> varargs = p.args[len(result):] <add> <add> result.extend([ <add> (name, p.kwargs.get(name, default)) <add> for (name, default) <add> in zip(named_args, argspec.defaults or []) <add> ]) <add> <add> seen_arg_names = set([ n for (n, _) in result ]) <add> keywords = QuietOrderedDict(sorted([ <add> (name, p.kwargs[name]) <add> for name in p.kwargs <add> if name not in seen_arg_names <add> ])) <add> <add> if varargs: <add> result.append(("*%s" %(argspec.varargs, ), tuple(varargs))) <add> <add> if keywords: <add> result.append(("**%s" %(argspec.keywords, ), keywords)) <add> <add> return result <add> <add>def short_repr(x, n=64): <add> """ A shortened repr of ``x`` which is guaranteed to be ``unicode``:: <add> <add> >>> short_repr("foo") <add> u"foo" <add> >>> short_repr("123456789", n=4) <add> u"12...89" <add> """ <add> <add> x_repr = repr(x) <add> if isinstance(x_repr, bytes_type): <add> try: <add> x_repr = text_type(x_repr, "utf-8") <add> except UnicodeDecodeError: <add> x_repr = text_type(x_repr, "latin1") <add> if len(x_repr) > n: <add> x_repr = x_repr[:n//2] + "..." + x_repr[len(x_repr) - n//2:] <add> return x_repr <add> <add>def default_doc_func(func, num, p): <add> if func.__doc__ is None: <add> return None <add> <add> all_args_with_values = parameterized_argument_value_pairs(func, p) <add> <add> # Assumes that the function passed is a bound method. <add> descs = ["%s=%s" %(n, short_repr(v)) for n, v in all_args_with_values] <add> <add> # The documentation might be a multiline string, so split it <add> # and just work with the first string, ignoring the period <add> # at the end if there is one. <add> first, nl, rest = func.__doc__.lstrip().partition("\n") <add> suffix = "" <add> if first.endswith("."): <add> suffix = "." <add> first = first[:-1] <add> args = "%s[with %s]" %(len(first) and " " or "", ", ".join(descs)) <add> return "".join([first.rstrip(), args, suffix, nl, rest]) <add> <add>def default_name_func(func, num, p): <add> base_name = func.__name__ <add> name_suffix = "_%s" %(num, ) <add> if len(p.args) > 0 and isinstance(p.args[0], string_types): <add> name_suffix += "_" + parameterized.to_safe_name(p.args[0]) <add> return base_name + name_suffix <add> <add> <add>_test_runner_override = None <add>_test_runner_guess = False <add>_test_runners = set(["unittest", "unittest2", "nose", "nose2", "pytest"]) <add>_test_runner_aliases = { <add> "_pytest": "pytest", <add>} <add> <add>def set_test_runner(name): <add> global _test_runner_override <add> if name not in _test_runners: <add> raise TypeError( <add> "Invalid test runner: %r (must be one of: %s)" <add> %(name, ", ".join(_test_runners)), <add> ) <add> _test_runner_override = name <add> <add>def detect_runner(): <add> """ Guess which test runner we're using by traversing the stack and looking <add> for the first matching module. This *should* be reasonably safe, as <add> it's done during test disocvery where the test runner should be the <add> stack frame immediately outside. """ <add> if _test_runner_override is not None: <add> return _test_runner_override <add> global _test_runner_guess <add> if _test_runner_guess is False: <add> stack = inspect.stack() <add> for record in reversed(stack): <add> frame = record[0] <add> module = frame.f_globals.get("__name__").partition(".")[0] <add> if module in _test_runner_aliases: <add> module = _test_runner_aliases[module] <add> if module in _test_runners: <add> _test_runner_guess = module <add> break <add> if record[1].endswith("python2.6/unittest.py"): <add> _test_runner_guess = "unittest" <add> break <add> else: <add> _test_runner_guess = None <add> return _test_runner_guess <add> <add>class parameterized(object): <add> """ Parameterize a test case:: <add> <add> class TestInt(object): <add> @parameterized([ <add> ("A", 10), <add> ("F", 15), <add> param("10", 42, base=42) <add> ]) <add> def test_int(self, input, expected, base=16): <add> actual = int(input, base=base) <add> assert_equal(actual, expected) <add> <add> @parameterized([ <add> (2, 3, 5) <add> (3, 5, 8), <add> ]) <add> def test_add(a, b, expected): <add> assert_equal(a + b, expected) <add> """ <add> <add> def __init__(self, input, doc_func=None): <add> self.get_input = self.input_as_callable(input) <add> self.doc_func = doc_func or default_doc_func <add> <add> def __call__(self, test_func): <add> self.assert_not_in_testcase_subclass() <add> <add> @wraps(test_func) <add> def wrapper(test_self=None): <add> test_cls = test_self and type(test_self) <add> if test_self is not None: <add> if issubclass(test_cls, InstanceType): <add> raise TypeError(( <add> "@parameterized can't be used with old-style classes, but " <add> "%r has an old-style class. Consider using a new-style " <add> "class, or '@parameterized.expand' " <add> "(see http://stackoverflow.com/q/54867/71522 for more " <add> "information on old-style classes)." <add> ) %(test_self, )) <add> <add> original_doc = wrapper.__doc__ <add> for num, args in enumerate(wrapper.parameterized_input): <add> p = param.from_decorator(args) <add> unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p) <add> try: <add> wrapper.__doc__ = nose_tuple[0].__doc__ <add> # Nose uses `getattr(instance, test_func.__name__)` to get <add> # a method bound to the test instance (as opposed to a <add> # method bound to the instance of the class created when <add> # tests were being enumerated). Set a value here to make <add> # sure nose can get the correct test method. <add> if test_self is not None: <add> setattr(test_cls, test_func.__name__, unbound_func) <add> yield nose_tuple <add> finally: <add> if test_self is not None: <add> delattr(test_cls, test_func.__name__) <add> wrapper.__doc__ = original_doc <add> wrapper.parameterized_input = self.get_input() <add> wrapper.parameterized_func = test_func <add> test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, ) <add> return wrapper <add> <add> def param_as_nose_tuple(self, test_self, func, num, p): <add> nose_func = wraps(func)(lambda *args: func(*args[:-1], **args[-1])) <add> nose_func.__doc__ = self.doc_func(func, num, p) <add> # Track the unbound function because we need to setattr the unbound <add> # function onto the class for nose to work (see comments above), and <add> # Python 3 doesn't let us pull the function out of a bound method. <add> unbound_func = nose_func <add> if test_self is not None: <add> # Under nose on Py2 we need to return an unbound method to make <add> # sure that the `self` in the method is properly shared with the <add> # `self` used in `setUp` and `tearDown`. But only there. Everyone <add> # else needs a bound method. <add> func_self = ( <add> None if PY2 and detect_runner() == "nose" else <add> test_self <add> ) <add> nose_func = make_method(nose_func, func_self, type(test_self)) <add> return unbound_func, (nose_func, ) + p.args + (p.kwargs or {}, ) <add> <add> def assert_not_in_testcase_subclass(self): <add> parent_classes = self._terrible_magic_get_defining_classes() <add> if any(issubclass(cls, TestCase) for cls in parent_classes): <add> raise Exception("Warning: '@parameterized' tests won't work " <add> "inside subclasses of 'TestCase' - use " <add> "'@parameterized.expand' instead.") <add> <add> def _terrible_magic_get_defining_classes(self): <add> """ Returns the set of parent classes of the class currently being defined. <add> Will likely only work if called from the ``parameterized`` decorator. <add> This function is entirely @brandon_rhodes's fault, as he suggested <add> the implementation: http://stackoverflow.com/a/8793684/71522 <add> """ <add> stack = inspect.stack() <add> if len(stack) <= 4: <add> return [] <add> frame = stack[4] <add> code_context = frame[4] and frame[4][0].strip() <add> if not (code_context and code_context.startswith("class ")): <add> return [] <add> _, _, parents = code_context.partition("(") <add> parents, _, _ = parents.partition(")") <add> return eval("[" + parents + "]", frame[0].f_globals, frame[0].f_locals) <add> <add> @classmethod <add> def input_as_callable(cls, input): <add> if callable(input): <add> return lambda: cls.check_input_values(input()) <add> input_values = cls.check_input_values(input) <add> return lambda: input_values <add> <add> @classmethod <add> def check_input_values(cls, input_values): <add> # Explicitly convery non-list inputs to a list so that: <add> # 1. A helpful exception will be raised if they aren't iterable, and <add> # 2. Generators are unwrapped exactly once (otherwise `nosetests <add> # --processes=n` has issues; see: <add> # https://github.com/wolever/nose-parameterized/pull/31) <add> if not isinstance(input_values, list): <add> input_values = list(input_values) <add> return [ param.from_decorator(p) for p in input_values ] <add> <add> @classmethod <add> def expand(cls, input, name_func=None, doc_func=None, **legacy): <add> """ A "brute force" method of parameterizing test cases. Creates new <add> test cases and injects them into the namespace that the wrapped <add> function is being defined in. Useful for parameterizing tests in <add> subclasses of 'UnitTest', where Nose test generators don't work. <add> <add> >>> @parameterized.expand([("foo", 1, 2)]) <add> ... def test_add1(name, input, expected): <add> ... actual = add1(input) <add> ... assert_equal(actual, expected) <add> ... <add> >>> locals() <add> ... 'test_add1_foo_0': <function ...> ... <add> >>> <add> """ <add> <add> if "testcase_func_name" in legacy: <add> warnings.warn("testcase_func_name= is deprecated; use name_func=", <add> DeprecationWarning, stacklevel=2) <add> if not name_func: <add> name_func = legacy["testcase_func_name"] <add> <add> if "testcase_func_doc" in legacy: <add> warnings.warn("testcase_func_doc= is deprecated; use doc_func=", <add> DeprecationWarning, stacklevel=2) <add> if not doc_func: <add> doc_func = legacy["testcase_func_doc"] <add> <add> doc_func = doc_func or default_doc_func <add> name_func = name_func or default_name_func <add> <add> def parameterized_expand_wrapper(f, instance=None): <add> stack = inspect.stack() <add> frame = stack[1] <add> frame_locals = frame[0].f_locals <add> <add> paramters = cls.input_as_callable(input)() <add> for num, p in enumerate(paramters): <add> name = name_func(f, num, p) <add> frame_locals[name] = cls.param_as_standalone_func(p, f, name) <add> frame_locals[name].__doc__ = doc_func(f, num, p) <add> <add> f.__test__ = False <add> return parameterized_expand_wrapper <add> <add> @classmethod <add> def param_as_standalone_func(cls, p, func, name): <add> @wraps(func) <add> def standalone_func(*a): <add> return func(*(a + p.args), **p.kwargs) <add> standalone_func.__name__ = name <add> <add> # place_as is used by py.test to determine what source file should be <add> # used for this test. <add> standalone_func.place_as = func <add> <add> # Remove __wrapped__ because py.test will try to look at __wrapped__ <add> # to determine which parameters should be used with this test case, <add> # and obviously we don't need it to do any parameterization. <add> try: <add> del standalone_func.__wrapped__ <add> except AttributeError: <add> pass <add> return standalone_func <add> <add> @classmethod <add> def to_safe_name(cls, s): <add> return str(re.sub("[^a-zA-Z0-9_]+", "_", s))
2
Text
Text
fix capitalization of project name in readme.md
a31bf266c19885cd4895296e9fb3a9d58a3e077c
<ide><path>README.md <ide> yarn add webpack --dev <ide> <ide> <h2 align="center">Introduction</h2> <ide> <del>> This README reflects Webpack v2.x and v3.x. The Webpack v1.x documentation has been deprecated and deleted. <add>> This README reflects webpack v2.x and v3.x. The webpack v1.x documentation has been deprecated and deleted. <ide> <ide> webpack is a bundler for modules. The main purpose is to bundle JavaScript <ide> files for usage in a browser, yet it is also capable of transforming, bundling,
1
Go
Go
add missing lock in processevent
6c03aa317404703a300ef25c3b5dc18d8e9cc64c
<ide><path>daemon/monitor.go <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> daemon.LogContainerEvent(c, "oom") <ide> case libcontainerd.EventExit: <ide> if int(ei.Pid) == c.Pid { <add> c.Lock() <ide> _, _, err := daemon.containerd.DeleteTask(context.Background(), c.ID) <ide> if err != nil { <ide> logrus.WithError(err).Warnf("failed to delete container %s from containerd", c.ID) <ide> } <ide> <del> c.Lock() <ide> c.StreamConfig.Wait() <ide> c.Reset(false) <ide> <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> c.SetStopped(&exitStatus) <ide> defer daemon.autoRemove(c) <ide> } <add> defer c.Unlock() // needs to be called before autoRemove <ide> <ide> // cancel healthcheck here, they will be automatically <ide> // restarted if/when the container is started again <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> } <ide> } <ide> if err != nil { <add> c.Lock() <ide> c.SetStopped(&exitStatus) <add> c.Unlock() <ide> defer daemon.autoRemove(c) <ide> if err != restartmanager.ErrRestartCanceled { <ide> logrus.Errorf("restartmanger wait error: %+v", err) <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> } <ide> <ide> daemon.setStateCounter(c) <del> defer c.Unlock() <ide> if err := c.CheckpointTo(daemon.containersReplica); err != nil { <ide> return err <ide> }
1
Javascript
Javascript
add test for cluster.worker.destroy()
9c992bdb752063913067feb533cd3db37d2e4d01
<ide><path>test/simple/test-cluster-worker-destroy.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>/* <add> * The goal of this test is to cover the Workers' implementation of <add> * Worker.prototype.destroy. Worker.prototype.destroy is called within <add> * the worker's context: once when the worker is still connected to the <add> * master, and another time when it's not connected to it, so that we cover <add> * both code paths. <add> */ <add> <add>require('../common'); <add>var cluster = require('cluster'); <add>var assert = require('assert'); <add> <add>var worker1, worker2, workerExited, workerDisconnected; <add> <add>if (cluster.isMaster) { <add> worker1 = cluster.fork(); <add> worker2 = cluster.fork(); <add> <add> workerExited = 0; <add> workerDisconnected = 0; <add> <add> [worker1, worker2].forEach(function(worker) { <add> worker.on('disconnect', ondisconnect); <add> worker.on('exit', onexit); <add> }); <add> <add> process.on('exit', onProcessExit); <add> <add>} else { <add> if (cluster.worker.id === 1) { <add> // Call destroy when worker is disconnected <add> cluster.worker.process.on('disconnect', function() { <add> cluster.worker.destroy(); <add> }); <add> <add> cluster.worker.disconnect(); <add> } else { <add> // Call destroy when worker is not disconnected yet <add> cluster.worker.destroy(); <add> } <add>} <add> <add>function onProcessExit() { <add> assert.equal(workerExited, <add> 2, <add> 'When master exits, all workers should have exited too'); <add> assert.equal(workerDisconnected, <add> 2, <add> 'When master exits, all workers should have disconnected'); <add>} <add> <add>function ondisconnect() { <add> ++workerDisconnected; <add>} <add> <add>function onexit() { <add> ++workerExited; <add>}
1
PHP
PHP
remove duplication of throws
bb821a426d0589263397144340ae0864978c99d6
<ide><path>lib/Cake/Configure/IniReader.php <ide> public function __construct($path = null, $section = null) { <ide> * @return array Parsed configuration values. <ide> * @throws ConfigureException when files don't exist. <ide> * Or when files contain '..' as this could lead to abusive reads. <del> * @throws ConfigureException <ide> */ <ide> public function read($key) { <ide> if (strpos($key, '..') !== false) {
1
Javascript
Javascript
remove unnecessary seq
cda7725188b745115879486303331e44fb55f1e1
<ide><path>src/Map.js <ide> class HashCollisionNode { <ide> } <ide> <ide> get(shift, hash, key, notFound) { <del> var idx = Sequence(this.keys).indexOf(key); <add> var idx = this.keys.indexOf(key); <ide> return idx === -1 ? notFound : this.values[idx]; <ide> } <ide>
1
Javascript
Javascript
add nodes to documentfragments before attaching
1f2d9b208d72b0461e2550c664c26728331d028e
<ide><path>src/renderers/dom/client/utils/DOMLazyTree.js <ide> function insertTreeChildren(tree) { <ide> <ide> var insertTreeBefore = createMicrosoftUnsafeLocalFunction( <ide> function(parentNode, tree, referenceNode) { <del> parentNode.insertBefore(tree.node, referenceNode); <del> insertTreeChildren(tree); <add> // Document Fragments in IE11, Edge (and possibly others) won't update <add> // correctly if they are already inserted. So we have to break out of our <add> // lazy approach and append children to the fragment before inserting it. <add> if (tree.node.nodeType === 11) { <add> insertTreeChildren(tree); <add> parentNode.insertBefore(tree.node, referenceNode); <add> } else { <add> parentNode.insertBefore(tree.node, referenceNode); <add> insertTreeChildren(tree); <add> } <ide> } <ide> ); <ide>
1
Ruby
Ruby
push more mutations outside the factory method
86588f9bc4d6214a8e625f97fcadb246592c41c0
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> def self.build(model, name, scope, options, &block) <ide> reflection = builder.build <ide> builder.define_accessors model.generated_feature_methods <ide> builder.define_callbacks model, reflection <add> builder.define_extensions model <ide> reflection <ide> end <ide> <ide> def validate_options <ide> options.assert_valid_keys(valid_options) <ide> end <ide> <add> def define_extensions(model) <add> end <add> <ide> def define_callbacks(model, reflection) <ide> add_before_destroy_callbacks(model, name) if options[:dependent] <ide> Association.extensions.each do |extension| <ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> def valid_options <ide> <ide> attr_reader :block_extension <ide> <del> def initialize(*args) <del> super(*args) <add> def initialize(model, name, scope, options) <add> super <ide> @mod = nil <ide> if block_given? <ide> @mod = Module.new(&Proc.new) <ide> @scope = wrap_scope @scope, @mod <ide> end <ide> end <ide> <del> def build <del> define_extensions(model) <del> reflection = super <del> reflection <del> end <del> <ide> def define_callbacks(model, reflection) <ide> super <ide> CALLBACKS.each { |callback_name| define_callback(model, callback_name) }
2
Text
Text
add artelys to the list of airflow users
aa00e9bcd4ec16f42338b30d29e87ccda8eecf82
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Apigee](https://apigee.com) [[@btallman](https://github.com/btallman)] <ide> 1. [Arquivei](https://www.arquivei.com.br/) [[@arquivei](https://github.com/arquivei)] <ide> 1. [Arrive](https://www.arrive.com/) <add>1. [Artelys](https://www.artelys.com/) [[@fortierq](https://github.com/fortierq)] <ide> 1. [Asana](https://asana.com/) [[@chang](https://github.com/chang), [@dima-asana](https://github.com/dima-asana), [@jdavidheiser](https://github.com/jdavidheiser), [@ricardoandresrojas](https://github.com/ricardoandresrojas)] <ide> 1. [Astronomer](http://www.astronomer.io) [[@schnie](https://github.com/schnie), [@ashb](https://github.com/ashb), [@kaxil](https://github.com/kaxil), [@dimberman](https://github.com/dimberman), [@andriisoldatenko](https://github.com/andriisoldatenko), [@ryw](https://github.com/ryw), [@ryanahamilton](https://github.com/ryanahamilton), [@jhtimmins](https://github.com/jhtimmins), [@vikramkoka](https://github.com/vikramkoka)] <ide> 1. [Auth0](https://auth0.com) [[@scottypate](https://github.com/scottypate)], [[@dm03514](https://github.com/dm03514)], [[@karangale](https://github.com/karangale)]
1
Go
Go
retrieve all filesystems on startup at once
bad25ccf978b56da6fa181439504ab33906524cd
<ide><path>daemon/graphdriver/zfs/zfs.go <ide> func Init(base string, opt []string) (graphdriver.Driver, error) { <ide> <ide> zfs.SetLogger(new(Logger)) <ide> <del> dataset, err := zfs.GetDataset(options.fsName) <add> filesystems, err := zfs.Filesystems(options.fsName) <ide> if err != nil { <del> return nil, fmt.Errorf("Cannot open %s", options.fsName) <add> return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err) <add> } <add> <add> filesystemsCache := make(map[string]bool, len(filesystems)) <add> var rootDataset *zfs.Dataset <add> for _, fs := range filesystems { <add> if fs.Name == options.fsName { <add> rootDataset = fs <add> } <add> filesystemsCache[fs.Name] = true <add> } <add> <add> if rootDataset == nil { <add> return nil, fmt.Errorf("BUG: zfs get all -t filesystems -rHp '%s' should contain '%s'", options.fsName, options.fsName) <ide> } <ide> <ide> d := &Driver{ <del> dataset: dataset, <del> options: options, <add> dataset: rootDataset, <add> options: options, <add> filesystemsCache: filesystemsCache, <ide> } <ide> return graphdriver.NaiveDiffDriver(d), nil <ide> } <ide> func lookupZfsDataset(rootdir string) (string, error) { <ide> } <ide> <ide> type Driver struct { <del> dataset *zfs.Dataset <del> options ZfsOptions <add> dataset *zfs.Dataset <add> options ZfsOptions <add> filesystemsCache map[string]bool <ide> } <ide> <ide> func (d *Driver) String() string { <ide> func (d *Driver) Put(id string) error { <ide> } <ide> <ide> func (d *Driver) Exists(id string) bool { <del> _, err := zfs.GetDataset(d.ZfsPath(id)) <del> return err == nil <add> return d.filesystemsCache[d.ZfsPath(id)] == true <ide> }
1
Python
Python
fix bug in pegasus converter
0ec63afec2558d76312bf6fddc3f171ceebfa584
<ide><path>src/transformers/convert_pegasus_tf_to_pytorch.py <ide> <ide> def rename_state_dict_key(k): <ide> <del> for pegasus_name, bart_name in PATTERNS: <del> k = k.replace(pegasus_name, bart_name) <add> for pegasus_name, hf_name in PATTERNS: <add> k = k.replace(pegasus_name, hf_name) <ide> return k <ide> <ide> <ide> def rename_state_dict_key(k): <ide> # TODO(SS): one constant <ide> <ide> <del>def convert_pegasus_to_bart(tf_weights: dict, cfg_updates: dict) -> PegasusForConditionalGeneration: <add>def convert_pegasus(tf_weights: dict, cfg_updates: dict) -> PegasusForConditionalGeneration: <ide> cfg_kwargs = DEFAULTS.copy() <ide> cfg_kwargs.update(cfg_updates) <del> <del> cfg = PegasusConfig(**cfg_updates) <del> bart = PegasusForConditionalGeneration(cfg) <del> sd = bart.model.state_dict() <add> cfg = PegasusConfig(**cfg_kwargs) <add> torch_model = PegasusForConditionalGeneration(cfg) <add> sd = torch_model.model.state_dict() <ide> mapping = {} <ide> for k, v in tf_weights.items(): <ide> new_k = rename_state_dict_key(k) <ide> def convert_pegasus_to_bart(tf_weights: dict, cfg_updates: dict) -> PegasusForCo <ide> mapping["decoder.embed_tokens.weight"] = mapping["shared.weight"] <ide> empty_biases = {k: torch.zeros_like(v) for k, v in sd.items() if k.endswith("bias") and k not in mapping} <ide> mapping.update(**empty_biases) <del> missing, extra = bart.model.load_state_dict(mapping, strict=False) <add> missing, extra = torch_model.model.load_state_dict(mapping, strict=False) <ide> unexpected_missing = [ <ide> k for k in missing if k not in ["encoder.embed_positions.weight", "decoder.embed_positions.weight"] <ide> ] <ide> assert unexpected_missing == [], f"no matches found for the following torch keys {unexpected_missing}" <ide> assert extra == [], f"no matches found for the following tf keys {extra}" <del> return bart <add> return torch_model <ide> <ide> <ide> def get_tf_weights_as_numpy(path="./ckpt/aeslc/model.ckpt-32000") -> Dict: <ide> def convert_pegasus_ckpt_to_pytorch(ckpt_path: str, save_dir: str): <ide> cfg_updates = task_specific_params[f"summarization_{dataset}"] <ide> if dataset == "large": <ide> cfg_updates["task_specific_params"] = task_specific_params <del> torch_model = convert_pegasus_to_bart(tf_weights, cfg_updates) <add> torch_model = convert_pegasus(tf_weights, cfg_updates) <ide> torch_model.save_pretrained(save_dir) <ide> sd = torch_model.state_dict() <ide> sd.pop("model.decoder.embed_positions.weight")
1
Javascript
Javascript
use the new `any` event function
3c932c5f8e3b92ab9230b5c4d6e84b29ad82b36a
<ide><path>src/js/player.js <ide> class Player extends Component { <ide> // if the `sourceset` `src` was an empty string <ide> // wait for a `loadstart` to update the cache to `currentSrc`. <ide> // If a sourceset happens before a `loadstart`, we reset the state <del> // as this function will be called again. <ide> if (!event.src) { <del> const updateCache = (e) => { <del> if (e.type !== 'sourceset') { <del> const techSrc = this.techGet('currentSrc'); <del> <del> this.lastSource_.tech = techSrc; <del> this.updateSourceCaches_(techSrc); <add> this.tech_.any(['sourceset', 'loadstart'], (e) => { <add> // if a sourceset happens before a `loadstart` there <add> // is nothing to do as this `handleTechSourceset_` <add> // will be called again and this will be handled there. <add> if (e.type === 'sourceset') { <add> return; <ide> } <ide> <del> this.tech_.off(['sourceset', 'loadstart'], updateCache); <del> }; <add> const techSrc = this.techGet('currentSrc'); <ide> <del> this.tech_.one(['sourceset', 'loadstart'], updateCache); <add> this.lastSource_.tech = techSrc; <add> this.updateSourceCaches_(techSrc); <add> }); <ide> } <ide> } <ide> this.lastSource_ = {player: this.currentSource().src, tech: event.src}; <ide><path>src/js/tracks/text-track.js <ide> const loadTrack = function(src, track) { <ide> if (track.tech_) { <ide> // to prevent use before define eslint error, we define loadHandler <ide> // as a let here <del> let loadHandler; <del> const errorHandler = () => { <del> log.error(`vttjs failed to load, stopping trying to process ${track.src}`); <del> track.tech_.off('vttjsloaded', loadHandler); <del> }; <del> <del> loadHandler = () => { <del> track.tech_.off('vttjserror', errorHandler); <add> track.tech_.any(['vttjsloaded', 'vttjserror'], (event) => { <add> if (event.type === 'vttjserror') { <add> log.error(`vttjs failed to load, stopping trying to process ${track.src}`); <add> return; <add> } <ide> return parseCues(responseBody, track); <del> }; <del> <del> track.tech_.one('vttjsloaded', loadHandler); <del> track.tech_.one('vttjserror', errorHandler); <add> }); <ide> } <ide> } else { <ide> parseCues(responseBody, track); <ide><path>test/unit/tracks/text-track.test.js <ide> QUnit.test('stops processing if vttjs loading errored out', function(assert) { <ide> const errorSpy = sinon.spy(); <ide> const oldVTT = window.WebVTT; <ide> const oldLogError = log.error; <del> const parserCreated = false; <ide> const reqs = []; <ide> <ide> window.xhr.onCreate = function(req) { <ide> QUnit.test('stops processing if vttjs loading errored out', function(assert) { <ide> <ide> reqs.pop().respond(200, null, 'WEBVTT\n'); <ide> <del> assert.ok(!parserCreated, 'WebVTT is not loaded, do not try to parse yet'); <add> testTech.trigger('vttjserror'); <add> <add> assert.equal(errorSpy.callCount, 1, 'vttjs failed to load, so log.error was called'); <ide> <ide> testTech.trigger('vttjserror'); <del> const offSpyCall = testTech.off.getCall(0); <del> <del> assert.ok(errorSpy.called, 'vttjs failed to load, so log.error was called'); <del> if (errorSpy.called) { <del> assert.ok( <del> /^vttjs failed to load, stopping trying to process/.test(errorSpy.getCall(0).args[0]), <del> 'log.error was called with the expected message' <del> ); <del> } <del> assert.ok(!parserCreated, 'WebVTT is not loaded, do not try to parse yet'); <del> assert.ok(offSpyCall, 'tech.off was called'); <add> <add> // vttjserror not called again <add> assert.equal(errorSpy.callCount, 1, 'vttjserror handler not called again'); <ide> <ide> clock.restore(); <ide> window.WebVTT = oldVTT;
3
Text
Text
add virtualenv to start of tutorial
247a422a64378c968f0972b1797b919ae03296bb
<ide><path>docs/tutorial/1-serialization.md <ide> This tutorial will walk you through the building blocks that make up REST framew <ide> <ide> ## Getting started <ide> <add>Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. <add> <add> mkdir -p ~/.env <add> virtualenv --no-site-packages ~/.env/djangorestframework <add> source ~/.env/djangorestframework/env/bin/activate <add> <add>Now that we're inside a virtualenv environment, we can install our packages requirements. <add> <add> pip install django <add> pip install djangorestframework <add> <add>Now we're ready to get coding. <ide> To get started, let's create a new project to work with. <ide> <ide> django-admin.py startproject tutorial <ide> We're doing okay so far, we've got a serialization API that feels pretty similar <ide> <ide> Our API views don't do anything particularly special at the moment, beyond serve `json` responses, and there's some error handling edge cases we'd still like to clean up, but it's a functioning Web API. <ide> <del>We'll see how we can start to improve things in [part 2 of the tutorial][1]. <add>We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. <ide> <del>[1]: 2-requests-and-responses.md <ide>\ No newline at end of file <add>[virtualenv]: http://www.virtualenv.org/en/latest/index.html <add>[tut-2]: 2-requests-and-responses.md <ide>\ No newline at end of file
1
Javascript
Javascript
add error code on null byte paths
03ee4d854744e83f99bc5857b98f75139c448564
<ide><path>lib/fs.js <ide> function assertEncoding(encoding) { <ide> function nullCheck(path, callback) { <ide> if (('' + path).indexOf('\u0000') !== -1) { <ide> var er = new Error('Path must be a string without null bytes.'); <add> er.code = 'ENOENT'; <ide> if (!callback) <ide> throw er; <ide> process.nextTick(function() { <ide><path>test/parallel/test-fs-null-bytes.js <ide> function check(async, sync) { <ide> var argsSync = Array.prototype.slice.call(arguments, 2); <ide> var argsAsync = argsSync.concat(function(er) { <ide> assert(er && er.message.match(expected)); <add> assert.equal(er.code, 'ENOENT'); <ide> }); <ide> <ide> if (sync)
2
Ruby
Ruby
fix typo in caching docs
9b204641c002317d097261c753490cced3dec40c
<ide><path>actionpack/lib/action_controller/caching.rb <ide> def caching_allowed <ide> # "jamis.somewhere.com/lists/" -- which is a helpful way of assisting the subdomain-as-account-key pattern. <ide> # <ide> # Different representations of the same resource, e.g. <tt>http://david.somewhere.com/lists</tt> and <tt>http://david.somewhere.com/lists.xml</tt> <del> # are treated like separate requests and so are cached separately. Keep in mine when expiring an action cache that <tt>:action => 'lists'</tt> is not the same <add> # are treated like separate requests and so are cached separately. Keep in mind when expiring an action cache that <tt>:action => 'lists'</tt> is not the same <ide> # as <tt>:action => 'list', :format => :xml</tt>. <ide> module Actions <ide> def self.included(base) #:nodoc:
1
Javascript
Javascript
use the watchpath api in specs
9c874c921e31098bf9a6216fb6056dd46f9377b2
<ide><path>spec/path-watcher-spec.js <ide> import fsCb from 'fs-plus' <ide> import path from 'path' <ide> <ide> import {CompositeDisposable} from 'event-kit' <del>import PathWatcher, {stopAllWatchers} from '../src/path-watcher' <add>import watchPath, {stopAllWatchers} from '../src/path-watcher' <ide> <ide> tempCb.track() <ide> <ide> describe('PathWatcher', function () { <ide> }) <ide> } <ide> <del> describe('new PatchWatcher()', function () { <add> describe('watchPath()', function () { <ide> it('resolves getStartPromise() when the watcher begins listening', async function () { <ide> const rootDir = await temp.mkdir('atom-fsmanager-test-') <ide> <del> const watcher = new PathWatcher(rootDir) <del> watcher.onDidChange(() => {}) <del> <del> await watcher.getStartPromise() <del> }) <del> <del> it('does not start actually watching until an onDidChange subscriber is registered', async function () { <del> const rootDir = await temp.mkdir('atom-fsmanager-test-') <del> const watcher = new PathWatcher(rootDir) <del> <del> let started = false <del> const startPromise = watcher.getStartPromise().then(() => { <del> started = true <del> }) <del> <del> expect(watcher.native).toBe(null) <del> expect(watcher.normalizedPath).toBe(null) <del> expect(started).toBe(false) <del> <del> await watcher.getNormalizedPathPromise() <del> <del> expect(watcher.native).toBe(null) <del> expect(watcher.normalizedPath).not.toBe(null) <del> expect(started).toBe(false) <del> <del> watcher.onDidChange(() => {}) <del> await startPromise <del> <del> expect(watcher.native).not.toBe(null) <del> expect(started).toBe(true) <del> }) <del> <del> it('automatically stops and removes the watcher when all onDidChange subscribers dispose', async function () { <del> const dir = await temp.mkdir('atom-fsmanager-test-') <del> const watcher = new PathWatcher(dir) <del> <del> const sub0 = watcher.onDidChange(() => {}) <del> const sub1 = watcher.onDidChange(() => {}) <del> <add> const watcher = watchPath(rootDir, {}, () => {}) <ide> await watcher.getStartPromise() <del> const native = watcher.native <del> expect(native).not.toBe(null) <del> expect(native.isRunning()).toBe(true) <del> <del> sub0.dispose() <del> expect(watcher.native).toBe(native) <del> expect(native.isRunning()).toBe(true) <del> <del> sub1.dispose() <del> expect(watcher.native).toBeNull() <del> expect(native.isRunning()).toBe(false) <ide> }) <ide> <ide> it('reuses an existing native watcher and resolves getStartPromise immediately if attached to a running watcher', async function () { <ide> const rootDir = await temp.mkdir('atom-fsmanager-test-') <ide> <del> const watcher0 = new PathWatcher(rootDir) <del> watcher0.onDidChange(() => {}) <add> const watcher0 = watchPath(rootDir, {}, () => {}) <ide> await watcher0.getStartPromise() <ide> <del> const watcher1 = new PathWatcher(rootDir) <del> watcher1.onDidChange(() => {}) <add> const watcher1 = watchPath(rootDir, {}, () => {}) <ide> await watcher1.getStartPromise() <ide> <ide> expect(watcher0.native).toBe(watcher1.native) <ide> describe('PathWatcher', function () { <ide> it("reuses existing native watchers even while they're still starting", async function () { <ide> const rootDir = await temp.mkdir('atom-fsmanager-test-') <ide> <del> const watcher0 = new PathWatcher(rootDir) <del> watcher0.onDidChange(() => {}) <add> const watcher0 = watchPath(rootDir, {}, () => {}) <ide> await watcher0.getAttachedPromise() <ide> expect(watcher0.native.isRunning()).toBe(false) <ide> <del> const watcher1 = new PathWatcher(rootDir) <del> watcher1.onDidChange(() => {}) <add> const watcher1 = watchPath(rootDir, {}, () => {}) <ide> await watcher1.getAttachedPromise() <ide> <ide> expect(watcher0.native).toBe(watcher1.native) <ide> describe('PathWatcher', function () { <ide> it("doesn't attach new watchers to a native watcher that's stopping", async function () { <ide> const rootDir = await temp.mkdir('atom-fsmanager-test-') <ide> <del> const watcher0 = new PathWatcher(rootDir) <del> const sub = watcher0.onDidChange(() => {}) <add> const watcher0 = watchPath(rootDir, {}, () => {}) <ide> await watcher0.getStartPromise() <ide> const native0 = watcher0.native <ide> <del> sub.dispose() <add> watcher0.dispose() <ide> <del> const watcher1 = new PathWatcher(rootDir) <del> watcher1.onDidChange(() => {}) <add> const watcher1 = watchPath(rootDir, {}, () => {}) <ide> <ide> expect(watcher1.native).not.toBe(native0) <ide> }) <ide> describe('PathWatcher', function () { <ide> await fs.mkdir(subDir) <ide> <ide> // Keep the watchers alive with an undisposed subscription <del> const rootWatcher = new PathWatcher(rootDir) <del> rootWatcher.onDidChange(() => {}) <del> const childWatcher = new PathWatcher(subDir) <del> childWatcher.onDidChange(() => {}) <add> const rootWatcher = watchPath(rootDir, {}, () => {}) <add> const childWatcher = watchPath(subDir, {}, () => {}) <ide> <ide> await Promise.all([ <ide> rootWatcher.getStartPromise(), <ide> describe('PathWatcher', function () { <ide> ]) <ide> <ide> // Begin the child watchers and keep them alive <del> const subWatcher0 = new PathWatcher(subDir0) <del> subWatcher0.onDidChange(() => {}) <add> const subWatcher0 = watchPath(subDir0, {}, () => {}) <ide> const subWatcherChanges0 = waitForChanges(subWatcher0, subFile0) <ide> <del> const subWatcher1 = new PathWatcher(subDir1) <del> subWatcher1.onDidChange(() => {}) <add> const subWatcher1 = watchPath(subDir1, {}, () => {}) <ide> const subWatcherChanges1 = waitForChanges(subWatcher1, subFile1) <ide> <ide> await Promise.all( <ide> describe('PathWatcher', function () { <ide> expect(subWatcher0.native).not.toBe(subWatcher1.native) <ide> <ide> // Create the parent watcher <del> const parentWatcher = new PathWatcher(parentDir) <add> const parentWatcher = watchPath(parentDir, {}, () => {}) <ide> const parentWatcherChanges = waitForChanges(parentWatcher, rootFile, subFile0, subFile1) <ide> <ide> await parentWatcher.getStartPromise()
1
Python
Python
fix html template path in glanceshtml class
94d016ab517a8ba5dd47a1bff7105d8ba7a8a4cc
<ide><path>glances/glances.py <ide> def __init__(self, htmlfolder="/usr/share", refresh_time=1): <ide> <ide> # Set the templates path <ide> environment = jinja2.Environment( <del> loader=jinja2.FileSystemLoader(self.root_path + 'html'), <add> loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/html'), <ide> extensions=['jinja2.ext.loopcontrols']) <ide> <ide> # Open the template
1
PHP
PHP
make username customizable during login
37927a9f732097e484a67fac66b6aaee7dc61fef
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesUsers.php <ide> public function getLogin() <ide> public function postLogin(Request $request) <ide> { <ide> $this->validate($request, [ <del> 'email' => 'required|email', 'password' => 'required', <add> $this->loginUsername() => 'required', 'password' => 'required', <ide> ]); <ide> <ide> $throttles = in_array( <ide> public function postLogin(Request $request) <ide> } <ide> <ide> return redirect($this->loginPath()) <del> ->withInput($request->only('email', 'remember')) <add> ->withInput($request->only($this->loginUsername(), 'remember')) <ide> ->withErrors([ <del> 'email' => $this->getFailedLoginMessage(), <add> $this->loginUsername() => $this->getFailedLoginMessage(), <ide> ]); <ide> } <ide> <ide> public function postLogin(Request $request) <ide> */ <ide> protected function getCredentials(Request $request) <ide> { <del> return $request->only('email', 'password'); <add> return $request->only($this->loginUsername(), 'password'); <ide> } <ide> <ide> /** <ide> public function loginPath() <ide> { <ide> return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login'; <ide> } <add> <add> /** <add> * Get the login username to be used by the controller. <add> * <add> * @return string <add> */ <add> public function loginUsername() <add> { <add> return property_exists($this, 'username') ? $this->username : 'email'; <add> } <ide> } <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php <ide> protected function sendLockoutResponse(Request $request) <ide> $seconds = (int) Cache::get($this->getLoginLockExpirationKey($request)) - time(); <ide> <ide> return redirect($this->loginPath()) <del> ->withInput($request->only('email', 'remember')) <add> ->withInput($request->only($this->loginUsername(), 'remember')) <ide> ->withErrors([ <del> 'email' => 'Too many login attempts. Please try again in '.$seconds.' seconds.', <add> $this->loginUsername() => 'Too many login attempts. Please try again in '.$seconds.' seconds.', <ide> ]); <ide> } <ide> <ide> protected function clearLoginAttempts(Request $request) <ide> */ <ide> protected function getLoginAttemptsKey(Request $request) <ide> { <del> return 'login:attempts:'.md5($request->email.$request->ip()); <add> $username = $request->input($this->loginUsername()); <add> <add> return 'login:attempts:'.md5($username.$request->ip()); <ide> } <ide> <ide> /** <ide> protected function getLoginAttemptsKey(Request $request) <ide> */ <ide> protected function getLoginLockExpirationKey(Request $request) <ide> { <del> return 'login:expiration:'.md5($request->email.$request->ip()); <add> $username = $request->input($this->loginUsername()); <add> <add> return 'login:expiration:'.md5($username.$request->ip()); <ide> } <ide> }
2
Javascript
Javascript
avoid a breaking change and use a warning instead
c9fbdb9e486ded97dc025c855793ed5b6b553a30
<ide><path>lib/HotModuleReplacementPlugin.js <ide> const Compilation = require("./Compilation"); <ide> const HotUpdateChunk = require("./HotUpdateChunk"); <ide> const NormalModule = require("./NormalModule"); <ide> const RuntimeGlobals = require("./RuntimeGlobals"); <add>const WebpackError = require("./WebpackError"); <ide> const ConstDependency = require("./dependencies/ConstDependency"); <ide> const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency"); <ide> const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency"); <ide> const JavascriptParser = require("./javascript/JavascriptParser"); <ide> const { <ide> evaluateToIdentifier <ide> } = require("./javascript/JavascriptParserHelpers"); <del>const { find } = require("./util/SetHelpers"); <add>const { find, isSubset } = require("./util/SetHelpers"); <ide> const TupleSet = require("./util/TupleSet"); <ide> const { compareModulesById } = require("./util/comparators"); <ide> const { <ide> class HotModuleReplacementPlugin { <ide> chunkModuleHashes[key] = hash; <ide> } <ide> <del> /** @type {Map<string, { updatedChunkIds: (string|number)[], removedChunkIds: (string|number)[], removedModules: Set<Module> }>} */ <add> /** @type {Map<string, { updatedChunkIds: Set<string|number>, removedChunkIds: Set<string|number>, removedModules: Set<Module>, filename: string, assetInfo: AssetInfo }>} */ <ide> const hotUpdateMainContentByRuntime = new Map(); <ide> let allOldRuntime; <ide> for (const key of Object.keys(records.chunkRuntime)) { <ide> const runtime = keyToRuntime(records.chunkRuntime[key]); <ide> allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime); <ide> } <ide> forEachRuntime(allOldRuntime, runtime => { <add> const { <add> path: filename, <add> info: assetInfo <add> } = compilation.getPathWithInfo( <add> compilation.outputOptions.hotUpdateMainFilename, <add> { <add> hash: records.hash, <add> runtime <add> } <add> ); <ide> hotUpdateMainContentByRuntime.set(runtime, { <del> updatedChunkIds: [], <del> removedChunkIds: [], <del> removedModules: new Set() <add> updatedChunkIds: new Set(), <add> removedChunkIds: new Set(), <add> removedModules: new Set(), <add> filename, <add> assetInfo <ide> }); <ide> }); <ide> if (hotUpdateMainContentByRuntime.size === 0) return; <ide> class HotModuleReplacementPlugin { <ide> forEachRuntime(removedFromRuntime, runtime => { <ide> hotUpdateMainContentByRuntime <ide> .get(runtime) <del> .removedChunkIds.push(chunkId); <add> .removedChunkIds.add(chunkId); <ide> }); <ide> // dispose modules from the chunk in these runtimes <ide> // where they are no longer in this runtime <ide> class HotModuleReplacementPlugin { <ide> forEachRuntime(newRuntime, runtime => { <ide> hotUpdateMainContentByRuntime <ide> .get(runtime) <del> .updatedChunkIds.push(chunkId); <add> .updatedChunkIds.add(chunkId); <ide> }); <ide> } <ide> } <ide> const completelyRemovedModulesArray = Array.from( <ide> completelyRemovedModules <ide> ); <add> const hotUpdateMainContentByFilename = new Map(); <add> for (const { <add> removedChunkIds, <add> removedModules, <add> updatedChunkIds, <add> filename, <add> assetInfo <add> } of hotUpdateMainContentByRuntime.values()) { <add> const old = hotUpdateMainContentByFilename.get(filename); <add> if ( <add> old && <add> (!isSubset(old.removedChunkIds, removedChunkIds) || <add> !isSubset(old.removedModules, removedModules) || <add> !isSubset(old.updatedChunkIds, updatedChunkIds)) <add> ) { <add> compilation.warnings.push( <add> new WebpackError(`HotModuleReplacementPlugin <add>The configured output.hotUpdateMainFilename doesn't lead to unique filenames per runtime and HMR update differs between runtimes. <add>This might lead to incorrect runtime behavior of the applied update. <add>To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename option, or use the default config.`) <add> ); <add> for (const chunkId of removedChunkIds) <add> old.removedChunkIds.add(chunkId); <add> for (const chunkId of removedModules) <add> old.removedModules.add(chunkId); <add> for (const chunkId of updatedChunkIds) <add> old.updatedChunkIds.add(chunkId); <add> continue; <add> } <add> hotUpdateMainContentByFilename.set(filename, { <add> removedChunkIds, <add> removedModules, <add> updatedChunkIds, <add> assetInfo <add> }); <add> } <ide> for (const [ <del> runtime, <del> { removedChunkIds, removedModules, updatedChunkIds } <del> ] of hotUpdateMainContentByRuntime) { <add> filename, <add> { removedChunkIds, removedModules, updatedChunkIds, assetInfo } <add> ] of hotUpdateMainContentByFilename) { <ide> const hotUpdateMainJson = { <del> c: updatedChunkIds, <del> r: removedChunkIds, <add> c: Array.from(updatedChunkIds), <add> r: Array.from(removedChunkIds), <ide> m: <ide> removedModules.size === 0 <ide> ? completelyRemovedModulesArray <ide> class HotModuleReplacementPlugin { <ide> }; <ide> <ide> const source = new RawSource(JSON.stringify(hotUpdateMainJson)); <del> const { <del> path: filename, <del> info: assetInfo <del> } = compilation.getPathWithInfo( <del> compilation.outputOptions.hotUpdateMainFilename, <del> { <del> hash: records.hash, <del> runtime <del> } <del> ); <ide> compilation.emitAsset(filename, source, { <ide> hotModuleReplacement: true, <ide> ...assetInfo <ide><path>test/hotCases/disposing/runtime-independent-filename/chunk1.js <add>export * from "./shared"; <add>import.meta.webpackHot.accept("./shared"); <ide><path>test/hotCases/disposing/runtime-independent-filename/chunk2.js <add>export * from "./shared"; <add>import.meta.webpackHot.accept("./shared"); <ide><path>test/hotCases/disposing/runtime-independent-filename/index.js <add>import module from "./module"; <add> <add>it("should not dispose shared modules when a chunk from a different runtime is removed", done => { <add> import("./chunk1").then(chunk1 => { <add> import.meta.webpackHot.accept("./module", async () => { <add> expect(module).toBe(42); <add> expect(chunk1).toMatchObject({ <add> active: false // This get incorrectly disposed, due to the runtime-independent filename <add> }); <add> done(); <add> }); <add> NEXT(require("../../update")(done)); <add> }, done); <add>}); <ide><path>test/hotCases/disposing/runtime-independent-filename/module.js <add>export default () => new Worker(new URL("./chunk2", import.meta.url)); <add>--- <add>export default 42; <ide><path>test/hotCases/disposing/runtime-independent-filename/shared.js <add>export let active = true; <add> <add>import.meta.webpackHot.dispose(() => { <add> active = false; <add>}); <ide><path>test/hotCases/disposing/runtime-independent-filename/warnings1.js <add>module.exports = [ <add> [ <add> /The configured output\.hotUpdateMainFilename doesn't lead to unique filenames per runtime/ <add> ] <add>]; <ide><path>test/hotCases/disposing/runtime-independent-filename/webpack.config.js <add>/** @type {import("../../../../").Configuration} */ <add>module.exports = { <add> output: { <add> hotUpdateMainFilename: "[hash].main-filename.json" <add> } <add>};
8
Javascript
Javascript
fix mixins w/ tostring() in ie
9b0aa65af9c44e512f6bd1bec43bcfbbbff54f5c
<ide><path>packages/sproutcore-metal/lib/mixin.js <ide> function mergeMixins(mixins, m, descs, values, base) { <ide> values[key] = value; <ide> } <ide> } <del> <add> <add> // manually copy toString() because some JS engines do not enumerate it <add> if (props.hasOwnProperty('toString')) { <add> base.toString = props.toString; <add> } <ide> <ide> } else if (mixin.mixins) { <ide> mergeMixins(mixin.mixins, m, descs, values, base);
1
Text
Text
add agentconf 2018
5f12867824e6ba06492e0176ebf9f785da221d23
<ide><path>docs/community/conferences.md <ide> October 25–27, Bratislava, Slovakia <ide> <ide> [Website](https://reactiveconf.com) <ide> <add>### AgentConf 2018 <add>January 25-28 in Dornbirn, Austria <ide> <add>[Website](http://agent.sh/) <ide> <ide> ## Past Conferences <ide>
1
Python
Python
add resnet50 test
5b0967a08ff5a277d318506a9c28a31acd04794a
<ide><path>tests/keras/applications/applications_test.py <ide> from keras import backend as K <ide> <ide> <add>@keras_test <add>def test_resnet50(): <add> model = applications.ResNet50(weights=None) <add> assert model.output_shape == (None, 1000) <add> <add> <add>@keras_test <add>def test_resnet50_notop(): <add> model = applications.ResNet50(weights=None, include_top=False) <add> assert model.output_shape == (None, None, None, 2048) <add> <add> <add>@keras_test <add>def test_resnet50_pooling(): <add> model = applications.ResNet50(weights=None, <add> include_top=False, <add> pooling='avg') <add> assert model.output_shape == (None, 2048) <add> <add> <ide> @keras_test <ide> def test_vgg16(): <ide> model = applications.VGG16(weights=None)
1
Java
Java
update todos with new jira issue
31dfffde52baaff5c9539c9d11653f3776d10de4
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java <ide> public void testConstructor() throws Exception { <ide> <ide> @Test <ide> @Ignore("passes under Eclipse, but fails under Gradle with https://gist.github.com/1664133") <del> // TODO SPR-8116 passes under Eclipse, but fails under Gradle with <add> // TODO [SPR-10074] passes under Eclipse, but fails under Gradle with <ide> // https://gist.github.com/1664133 <ide> public void testContainerPrivileges() throws Exception { <ide> AccessControlContext acc = provider.getAccessControlContext(); <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java <ide> * <ide> * @author Ramnivas Laddad <ide> */ <del>// TODO SPR-8116 this test causes gradle to hang. <del>// when run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...` <add>// TODO [SPR-10074] this test causes gradle to hang. <add>// When run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...` <ide> // it works fine. When run together with all other tests e.g. `./gradlew :spring-orm:test` <ide> // it hangs on the 'testCanSerializeProxies' test method. Note that this test DOES pass in <ide> // Eclipse, even when the entire 'spring-orm' module is run. Run gradle with '-i' to <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java <ide> * <ide> * @author Costin Leau <ide> */ <del>// TODO SPR-8116 this test causes gradle to hang. See OJEMFWAJWIT. <add>// TODO [SPR-10074] this test causes gradle to hang. See OJEMFWAJWIT. <ide> @Ignore("this test causes gradle to hang. See OJEMFWAJWIT.") <ide> public class TopLinkMultiEntityManagerFactoryIntegrationTests extends <ide> AbstractContainerEntityManagerFactoryIntegrationTests { <ide><path>spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java <ide> * @author Juergen Hoeller <ide> * @since 2.5 <ide> */ <del>// TODO SPR-8116 - see https://gist.github.com/1150858 <add>// TODO [SPR-10074] see https://gist.github.com/1150858 <ide> @Ignore("see https://gist.github.com/1150858") <ide> public class JaxWsSupportTests { <ide>
4
Text
Text
fix "timout" typo in timeout
e7866568e5a4123d198b45ea13fbd3dd7a3103d9
<ide><path>doc/api/timers.md <ide> added: v0.9.1 <ide> When called, the active `Timeout` object will not require the Node.js event loop <ide> to remain active. If there is no other activity keeping the event loop running, <ide> the process may exit before the `Timeout` object's callback is invoked. Calling <del>`timout.unref()` multiple times will have no effect. <add>`timeout.unref()` multiple times will have no effect. <ide> <del>*Note*: Calling `timout.unref()` creates an internal timer that will wake the <add>*Note*: Calling `timeout.unref()` creates an internal timer that will wake the <ide> Node.js event loop. Creating too many of these can adversely impact performance <ide> of the Node.js application. <ide>
1
Javascript
Javascript
remove examples from api/components
200df00b9ef12405b8461c8c28b4874f3b638c0c
<ide><path>website/layout/AutodocsLayout.js <ide> var Autodocs = React.createClass({ <ide> ); <ide> }, <ide> <del> renderExample: function(example, metadata) { <del> if (!example) { <del> return; <del> } <del> <del> return ( <del> <div> <del> <HeaderWithGithub <del> title={example.title || 'Examples'} <del> level={example.title ? 4 : 3} <del> path={example.path} <del> metadata={metadata} <del> /> <del> <div className="example-container"> <del> <Prism> <del> {example.content.replace(/^[\s\S]*?\*\//, '').trim()} <del> </Prism> <del> </div> <del> </div> <del> ); <del> }, <del> <del> renderExamples: function(docs, metadata) { <del> if (!docs.examples || !docs.examples.length) { <del> return; <del> } <del> <del> return ( <del> <div> <del> {(docs.examples.length > 1) ? <Header level={3}>Examples</Header> : null} <del> {docs.examples.map(example => this.renderExample(example, metadata))} <del> </div> <del> ); <del> }, <del> <ide> render: function() { <ide> var metadata = this.props.metadata; <ide> var docs = JSON.parse(this.props.children); <ide> var Autodocs = React.createClass({ <ide> {content} <ide> <Footer path={metadata.path} /> <ide> {this.renderFullDescription(docs)} <del> {this.renderExamples(docs, metadata)} <ide> <div className="docs-prevnext"> <ide> {metadata.previous && <a className="docs-prev" href={'docs/' + metadata.previous + '.html#content'}>&larr; Prev</a>} <ide> {metadata.next && <a className="docs-next" href={'docs/' + metadata.next + '.html#content'}>Next &rarr;</a>} <ide><path>website/server/extractDocs.js <ide> function getPlatformFromPath(filepath) { <ide> return CROSS_SUFFIX; <ide> } <ide> <del>function getExamplePaths(componentName, componentPlatform) { <del> const componentExample = '../Examples/UIExplorer/js/' + componentName + 'Example.'; <del> const pathsToCheck = [ <del> componentExample + 'js', <del> componentExample + componentPlatform + '.js', <del> ]; <del> if (componentPlatform === CROSS_SUFFIX) { <del> pathsToCheck.push( <del> componentExample + IOS_SUFFIX + '.js', <del> componentExample + ANDROID_SUFFIX + '.js' <del> ); <del> } <del> const paths = []; <del> pathsToCheck.map((p) => { <del> if (fs.existsSync(p)) { <del> paths.push(p); <del> } <del> }); <del> return paths; <del>} <del> <del>function getExamples(componentName, componentPlatform) { <del> const paths = getExamplePaths(componentName, componentPlatform); <del> if (paths) { <del> const examples = []; <del> paths.map((p) => { <del> const platform = p.match(/Example\.(.*)\.js$/); <del> let title = ''; <del> if ((componentPlatform === CROSS_SUFFIX) && (platform !== null)) { <del> title = platform[1].toUpperCase(); <del> } <del> examples.push( <del> { <del> path: p.replace(/^\.\.\//, ''), <del> title: title, <del> content: fs.readFileSync(p).toString(), <del> } <del> ); <del> }); <del> return examples; <del> } <del> return; <del>} <del> <ide> // Add methods that should not appear in the components documentation. <ide> const methodsBlacklist = [ <ide> // Native methods mixin. <ide> function filterMethods(method) { <ide> return method.name[0] !== '_' && methodsBlacklist.indexOf(method.name) === -1; <ide> } <ide> <del>// Determines whether a component should have a link to a runnable example <del> <del>function isRunnable(componentName, componentPlatform) { <del> const paths = getExamplePaths(componentName, componentPlatform); <del> if (paths && paths.length > 0) { <del> return true; <del> } else { <del> return false; <del> } <del>} <del> <ide> // Hide a component from the sidebar by making it return false from <ide> // this function <ide> const HIDDEN_COMPONENTS = [ <ide> function componentsToMarkdown(type, json, filepath, idx, styles) { <ide> if (styles) { <ide> json.styles = styles; <ide> } <del> json.examples = getExamples(componentName, componentPlatform); <ide> <ide> if (json.methods) { <ide> json.methods = json.methods.filter(filterMethods); <ide> function componentsToMarkdown(type, json, filepath, idx, styles) { <ide> 'next: ' + next, <ide> 'previous: ' + previous, <ide> 'sidebar: ' + shouldDisplayInSidebar(componentName), <del> 'runnable:' + isRunnable(componentName, componentPlatform), <ide> 'path:' + json.filepath, <ide> '---', <ide> JSON.stringify(json, null, 2),
2
PHP
PHP
remove an unused import
5aa9a6d5151ca983e3a2c6b638e46e240c14be1f
<ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> <ide> namespace Illuminate\Database\Migrations; <ide> <del>use Closure; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Support\Collection;
1
Go
Go
replace aliased imports of logrus, fixes
6f4d847046cb4e072de61d042c0266190d73a8c9
<ide><path>api/client/attach.go <ide> import ( <ide> "io" <ide> "net/url" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/signal" <ide> func (cli *DockerCli) CmdAttach(args ...string) error { <ide> <ide> if tty && cli.isTerminalOut { <ide> if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { <del> log.Debugf("Error monitoring TTY size: %s", err) <add> logrus.Debugf("Error monitoring TTY size: %s", err) <ide> } <ide> } <ide> <ide><path>api/client/build.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/graph" <ide> "github.com/docker/docker/pkg/archive" <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> // windows: show error message about modified file permissions <ide> // FIXME: this is not a valid warning when the daemon is running windows. should be removed once docker engine for windows can build. <ide> if runtime.GOOS == "windows" { <del> log.Warn(`SECURITY WARNING: You are building a Docker image from Windows against a Linux Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.`) <add> logrus.Warn(`SECURITY WARNING: You are building a Docker image from Windows against a Linux Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.`) <ide> } <ide> <ide> var body io.Reader <ide><path>api/client/exec.go <ide> import ( <ide> "fmt" <ide> "io" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/runconfig" <ide> func (cli *DockerCli) CmdExec(args ...string) error { <ide> <ide> // Block the return until the chan gets closed <ide> defer func() { <del> log.Debugf("End of CmdExec(), Waiting for hijack to finish.") <add> logrus.Debugf("End of CmdExec(), Waiting for hijack to finish.") <ide> if _, ok := <-hijacked; ok { <del> log.Errorf("Hijack did not finish (chan still open)") <add> logrus.Errorf("Hijack did not finish (chan still open)") <ide> } <ide> }() <ide> <ide> func (cli *DockerCli) CmdExec(args ...string) error { <ide> } <ide> case err := <-errCh: <ide> if err != nil { <del> log.Debugf("Error hijack: %s", err) <add> logrus.Debugf("Error hijack: %s", err) <ide> return err <ide> } <ide> } <ide> <ide> if execConfig.Tty && cli.isTerminalIn { <ide> if err := cli.monitorTtySize(execID, true); err != nil { <del> log.Errorf("Error monitoring TTY size: %s", err) <add> logrus.Errorf("Error monitoring TTY size: %s", err) <ide> } <ide> } <ide> <ide> if err := <-errCh; err != nil { <del> log.Debugf("Error hijack: %s", err) <add> logrus.Debugf("Error hijack: %s", err) <ide> return err <ide> } <ide> <ide><path>api/client/hijack.go <ide> import ( <ide> "strings" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/pkg/promise" <ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea <ide> } else { <ide> _, err = stdcopy.StdCopy(stdout, stderr, br) <ide> } <del> log.Debugf("[hijack] End of stdout") <add> logrus.Debugf("[hijack] End of stdout") <ide> return err <ide> }) <ide> } <ide> <ide> sendStdin := promise.Go(func() error { <ide> if in != nil { <ide> io.Copy(rwc, in) <del> log.Debugf("[hijack] End of stdin") <add> logrus.Debugf("[hijack] End of stdin") <ide> } <ide> <ide> if conn, ok := rwc.(interface { <ide> CloseWrite() error <ide> }); ok { <ide> if err := conn.CloseWrite(); err != nil { <del> log.Debugf("Couldn't send EOF: %s", err) <add> logrus.Debugf("Couldn't send EOF: %s", err) <ide> } <ide> } <ide> // Discard errors due to pipe interruption <ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea <ide> <ide> if stdout != nil || stderr != nil { <ide> if err := <-receiveStdout; err != nil { <del> log.Debugf("Error receiveStdout: %s", err) <add> logrus.Debugf("Error receiveStdout: %s", err) <ide> return err <ide> } <ide> } <ide> <ide> if !cli.isTerminalIn { <ide> if err := <-sendStdin; err != nil { <del> log.Debugf("Error sendStdin: %s", err) <add> logrus.Debugf("Error sendStdin: %s", err) <ide> return err <ide> } <ide> } <ide><path>api/client/info.go <ide> import ( <ide> "os" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/units" <ide> func (cli *DockerCli) CmdInfo(args ...string) error { <ide> } <ide> <ide> if _, err := out.Write(body); err != nil { <del> log.Errorf("Error reading remote info: %s", err) <add> logrus.Errorf("Error reading remote info: %s", err) <ide> return err <ide> } <ide> out.Close() <ide> func (cli *DockerCli) CmdInfo(args ...string) error { <ide> if remoteInfo.Exists("SystemTime") { <ide> t, err := remoteInfo.GetTime("SystemTime") <ide> if err != nil { <del> log.Errorf("Error reading system time: %v", err) <add> logrus.Errorf("Error reading system time: %v", err) <ide> } else { <ide> fmt.Fprintf(cli.out, "System Time: %s\n", t.Format(time.UnixDate)) <ide> } <ide><path>api/client/run.go <ide> import ( <ide> "net/url" <ide> "os" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/resolvconf" <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> hijacked := make(chan io.Closer) <ide> // Block the return until the chan gets closed <ide> defer func() { <del> log.Debugf("End of CmdRun(), Waiting for hijack to finish.") <add> logrus.Debugf("End of CmdRun(), Waiting for hijack to finish.") <ide> if _, ok := <-hijacked; ok { <del> log.Errorf("Hijack did not finish (chan still open)") <add> logrus.Errorf("Hijack did not finish (chan still open)") <ide> } <ide> }() <ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr { <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> } <ide> case err := <-errCh: <ide> if err != nil { <del> log.Debugf("Error hijack: %s", err) <add> logrus.Debugf("Error hijack: %s", err) <ide> return err <ide> } <ide> } <ide> <ide> defer func() { <ide> if *flAutoRemove { <ide> if _, _, err = readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, nil)); err != nil { <del> log.Errorf("Error deleting container: %s", err) <add> logrus.Errorf("Error deleting container: %s", err) <ide> } <ide> } <ide> }() <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> <ide> if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut { <ide> if err := cli.monitorTtySize(createResponse.ID, false); err != nil { <del> log.Errorf("Error monitoring TTY size: %s", err) <add> logrus.Errorf("Error monitoring TTY size: %s", err) <ide> } <ide> } <ide> <ide> if errCh != nil { <ide> if err := <-errCh; err != nil { <del> log.Debugf("Error hijack: %s", err) <add> logrus.Debugf("Error hijack: %s", err) <ide> return err <ide> } <ide> } <ide><path>api/client/start.go <ide> import ( <ide> "net/url" <ide> "os" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/promise" <ide> func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { <ide> } <ide> } <ide> if sig == "" { <del> log.Errorf("Unsupported signal: %v. Discarding.", s) <add> logrus.Errorf("Unsupported signal: %v. Discarding.", s) <ide> } <ide> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, nil)); err != nil { <del> log.Debugf("Error sending signal: %s", err) <add> logrus.Debugf("Error sending signal: %s", err) <ide> } <ide> } <ide> }() <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> hijacked := make(chan io.Closer) <ide> // Block the return until the chan gets closed <ide> defer func() { <del> log.Debugf("CmdStart() returned, defer waiting for hijack to finish.") <add> logrus.Debugf("CmdStart() returned, defer waiting for hijack to finish.") <ide> if _, ok := <-hijacked; ok { <del> log.Errorf("Hijack did not finish (chan still open)") <add> logrus.Errorf("Hijack did not finish (chan still open)") <ide> } <ide> cli.in.Close() <ide> }() <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> if *openStdin || *attach { <ide> if tty && cli.isTerminalOut { <ide> if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { <del> log.Errorf("Error monitoring TTY size: %s", err) <add> logrus.Errorf("Error monitoring TTY size: %s", err) <ide> } <ide> } <ide> if attchErr := <-cErr; attchErr != nil { <ide><path>api/client/utils.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/engine" <ide> func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawT <ide> } else { <ide> _, err = stdcopy.StdCopy(stdout, stderr, body) <ide> } <del> log.Debugf("[stream] End of stdout") <add> logrus.Debugf("[stream] End of stdout") <ide> return err <ide> } <ide> return nil <ide> func (cli *DockerCli) resizeTty(id string, isExec bool) { <ide> } <ide> <ide> if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil { <del> log.Debugf("Error resize: %s", err) <add> logrus.Debugf("Error resize: %s", err) <ide> } <ide> } <ide> <ide> func (cli *DockerCli) getTtySize() (int, int) { <ide> } <ide> ws, err := term.GetWinsize(cli.outFd) <ide> if err != nil { <del> log.Debugf("Error getting size: %s", err) <add> logrus.Debugf("Error getting size: %s", err) <ide> if ws == nil { <ide> return 0, 0 <ide> } <ide><path>api/client/version.go <ide> import ( <ide> "fmt" <ide> "runtime" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/engine" <ide> func (cli *DockerCli) CmdVersion(args ...string) error { <ide> out := engine.NewOutput() <ide> remoteVersion, err := out.AddEnv() <ide> if err != nil { <del> log.Errorf("Error reading remote version: %s", err) <add> logrus.Errorf("Error reading remote version: %s", err) <ide> return err <ide> } <ide> if _, err := out.Write(body); err != nil { <del> log.Errorf("Error reading remote version: %s", err) <add> logrus.Errorf("Error reading remote version: %s", err) <ide> return err <ide> } <ide> out.Close() <ide><path>api/common.go <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/version" <ide> func FormGroup(key string, start, last int) string { <ide> func MatchesContentType(contentType, expectedType string) bool { <ide> mimetype, _, err := mime.ParseMediaType(contentType) <ide> if err != nil { <del> log.Errorf("Error parsing media type: %s error: %v", contentType, err) <add> logrus.Errorf("Error parsing media type: %s error: %v", contentType, err) <ide> } <ide> return err == nil && mimetype == expectedType <ide> } <ide><path>api/server/server.go <ide> import ( <ide> "github.com/docker/libcontainer/user" <ide> "github.com/gorilla/mux" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/daemon/networkdriver/portallocator" <ide> func httpError(w http.ResponseWriter, err error) { <ide> } <ide> <ide> if err != nil { <del> log.Errorf("HTTP Error: statusCode=%d %v", statusCode, err) <add> logrus.Errorf("HTTP Error: statusCode=%d %v", statusCode, err) <ide> http.Error(w, err.Error(), statusCode) <ide> } <ide> } <ide> func postCommit(eng *engine.Engine, version version.Version, w http.ResponseWrit <ide> } <ide> <ide> if err := config.Decode(r.Body); err != nil { <del> log.Errorf("%s", err) <add> logrus.Errorf("%s", err) <ide> } <ide> <ide> if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") { <ide> func wsContainersAttach(eng *engine.Engine, version version.Version, w http.Resp <ide> job.Stdout.Add(ws) <ide> job.Stderr.Set(ws) <ide> if err := job.Run(); err != nil { <del> log.Errorf("Error attaching websocket: %s", err) <add> logrus.Errorf("Error attaching websocket: %s", err) <ide> } <ide> }) <ide> h.ServeHTTP(w, r) <ide> func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWrite <ide> select { <ide> case <-finished: <ide> case <-closeNotifier.CloseNotify(): <del> log.Infof("Client disconnected, cancelling job: %s", job.Name) <add> logrus.Infof("Client disconnected, cancelling job: %s", job.Name) <ide> job.Cancel() <ide> } <ide> }() <ide> func postContainersCopy(eng *engine.Engine, version version.Version, w http.Resp <ide> job.Stdout.Add(w) <ide> w.Header().Set("Content-Type", "application/x-tar") <ide> if err := job.Run(); err != nil { <del> log.Errorf("%v", err) <add> logrus.Errorf("%v", err) <ide> if strings.Contains(strings.ToLower(err.Error()), "no such id") { <ide> w.WriteHeader(http.StatusNotFound) <ide> } else if strings.Contains(err.Error(), "no such file or directory") { <ide> func optionsHandler(eng *engine.Engine, version version.Version, w http.Response <ide> return nil <ide> } <ide> func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) { <del> log.Debugf("CORS header is enabled and set to: %s", corsHeaders) <add> logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders) <ide> w.Header().Add("Access-Control-Allow-Origin", corsHeaders) <ide> w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth") <ide> w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS") <ide> func ping(eng *engine.Engine, version version.Version, w http.ResponseWriter, r <ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc { <ide> return func(w http.ResponseWriter, r *http.Request) { <ide> // log the request <del> log.Debugf("Calling %s %s", localMethod, localRoute) <add> logrus.Debugf("Calling %s %s", localMethod, localRoute) <ide> <ide> if logging { <del> log.Infof("%s %s", r.Method, r.RequestURI) <add> logrus.Infof("%s %s", r.Method, r.RequestURI) <ide> } <ide> <ide> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") { <ide> userAgent := strings.Split(r.Header.Get("User-Agent"), "/") <ide> if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) { <del> log.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion) <add> logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion) <ide> } <ide> } <ide> version := version.Version(mux.Vars(r)["version"]) <ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, local <ide> } <ide> <ide> if err := handlerFunc(eng, version, w, r, mux.Vars(r)); err != nil { <del> log.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err) <add> logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err) <ide> httpError(w, err) <ide> } <ide> } <ide> func createRouter(eng *engine.Engine, logging, enableCors bool, corsHeaders stri <ide> <ide> for method, routes := range m { <ide> for route, fct := range routes { <del> log.Debugf("Registering %s, %s", method, route) <add> logrus.Debugf("Registering %s, %s", method, route) <ide> // NOTE: scope issue, make sure the variables are local and won't be changed <ide> localRoute := route <ide> localFct := fct <ide> func lookupGidByName(nameOrGid string) (int, error) { <ide> } <ide> gid, err := strconv.Atoi(nameOrGid) <ide> if err == nil { <del> log.Warnf("Could not find GID %d", gid) <add> logrus.Warnf("Could not find GID %d", gid) <ide> return gid, nil <ide> } <ide> return -1, fmt.Errorf("Group %s not found", nameOrGid) <ide> func changeGroup(addr string, nameOrGid string) error { <ide> return err <ide> } <ide> <del> log.Debugf("%s group found. gid: %d", nameOrGid, gid) <add> logrus.Debugf("%s group found. gid: %d", nameOrGid, gid) <ide> return os.Chown(addr, 0, gid) <ide> } <ide> <ide> func setSocketGroup(addr, group string) error { <ide> if group != "docker" { <ide> return err <ide> } <del> log.Debugf("Warning: could not chgrp %s to docker: %v", addr, err) <add> logrus.Debugf("Warning: could not chgrp %s to docker: %v", addr, err) <ide> } <ide> <ide> return nil <ide> func allocateDaemonPort(addr string) error { <ide> <ide> func setupTcpHttp(addr string, job *engine.Job) (*HttpServer, error) { <ide> if !job.GetenvBool("TlsVerify") { <del> log.Infof("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\") <add> logrus.Infof("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\") <ide> } <ide> <ide> r := createRouter(job.Eng, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"), job.Getenv("CorsHeaders"), job.Getenv("Version")) <ide> func ServeApi(job *engine.Job) error { <ide> return fmt.Errorf("usage: %s PROTO://ADDR [PROTO://ADDR ...]", job.Name) <ide> } <ide> go func() { <del> log.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1]) <add> logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1]) <ide> srv, err := NewServer(protoAddrParts[0], protoAddrParts[1], job) <ide> if err != nil { <ide> chErrors <- err <ide> return <ide> } <ide> job.Eng.OnShutdown(func() { <ide> if err := srv.Close(); err != nil { <del> log.Error(err) <add> logrus.Error(err) <ide> } <ide> }) <ide> if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") { <ide><path>builder/dispatchers.go <ide> import ( <ide> "sort" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/nat" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/runconfig" <ide> func run(b *Builder, args []string, attributes map[string]bool, original string) <ide> <ide> defer func(cmd []string) { b.Config.Cmd = cmd }(cmd) <ide> <del> log.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd) <add> logrus.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd) <ide> <ide> hit, err := b.probeCache() <ide> if err != nil { <ide><path>builder/evaluator.go <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/builder/command" <ide> "github.com/docker/docker/builder/parser" <ide> func (b *Builder) Run(context io.Reader) (string, error) { <ide> <ide> defer func() { <ide> if err := os.RemoveAll(b.contextPath); err != nil { <del> log.Debugf("[BUILDER] failed to remove temporary context: %s", err) <add> logrus.Debugf("[BUILDER] failed to remove temporary context: %s", err) <ide> } <ide> }() <ide> <ide> func (b *Builder) Run(context io.Reader) (string, error) { <ide> for i, n := range b.dockerfile.Children { <ide> select { <ide> case <-b.cancelled: <del> log.Debug("Builder: build cancelled!") <add> logrus.Debug("Builder: build cancelled!") <ide> fmt.Fprintf(b.OutStream, "Build cancelled") <ide> return "", fmt.Errorf("Build cancelled") <ide> default: <ide><path>builder/internals.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/builder/parser" <ide> "github.com/docker/docker/daemon" <ide> imagepkg "github.com/docker/docker/image" <ide> func (b *Builder) probeCache() (bool, error) { <ide> return false, err <ide> } <ide> if cache == nil { <del> log.Debugf("[BUILDER] Cache miss") <add> logrus.Debugf("[BUILDER] Cache miss") <ide> b.cacheBusted = true <ide> return false, nil <ide> } <ide> <ide> fmt.Fprintf(b.OutStream, " ---> Using cache\n") <del> log.Debugf("[BUILDER] Use cached version") <add> logrus.Debugf("[BUILDER] Use cached version") <ide> b.image = cache.ID <ide> return true, nil <ide> } <ide> func (b *Builder) run(c *daemon.Container) error { <ide> go func() { <ide> select { <ide> case <-b.cancelled: <del> log.Debugln("Build cancelled, killing container:", c.ID) <add> logrus.Debugln("Build cancelled, killing container:", c.ID) <ide> c.Kill() <ide> case <-finished: <ide> } <ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec <ide> if err := chrootarchive.UntarPath(origPath, tarDest); err == nil { <ide> return nil <ide> } else if err != io.EOF { <del> log.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err) <add> logrus.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err) <ide> } <ide> } <ide> <ide><path>contrib/docker-device-tool/device_tool.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver/devmapper" <ide> "github.com/docker/docker/pkg/devicemapper" <ide> ) <ide> func main() { <ide> <ide> if *flDebug { <ide> os.Setenv("DEBUG", "1") <del> log.SetLevel(log.DebugLevel) <add> logrus.SetLevel(logrus.DebugLevel) <ide> } <ide> <ide> if flag.NArg() < 1 { <ide><path>daemon/attach.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/jsonlog" <ide> "github.com/docker/docker/pkg/promise" <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) error { <ide> cLog, err := container.ReadLog("json") <ide> if err != nil && os.IsNotExist(err) { <ide> // Legacy logs <del> log.Debugf("Old logs format") <add> logrus.Debugf("Old logs format") <ide> if stdout { <ide> cLog, err := container.ReadLog("stdout") <ide> if err != nil { <del> log.Errorf("Error reading logs (stdout): %s", err) <add> logrus.Errorf("Error reading logs (stdout): %s", err) <ide> } else if _, err := io.Copy(job.Stdout, cLog); err != nil { <del> log.Errorf("Error streaming logs (stdout): %s", err) <add> logrus.Errorf("Error streaming logs (stdout): %s", err) <ide> } <ide> } <ide> if stderr { <ide> cLog, err := container.ReadLog("stderr") <ide> if err != nil { <del> log.Errorf("Error reading logs (stderr): %s", err) <add> logrus.Errorf("Error reading logs (stderr): %s", err) <ide> } else if _, err := io.Copy(job.Stderr, cLog); err != nil { <del> log.Errorf("Error streaming logs (stderr): %s", err) <add> logrus.Errorf("Error streaming logs (stderr): %s", err) <ide> } <ide> } <ide> } else if err != nil { <del> log.Errorf("Error reading logs (json): %s", err) <add> logrus.Errorf("Error reading logs (json): %s", err) <ide> } else { <ide> dec := json.NewDecoder(cLog) <ide> for { <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) error { <ide> if err := dec.Decode(l); err == io.EOF { <ide> break <ide> } else if err != nil { <del> log.Errorf("Error streaming logs: %s", err) <add> logrus.Errorf("Error streaming logs: %s", err) <ide> break <ide> } <ide> if l.Stream == "stdout" && stdout { <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) error { <ide> r, w := io.Pipe() <ide> go func() { <ide> defer w.Close() <del> defer log.Debugf("Closing buffered stdin pipe") <add> defer logrus.Debugf("Closing buffered stdin pipe") <ide> io.Copy(w, job.Stdin) <ide> }() <ide> cStdin = r <ide> func (daemon *Daemon) Attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> if stdin == nil || !openStdin { <ide> return <ide> } <del> log.Debugf("attach: stdin: begin") <add> logrus.Debugf("attach: stdin: begin") <ide> defer func() { <ide> if stdinOnce && !tty { <ide> cStdin.Close() <ide> func (daemon *Daemon) Attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> } <ide> } <ide> wg.Done() <del> log.Debugf("attach: stdin: end") <add> logrus.Debugf("attach: stdin: end") <ide> }() <ide> <ide> var err error <ide> func (daemon *Daemon) Attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> err = nil <ide> } <ide> if err != nil { <del> log.Errorf("attach: stdin: %s", err) <add> logrus.Errorf("attach: stdin: %s", err) <ide> errors <- err <ide> return <ide> } <ide> func (daemon *Daemon) Attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> } <ide> streamPipe.Close() <ide> wg.Done() <del> log.Debugf("attach: %s: end", name) <add> logrus.Debugf("attach: %s: end", name) <ide> }() <ide> <del> log.Debugf("attach: %s: begin", name) <add> logrus.Debugf("attach: %s: begin", name) <ide> _, err := io.Copy(stream, streamPipe) <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> } <ide> if err != nil { <del> log.Errorf("attach: %s: %v", name, err) <add> logrus.Errorf("attach: %s: %v", name, err) <ide> errors <- err <ide> } <ide> } <ide><path>daemon/container.go <ide> import ( <ide> "github.com/docker/libcontainer/devices" <ide> "github.com/docker/libcontainer/label" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/jsonfilelog" <ide> func (container *Container) WriteHostConfig() error { <ide> func (container *Container) LogEvent(action string) { <ide> d := container.daemon <ide> if err := d.eng.Job("log", action, container.ID, d.Repositories().ImageName(container.ImageID)).Run(); err != nil { <del> log.Errorf("Error logging event %s for %s: %s", action, container.ID, err) <add> logrus.Errorf("Error logging event %s for %s: %s", action, container.ID, err) <ide> } <ide> } <ide> <ide> func (container *Container) cleanup() { <ide> } <ide> <ide> if err := container.Unmount(); err != nil { <del> log.Errorf("%v: Failed to umount filesystem: %v", container.ID, err) <add> logrus.Errorf("%v: Failed to umount filesystem: %v", container.ID, err) <ide> } <ide> <ide> for _, eConfig := range container.execCommands.s { <ide> func (container *Container) cleanup() { <ide> } <ide> <ide> func (container *Container) KillSig(sig int) error { <del> log.Debugf("Sending %d to %s", sig, container.ID) <add> logrus.Debugf("Sending %d to %s", sig, container.ID) <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> func (container *Container) KillSig(sig int) error { <ide> func (container *Container) killPossiblyDeadProcess(sig int) error { <ide> err := container.KillSig(sig) <ide> if err == syscall.ESRCH { <del> log.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPid(), sig) <add> logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPid(), sig) <ide> return nil <ide> } <ide> return err <ide> func (container *Container) Kill() error { <ide> if _, err := container.WaitStop(10 * time.Second); err != nil { <ide> // Ensure that we don't kill ourselves <ide> if pid := container.GetPid(); pid != 0 { <del> log.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID)) <add> logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID)) <ide> if err := syscall.Kill(pid, 9); err != nil { <ide> if err != syscall.ESRCH { <ide> return err <ide> } <del> log.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid) <add> logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid) <ide> } <ide> } <ide> } <ide> func (container *Container) Stop(seconds int) error { <ide> <ide> // 1. Send a SIGTERM <ide> if err := container.killPossiblyDeadProcess(15); err != nil { <del> log.Infof("Failed to send SIGTERM to the process, force killing") <add> logrus.Infof("Failed to send SIGTERM to the process, force killing") <ide> if err := container.killPossiblyDeadProcess(9); err != nil { <ide> return err <ide> } <ide> } <ide> <ide> // 2. Wait for the process to exit on its own <ide> if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil { <del> log.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) <add> logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) <ide> // 3. If it doesn't, then send SIGKILL <ide> if err := container.Kill(); err != nil { <ide> container.WaitStop(-1 * time.Second) <ide> func (container *Container) GetSize() (int64, int64) { <ide> ) <ide> <ide> if err := container.Mount(); err != nil { <del> log.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err) <add> logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err) <ide> return sizeRw, sizeRootfs <ide> } <ide> defer container.Unmount() <ide> <ide> initID := fmt.Sprintf("%s-init", container.ID) <ide> sizeRw, err = driver.DiffSize(container.ID, initID) <ide> if err != nil { <del> log.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err) <add> logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err) <ide> // FIXME: GetSize should return an error. Not changing it now in case <ide> // there is a side-effect. <ide> sizeRw = -1 <ide> func (container *Container) DisableLink(name string) { <ide> if link, exists := container.activeLinks[name]; exists { <ide> link.Disable() <ide> } else { <del> log.Debugf("Could not find active link for %s", name) <add> logrus.Debugf("Could not find active link for %s", name) <ide> } <ide> } <ide> } <ide> func (container *Container) setupContainerDns() error { <ide> // check if this is an existing container that needs DNS update: <ide> if container.UpdateDns { <ide> // read the host's resolv.conf, get the hash and call updateResolvConf <del> log.Debugf("Check container (%s) for update to resolv.conf - UpdateDns flag was set", container.ID) <add> logrus.Debugf("Check container (%s) for update to resolv.conf - UpdateDns flag was set", container.ID) <ide> latestResolvConf, latestHash := resolvconf.GetLastModified() <ide> <ide> // clean container resolv.conf re: localhost nameservers and IPv6 NS (if IPv6 disabled) <ide> func (container *Container) updateResolvConf(updatedResolvConf []byte, newResolv <ide> //if the user has not modified the resolv.conf of the container since we wrote it last <ide> //we will replace it with the updated resolv.conf from the host <ide> if string(hashBytes) == curHash { <del> log.Debugf("replacing %q with updated host resolv.conf", container.ResolvConfPath) <add> logrus.Debugf("replacing %q with updated host resolv.conf", container.ResolvConfPath) <ide> <ide> // for atomic updates to these files, use temporary files with os.Rename: <ide> dir := path.Dir(container.ResolvConfPath) <ide> func (container *Container) updateParentsHosts() error { <ide> <ide> c, err := container.daemon.Get(ref.ParentID) <ide> if err != nil { <del> log.Error(err) <add> logrus.Error(err) <ide> } <ide> <ide> if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() { <del> log.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress) <add> logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress) <ide> if err := etchosts.Update(c.HostsPath, container.NetworkSettings.IPAddress, ref.Name); err != nil { <del> log.Errorf("Failed to update /etc/hosts in parent container %s for alias %s: %v", c.ID, ref.Name, err) <add> logrus.Errorf("Failed to update /etc/hosts in parent container %s for alias %s: %v", c.ID, ref.Name, err) <ide> } <ide> } <ide> } <ide> func (container *Container) initializeNetworking() error { <ide> // Make sure the config is compatible with the current kernel <ide> func (container *Container) verifyDaemonSettings() { <ide> if container.Config.Memory > 0 && !container.daemon.sysInfo.MemoryLimit { <del> log.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.") <add> logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.") <ide> container.Config.Memory = 0 <ide> } <ide> if container.Config.Memory > 0 && !container.daemon.sysInfo.SwapLimit { <del> log.Warnf("Your kernel does not support swap limit capabilities. Limitation discarded.") <add> logrus.Warnf("Your kernel does not support swap limit capabilities. Limitation discarded.") <ide> container.Config.MemorySwap = -1 <ide> } <ide> if container.daemon.sysInfo.IPv4ForwardingDisabled { <del> log.Warnf("IPv4 forwarding is disabled. Networking will not work") <add> logrus.Warnf("IPv4 forwarding is disabled. Networking will not work") <ide> } <ide> } <ide> <ide><path>daemon/daemon.go <ide> import ( <ide> <ide> "github.com/docker/libcontainer/label" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/daemon/execdriver" <ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err <ide> // if so, then we need to restart monitor and init a new lock <ide> // If the container is supposed to be running, make sure of it <ide> if container.IsRunning() { <del> log.Debugf("killing old running container %s", container.ID) <add> logrus.Debugf("killing old running container %s", container.ID) <ide> <ide> existingPid := container.Pid <ide> container.SetStopped(&execdriver.ExitStatus{ExitCode: 0}) <ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err <ide> var err error <ide> cmd.ProcessConfig.Process, err = os.FindProcess(existingPid) <ide> if err != nil { <del> log.Debugf("cannot find existing process for %d", existingPid) <add> logrus.Debugf("cannot find existing process for %d", existingPid) <ide> } <ide> daemon.execDriver.Terminate(cmd) <ide> } <ide> <ide> if err := container.Unmount(); err != nil { <del> log.Debugf("unmount error %s", err) <add> logrus.Debugf("unmount error %s", err) <ide> } <ide> if err := container.ToDisk(); err != nil { <del> log.Debugf("saving stopped state to disk %s", err) <add> logrus.Debugf("saving stopped state to disk %s", err) <ide> } <ide> <ide> info := daemon.execDriver.Info(container.ID) <ide> if !info.IsRunning() { <del> log.Debugf("Container %s was supposed to be running but is not.", container.ID) <add> logrus.Debugf("Container %s was supposed to be running but is not.", container.ID) <ide> <del> log.Debug("Marking as stopped") <add> logrus.Debug("Marking as stopped") <ide> <ide> container.SetStopped(&execdriver.ExitStatus{ExitCode: -127}) <ide> if err := container.ToDisk(); err != nil { <ide> func (daemon *Daemon) ensureName(container *Container) error { <ide> container.Name = name <ide> <ide> if err := container.ToDisk(); err != nil { <del> log.Debugf("Error saving container name %s", err) <add> logrus.Debugf("Error saving container name %s", err) <ide> } <ide> } <ide> return nil <ide> func (daemon *Daemon) restore() error { <ide> ) <ide> <ide> if !debug { <del> log.Info("Loading containers: start.") <add> logrus.Info("Loading containers: start.") <ide> } <ide> dir, err := ioutil.ReadDir(daemon.repository) <ide> if err != nil { <ide> func (daemon *Daemon) restore() error { <ide> for _, v := range dir { <ide> id := v.Name() <ide> container, err := daemon.load(id) <del> if !debug && log.GetLevel() == log.InfoLevel { <add> if !debug && logrus.GetLevel() == logrus.InfoLevel { <ide> fmt.Print(".") <ide> } <ide> if err != nil { <del> log.Errorf("Failed to load container %v: %v", id, err) <add> logrus.Errorf("Failed to load container %v: %v", id, err) <ide> continue <ide> } <ide> <ide> // Ignore the container if it does not support the current driver being used by the graph <ide> if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver { <del> log.Debugf("Loaded container %v", container.ID) <add> logrus.Debugf("Loaded container %v", container.ID) <ide> <ide> containers[container.ID] = container <ide> } else { <del> log.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID) <add> logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID) <ide> } <ide> } <ide> <ide> registeredContainers := []*Container{} <ide> <ide> if entities := daemon.containerGraph.List("/", -1); entities != nil { <ide> for _, p := range entities.Paths() { <del> if !debug && log.GetLevel() == log.InfoLevel { <add> if !debug && logrus.GetLevel() == logrus.InfoLevel { <ide> fmt.Print(".") <ide> } <ide> <ide> e := entities[p] <ide> <ide> if container, ok := containers[e.ID()]; ok { <ide> if err := daemon.register(container, false); err != nil { <del> log.Debugf("Failed to register container %s: %s", container.ID, err) <add> logrus.Debugf("Failed to register container %s: %s", container.ID, err) <ide> } <ide> <ide> registeredContainers = append(registeredContainers, container) <ide> func (daemon *Daemon) restore() error { <ide> // Try to set the default name for a container if it exists prior to links <ide> container.Name, err = daemon.generateNewName(container.ID) <ide> if err != nil { <del> log.Debugf("Setting default id - %s", err) <add> logrus.Debugf("Setting default id - %s", err) <ide> } <ide> <ide> if err := daemon.register(container, false); err != nil { <del> log.Debugf("Failed to register container %s: %s", container.ID, err) <add> logrus.Debugf("Failed to register container %s: %s", container.ID, err) <ide> } <ide> <ide> registeredContainers = append(registeredContainers, container) <ide> func (daemon *Daemon) restore() error { <ide> // check the restart policy on the containers and restart any container with <ide> // the restart policy of "always" <ide> if daemon.config.AutoRestart { <del> log.Debug("Restarting containers...") <add> logrus.Debug("Restarting containers...") <ide> <ide> for _, container := range registeredContainers { <ide> if container.hostConfig.RestartPolicy.Name == "always" || <ide> (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) { <del> log.Debugf("Starting container %s", container.ID) <add> logrus.Debugf("Starting container %s", container.ID) <ide> <ide> if err := container.Start(); err != nil { <del> log.Debugf("Failed to start container %s: %s", container.ID, err) <add> logrus.Debugf("Failed to start container %s: %s", container.ID, err) <ide> } <ide> } <ide> } <ide> } <ide> <ide> if !debug { <del> if log.GetLevel() == log.InfoLevel { <add> if logrus.GetLevel() == logrus.InfoLevel { <ide> fmt.Println() <ide> } <del> log.Info("Loading containers: done.") <add> logrus.Info("Loading containers: done.") <ide> } <ide> <ide> return nil <ide> func (daemon *Daemon) setupResolvconfWatcher() error { <ide> // without an actual change to the file <ide> updatedResolvConf, newResolvConfHash, err := resolvconf.GetIfChanged() <ide> if err != nil { <del> log.Debugf("Error retrieving updated host resolv.conf: %v", err) <add> logrus.Debugf("Error retrieving updated host resolv.conf: %v", err) <ide> } else if updatedResolvConf != nil { <ide> // because the new host resolv.conf might have localhost nameservers.. <ide> updatedResolvConf, modified := resolvconf.FilterResolvDns(updatedResolvConf, daemon.config.EnableIPv6) <ide> if modified { <ide> // changes have occurred during localhost cleanup: generate an updated hash <ide> newHash, err := utils.HashData(bytes.NewReader(updatedResolvConf)) <ide> if err != nil { <del> log.Debugf("Error generating hash of new resolv.conf: %v", err) <add> logrus.Debugf("Error generating hash of new resolv.conf: %v", err) <ide> } else { <ide> newResolvConfHash = newHash <ide> } <ide> } <del> log.Debug("host network resolv.conf changed--walking container list for updates") <add> logrus.Debug("host network resolv.conf changed--walking container list for updates") <ide> contList := daemon.containers.List() <ide> for _, container := range contList { <ide> if err := container.updateResolvConf(updatedResolvConf, newResolvConfHash); err != nil { <del> log.Debugf("Error on resolv.conf update check for container ID: %s: %v", container.ID, err) <add> logrus.Debugf("Error on resolv.conf update check for container ID: %s: %v", container.ID, err) <ide> } <ide> } <ide> } <ide> } <ide> case err := <-watcher.Errors: <del> log.Debugf("host resolv.conf notify error: %v", err) <add> logrus.Debugf("host resolv.conf notify error: %v", err) <ide> } <ide> } <ide> }() <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> // register portallocator release on shutdown <ide> eng.OnShutdown(func() { <ide> if err := portallocator.ReleaseAll(); err != nil { <del> log.Errorf("portallocator.ReleaseAll(): %s", err) <add> logrus.Errorf("portallocator.ReleaseAll(): %s", err) <ide> } <ide> }) <ide> // Claim the pidfile first, to avoid any and all unexpected race conditions. <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> if err != nil { <ide> return nil, fmt.Errorf("error intializing graphdriver: %v", err) <ide> } <del> log.Debugf("Using graph driver %s", driver) <add> logrus.Debugf("Using graph driver %s", driver) <ide> // register cleanup for graph driver <ide> eng.OnShutdown(func() { <ide> if err := driver.Cleanup(); err != nil { <del> log.Errorf("Error during graph storage driver.Cleanup(): %v", err) <add> logrus.Errorf("Error during graph storage driver.Cleanup(): %v", err) <ide> } <ide> }) <ide> <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> if driver.String() == "btrfs" { <ide> return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver") <ide> } <del> log.Debug("SELinux enabled successfully") <add> logrus.Debug("SELinux enabled successfully") <ide> } else { <del> log.Warn("Docker could not enable SELinux on the host system") <add> logrus.Warn("Docker could not enable SELinux on the host system") <ide> } <ide> } else { <ide> selinuxSetDisabled() <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> return nil, err <ide> } <ide> <del> log.Debug("Creating images graph") <add> logrus.Debug("Creating images graph") <ide> g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver) <ide> if err != nil { <ide> return nil, err <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> return nil, err <ide> } <ide> <del> log.Debug("Creating repository list") <add> logrus.Debug("Creating repository list") <ide> repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g, trustKey) <ide> if err != nil { <ide> return nil, fmt.Errorf("Couldn't create Tag store: %s", err) <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> // register graph close on shutdown <ide> eng.OnShutdown(func() { <ide> if err := graph.Close(); err != nil { <del> log.Errorf("Error during container graph.Close(): %v", err) <add> logrus.Errorf("Error during container graph.Close(): %v", err) <ide> } <ide> }) <ide> <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> <ide> eng.OnShutdown(func() { <ide> if err := daemon.shutdown(); err != nil { <del> log.Errorf("Error during daemon.shutdown(): %v", err) <add> logrus.Errorf("Error during daemon.shutdown(): %v", err) <ide> } <ide> }) <ide> <ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) <ide> <ide> func (daemon *Daemon) shutdown() error { <ide> group := sync.WaitGroup{} <del> log.Debug("starting clean shutdown of all containers...") <add> logrus.Debug("starting clean shutdown of all containers...") <ide> for _, container := range daemon.List() { <ide> c := container <ide> if c.IsRunning() { <del> log.Debugf("stopping %s", c.ID) <add> logrus.Debugf("stopping %s", c.ID) <ide> group.Add(1) <ide> <ide> go func() { <ide> defer group.Done() <ide> if err := c.KillSig(15); err != nil { <del> log.Debugf("kill 15 error for %s - %s", c.ID, err) <add> logrus.Debugf("kill 15 error for %s - %s", c.ID, err) <ide> } <ide> c.WaitStop(-1 * time.Second) <del> log.Debugf("container stopped %s", c.ID) <add> logrus.Debugf("container stopped %s", c.ID) <ide> }() <ide> } <ide> } <ide> func checkKernel() error { <ide> // the circumstances of pre-3.8 crashes are clearer. <ide> // For details see http://github.com/docker/docker/issues/407 <ide> if k, err := kernel.GetKernelVersion(); err != nil { <del> log.Warnf("%s", err) <add> logrus.Warnf("%s", err) <ide> } else { <ide> if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 { <ide> if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" { <del> log.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String()) <add> logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String()) <ide> } <ide> } <ide> } <ide><path>daemon/daemon_aufs.go <ide> package daemon <ide> <ide> import ( <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/daemon/graphdriver/aufs" <ide> "github.com/docker/docker/graph" <ide> import ( <ide> // If aufs driver is not built, this func is a noop. <ide> func migrateIfAufs(driver graphdriver.Driver, root string) error { <ide> if ad, ok := driver.(*aufs.Driver); ok { <del> log.Debugf("Migrating existing containers") <add> logrus.Debugf("Migrating existing containers") <ide> if err := ad.Migrate(root, graph.SetupInitLayer); err != nil { <ide> return err <ide> } <ide><path>daemon/delete.go <ide> import ( <ide> "os" <ide> "path" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> ) <ide> <ide> func (daemon *Daemon) ContainerRm(job *engine.Job) error { <ide> func (daemon *Daemon) DeleteVolumes(volumeIDs map[string]struct{}) { <ide> for id := range volumeIDs { <ide> if err := daemon.volumes.Delete(id); err != nil { <del> log.Infof("%s", err) <add> logrus.Infof("%s", err) <ide> continue <ide> } <ide> } <ide> func (daemon *Daemon) Rm(container *Container) error { <ide> daemon.containers.Delete(container.ID) <ide> container.derefVolumes() <ide> if _, err := daemon.containerGraph.Purge(container.ID); err != nil { <del> log.Debugf("Unable to remove container from link graph: %s", err) <add> logrus.Debugf("Unable to remove container from link graph: %s", err) <ide> } <ide> <ide> if err := daemon.driver.Remove(container.ID); err != nil { <ide><path>daemon/exec.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/execdriver/lxc" <ide> "github.com/docker/docker/engine" <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) error { <ide> return err <ide> } <ide> <del> log.Debugf("starting exec command %s in container %s", execConfig.ID, execConfig.Container.ID) <add> logrus.Debugf("starting exec command %s in container %s", execConfig.ID, execConfig.Container.ID) <ide> container := execConfig.Container <ide> <ide> container.LogEvent("exec_start: " + execConfig.ProcessConfig.Entrypoint + " " + strings.Join(execConfig.ProcessConfig.Arguments, " ")) <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) error { <ide> r, w := io.Pipe() <ide> go func() { <ide> defer w.Close() <del> defer log.Debugf("Closing buffered stdin pipe") <add> defer logrus.Debugf("Closing buffered stdin pipe") <ide> io.Copy(w, job.Stdin) <ide> }() <ide> cStdin = r <ide> func (container *Container) monitorExec(execConfig *execConfig, callback execdri <ide> pipes := execdriver.NewPipes(execConfig.StreamConfig.stdin, execConfig.StreamConfig.stdout, execConfig.StreamConfig.stderr, execConfig.OpenStdin) <ide> exitCode, err = container.daemon.Exec(container, execConfig, pipes, callback) <ide> if err != nil { <del> log.Errorf("Error running command in existing container %s: %s", container.ID, err) <add> logrus.Errorf("Error running command in existing container %s: %s", container.ID, err) <ide> } <ide> <del> log.Debugf("Exec task in container %s exited with code %d", container.ID, exitCode) <add> logrus.Debugf("Exec task in container %s exited with code %d", container.ID, exitCode) <ide> if execConfig.OpenStdin { <ide> if err := execConfig.StreamConfig.stdin.Close(); err != nil { <del> log.Errorf("Error closing stdin while running in %s: %s", container.ID, err) <add> logrus.Errorf("Error closing stdin while running in %s: %s", container.ID, err) <ide> } <ide> } <ide> if err := execConfig.StreamConfig.stdout.Clean(); err != nil { <del> log.Errorf("Error closing stdout while running in %s: %s", container.ID, err) <add> logrus.Errorf("Error closing stdout while running in %s: %s", container.ID, err) <ide> } <ide> if err := execConfig.StreamConfig.stderr.Clean(); err != nil { <del> log.Errorf("Error closing stderr while running in %s: %s", container.ID, err) <add> logrus.Errorf("Error closing stderr while running in %s: %s", container.ID, err) <ide> } <ide> if execConfig.ProcessConfig.Terminal != nil { <ide> if err := execConfig.ProcessConfig.Terminal.Close(); err != nil { <del> log.Errorf("Error closing terminal while running in container %s: %s", container.ID, err) <add> logrus.Errorf("Error closing terminal while running in container %s: %s", container.ID, err) <ide> } <ide> } <ide> <ide><path>daemon/execdriver/lxc/driver.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> sysinfo "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/pkg/term" <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> "unshare", "-m", "--", "/bin/sh", "-c", shellString, <ide> } <ide> } <del> log.Debugf("lxc params %s", params) <add> logrus.Debugf("lxc params %s", params) <ide> var ( <ide> name = params[0] <ide> arg = params[1:] <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> c.ContainerPid = pid <ide> <ide> if startCallback != nil { <del> log.Debugf("Invoking startCallback") <add> logrus.Debugf("Invoking startCallback") <ide> startCallback(&c.ProcessConfig, pid) <ide> } <ide> <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> <ide> if err == nil { <ide> _, oomKill = <-oomKillNotification <del> log.Debugf("oomKill error %s waitErr %s", oomKill, waitErr) <add> logrus.Debugf("oomKill error %s waitErr %s", oomKill, waitErr) <ide> } else { <del> log.Warnf("Your kernel does not support OOM notifications: %s", err) <add> logrus.Warnf("Your kernel does not support OOM notifications: %s", err) <ide> } <ide> <ide> // check oom error <ide> func cgroupPaths(containerId string) (map[string]string, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> log.Debugf("subsystems: %s", subsystems) <add> logrus.Debugf("subsystems: %s", subsystems) <ide> paths := make(map[string]string) <ide> for _, subsystem := range subsystems { <ide> cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem) <del> log.Debugf("cgroup path %s %s", cgroupRoot, cgroupDir) <add> logrus.Debugf("cgroup path %s %s", cgroupRoot, cgroupDir) <ide> if err != nil { <ide> //unsupported subystem <ide> continue <ide> func (i *info) IsRunning() bool { <ide> <ide> output, err := i.driver.getInfo(i.ID) <ide> if err != nil { <del> log.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output) <add> logrus.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output) <ide> return false <ide> } <ide> if strings.Contains(string(output), "RUNNING") { <ide><path>daemon/execdriver/lxc/lxc_template.go <ide> import ( <ide> "strings" <ide> "text/template" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> nativeTemplate "github.com/docker/docker/daemon/execdriver/native/template" <ide> "github.com/docker/docker/utils" <ide> func escapeFstabSpaces(field string) string { <ide> <ide> func keepCapabilities(adds []string, drops []string) ([]string, error) { <ide> container := nativeTemplate.New() <del> log.Debugf("adds %s drops %s\n", adds, drops) <add> logrus.Debugf("adds %s drops %s\n", adds, drops) <ide> caps, err := execdriver.TweakCapabilities(container.Capabilities, adds, drops) <ide> if err != nil { <ide> return nil, err <ide> } <ide> var newCaps []string <ide> for _, cap := range caps { <del> log.Debugf("cap %s\n", cap) <add> logrus.Debugf("cap %s\n", cap) <ide> realCap := execdriver.GetCapability(cap) <ide> numCap := fmt.Sprintf("%d", realCap.Value) <ide> newCaps = append(newCaps, numCap) <ide> func dropList(drops []string) ([]string, error) { <ide> var newCaps []string <ide> for _, capName := range execdriver.GetAllCapabilities() { <ide> cap := execdriver.GetCapability(capName) <del> log.Debugf("drop cap %s\n", cap.Key) <add> logrus.Debugf("drop cap %s\n", cap.Key) <ide> numCap := fmt.Sprintf("%d", cap.Value) <ide> newCaps = append(newCaps, numCap) <ide> } <ide> func dropList(drops []string) ([]string, error) { <ide> <ide> func isDirectory(source string) string { <ide> f, err := os.Stat(source) <del> log.Debugf("dir: %s\n", source) <add> logrus.Debugf("dir: %s\n", source) <ide> if err != nil { <ide> if os.IsNotExist(err) { <ide> return "dir" <ide><path>daemon/execdriver/native/driver.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/reexec" <ide> sysinfo "github.com/docker/docker/pkg/system" <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> oomKillNotification, err := cont.NotifyOOM() <ide> if err != nil { <ide> oomKillNotification = nil <del> log.Warnf("Your kernel does not support OOM notifications: %s", err) <add> logrus.Warnf("Your kernel does not support OOM notifications: %s", err) <ide> } <ide> waitF := p.Wait <ide> if nss := cont.Config().Namespaces; nss.Contains(configs.NEWPID) { <ide> func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*o <ide> for _, pid := range processes { <ide> process, err := os.FindProcess(pid) <ide> if err != nil { <del> log.Errorf("Failed to kill process: %d", pid) <add> logrus.Errorf("Failed to kill process: %d", pid) <ide> continue <ide> } <ide> process.Kill() <ide><path>daemon/graphdriver/aufs/aufs.go <ide> import ( <ide> "sync" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> func (a *Driver) Remove(id string) error { <ide> defer a.Unlock() <ide> <ide> if a.active[id] != 0 { <del> log.Errorf("Removing active id %s", id) <add> logrus.Errorf("Removing active id %s", id) <ide> } <ide> <ide> // Make sure the dir is umounted first <ide> func (a *Driver) Cleanup() error { <ide> <ide> for _, id := range ids { <ide> if err := a.unmount(id); err != nil { <del> log.Errorf("Unmounting %s: %s", stringid.TruncateID(id), err) <add> logrus.Errorf("Unmounting %s: %s", stringid.TruncateID(id), err) <ide> } <ide> } <ide> <ide><path>daemon/graphdriver/aufs/mount.go <ide> import ( <ide> "os/exec" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> func Unmount(target string) error { <ide> if err := exec.Command("auplink", target, "flush").Run(); err != nil { <del> log.Errorf("Couldn't run auplink before unmount: %s", err) <add> logrus.Errorf("Couldn't run auplink before unmount: %s", err) <ide> } <ide> if err := syscall.Unmount(target, 0); err != nil { <ide> return err <ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/devicemapper" <ide> "github.com/docker/docker/pkg/parsers" <ide> func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) { <ide> if !os.IsNotExist(err) { <ide> return "", err <ide> } <del> log.Debugf("Creating loopback file %s for device-manage use", filename) <add> logrus.Debugf("Creating loopback file %s for device-manage use", filename) <ide> file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600) <ide> if err != nil { <ide> return "", err <ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) <ide> <ide> // Skip some of the meta files which are not device files. <ide> if strings.HasSuffix(finfo.Name(), ".migrated") { <del> log.Debugf("Skipping file %s", path) <add> logrus.Debugf("Skipping file %s", path) <ide> return nil <ide> } <ide> <ide> if strings.HasPrefix(finfo.Name(), ".") { <del> log.Debugf("Skipping file %s", path) <add> logrus.Debugf("Skipping file %s", path) <ide> return nil <ide> } <ide> <ide> if finfo.Name() == deviceSetMetaFile { <del> log.Debugf("Skipping file %s", path) <add> logrus.Debugf("Skipping file %s", path) <ide> return nil <ide> } <ide> <del> log.Debugf("Loading data for file %s", path) <add> logrus.Debugf("Loading data for file %s", path) <ide> <ide> hash := finfo.Name() <ide> if hash == "base" { <ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) <ide> } <ide> <ide> if dinfo.DeviceId > MaxDeviceId { <del> log.Errorf("Ignoring Invalid DeviceId=%d", dinfo.DeviceId) <add> logrus.Errorf("Ignoring Invalid DeviceId=%d", dinfo.DeviceId) <ide> return nil <ide> } <ide> <ide> devices.Lock() <ide> devices.markDeviceIdUsed(dinfo.DeviceId) <ide> devices.Unlock() <ide> <del> log.Debugf("Added deviceId=%d to DeviceIdMap", dinfo.DeviceId) <add> logrus.Debugf("Added deviceId=%d to DeviceIdMap", dinfo.DeviceId) <ide> return nil <ide> } <ide> <ide> func (devices *DeviceSet) constructDeviceIdMap() error { <del> log.Debugf("[deviceset] constructDeviceIdMap()") <del> defer log.Debugf("[deviceset] constructDeviceIdMap() END") <add> logrus.Debugf("[deviceset] constructDeviceIdMap()") <add> defer logrus.Debugf("[deviceset] constructDeviceIdMap() END") <ide> <ide> var scan = func(path string, info os.FileInfo, err error) error { <ide> if err != nil { <del> log.Debugf("Can't walk the file %s", path) <add> logrus.Debugf("Can't walk the file %s", path) <ide> return nil <ide> } <ide> <ide> func (devices *DeviceSet) constructDeviceIdMap() error { <ide> } <ide> <ide> func (devices *DeviceSet) unregisterDevice(id int, hash string) error { <del> log.Debugf("unregisterDevice(%v, %v)", id, hash) <add> logrus.Debugf("unregisterDevice(%v, %v)", id, hash) <ide> info := &DevInfo{ <ide> Hash: hash, <ide> DeviceId: id, <ide> func (devices *DeviceSet) unregisterDevice(id int, hash string) error { <ide> devices.devicesLock.Unlock() <ide> <ide> if err := devices.removeMetadata(info); err != nil { <del> log.Debugf("Error removing metadata: %s", err) <add> logrus.Debugf("Error removing metadata: %s", err) <ide> return err <ide> } <ide> <ide> return nil <ide> } <ide> <ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64, transactionId uint64) (*DevInfo, error) { <del> log.Debugf("registerDevice(%v, %v)", id, hash) <add> logrus.Debugf("registerDevice(%v, %v)", id, hash) <ide> info := &DevInfo{ <ide> Hash: hash, <ide> DeviceId: id, <ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64, trans <ide> } <ide> <ide> func (devices *DeviceSet) activateDeviceIfNeeded(info *DevInfo) error { <del> log.Debugf("activateDeviceIfNeeded(%v)", info.Hash) <add> logrus.Debugf("activateDeviceIfNeeded(%v)", info.Hash) <ide> <ide> if devinfo, _ := devicemapper.GetInfo(info.Name()); devinfo != nil && devinfo.Exists != 0 { <ide> return nil <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { <ide> } <ide> <ide> if err := devices.openTransaction(hash, deviceId); err != nil { <del> log.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) <add> logrus.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) <ide> devices.markDeviceIdFree(deviceId) <ide> return nil, err <ide> } <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { <ide> // happen. Now we have a mechianism to find <ide> // a free device Id. So something is not right. <ide> // Give a warning and continue. <del> log.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) <add> logrus.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) <ide> deviceId, err = devices.getNextFreeDeviceId() <ide> if err != nil { <ide> return nil, err <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { <ide> devices.refreshTransaction(deviceId) <ide> continue <ide> } <del> log.Debugf("Error creating device: %s", err) <add> logrus.Debugf("Error creating device: %s", err) <ide> devices.markDeviceIdFree(deviceId) <ide> return nil, err <ide> } <ide> break <ide> } <ide> <del> log.Debugf("Registering device (id %v) with FS size %v", deviceId, devices.baseFsSize) <add> logrus.Debugf("Registering device (id %v) with FS size %v", deviceId, devices.baseFsSize) <ide> info, err := devices.registerDevice(deviceId, hash, devices.baseFsSize, devices.OpenTransactionId) <ide> if err != nil { <ide> _ = devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInf <ide> } <ide> <ide> if err := devices.openTransaction(hash, deviceId); err != nil { <del> log.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) <add> logrus.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) <ide> devices.markDeviceIdFree(deviceId) <ide> return err <ide> } <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInf <ide> // happen. Now we have a mechianism to find <ide> // a free device Id. So something is not right. <ide> // Give a warning and continue. <del> log.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) <add> logrus.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) <ide> deviceId, err = devices.getNextFreeDeviceId() <ide> if err != nil { <ide> return err <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInf <ide> devices.refreshTransaction(deviceId) <ide> continue <ide> } <del> log.Debugf("Error creating snap device: %s", err) <add> logrus.Debugf("Error creating snap device: %s", err) <ide> devices.markDeviceIdFree(deviceId) <ide> return err <ide> } <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInf <ide> if _, err := devices.registerDevice(deviceId, hash, baseInfo.Size, devices.OpenTransactionId); err != nil { <ide> devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) <ide> devices.markDeviceIdFree(deviceId) <del> log.Debugf("Error registering device: %s", err) <add> logrus.Debugf("Error registering device: %s", err) <ide> return err <ide> } <ide> <ide> func (devices *DeviceSet) setupBaseImage() error { <ide> } <ide> <ide> if oldInfo != nil && !oldInfo.Initialized { <del> log.Debugf("Removing uninitialized base image") <add> logrus.Debugf("Removing uninitialized base image") <ide> if err := devices.DeleteDevice(""); err != nil { <ide> return err <ide> } <ide> func (devices *DeviceSet) setupBaseImage() error { <ide> } <ide> } <ide> <del> log.Debugf("Initializing base device-mapper thin volume") <add> logrus.Debugf("Initializing base device-mapper thin volume") <ide> <ide> // Create initial device <ide> info, err := devices.createRegisterDevice("") <ide> if err != nil { <ide> return err <ide> } <ide> <del> log.Debugf("Creating filesystem on base device-mapper thin volume") <add> logrus.Debugf("Creating filesystem on base device-mapper thin volume") <ide> <ide> if err = devices.activateDeviceIfNeeded(info); err != nil { <ide> return err <ide> func (devices *DeviceSet) DMLog(level int, file string, line int, dmError int, m <ide> } <ide> <ide> // FIXME(vbatts) push this back into ./pkg/devicemapper/ <del> log.Debugf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) <add> logrus.Debugf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) <ide> } <ide> <ide> func major(device uint64) uint64 { <ide> func (devices *DeviceSet) removeTransactionMetaData() error { <ide> } <ide> <ide> func (devices *DeviceSet) rollbackTransaction() error { <del> log.Debugf("Rolling back open transaction: TransactionId=%d hash=%s device_id=%d", devices.OpenTransactionId, devices.DeviceIdHash, devices.DeviceId) <add> logrus.Debugf("Rolling back open transaction: TransactionId=%d hash=%s device_id=%d", devices.OpenTransactionId, devices.DeviceIdHash, devices.DeviceId) <ide> <ide> // A device id might have already been deleted before transaction <ide> // closed. In that case this call will fail. Just leave a message <ide> // in case of failure. <ide> if err := devicemapper.DeleteDevice(devices.getPoolDevName(), devices.DeviceId); err != nil { <del> log.Errorf("Unable to delete device: %s", err) <add> logrus.Errorf("Unable to delete device: %s", err) <ide> } <ide> <ide> dinfo := &DevInfo{Hash: devices.DeviceIdHash} <ide> if err := devices.removeMetadata(dinfo); err != nil { <del> log.Errorf("Unable to remove metadata: %s", err) <add> logrus.Errorf("Unable to remove metadata: %s", err) <ide> } else { <ide> devices.markDeviceIdFree(devices.DeviceId) <ide> } <ide> <ide> if err := devices.removeTransactionMetaData(); err != nil { <del> log.Errorf("Unable to remove transaction meta file %s: %s", devices.transactionMetaFile(), err) <add> logrus.Errorf("Unable to remove transaction meta file %s: %s", devices.transactionMetaFile(), err) <ide> } <ide> <ide> return nil <ide> func (devices *DeviceSet) processPendingTransaction() error { <ide> // If open transaction Id is less than pool transaction Id, something <ide> // is wrong. Bail out. <ide> if devices.OpenTransactionId < devices.TransactionId { <del> log.Errorf("Open Transaction id %d is less than pool transaction id %d", devices.OpenTransactionId, devices.TransactionId) <add> logrus.Errorf("Open Transaction id %d is less than pool transaction id %d", devices.OpenTransactionId, devices.TransactionId) <ide> return nil <ide> } <ide> <ide> func (devices *DeviceSet) refreshTransaction(DeviceId int) error { <ide> <ide> func (devices *DeviceSet) closeTransaction() error { <ide> if err := devices.updatePoolTransactionId(); err != nil { <del> log.Debugf("Failed to close Transaction") <add> logrus.Debugf("Failed to close Transaction") <ide> return err <ide> } <ide> return nil <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> <ide> // https://github.com/docker/docker/issues/4036 <ide> if supported := devicemapper.UdevSetSyncSupport(true); !supported { <del> log.Warnf("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors") <add> logrus.Warnf("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors") <ide> } <del> log.Debugf("devicemapper: udev sync support: %v", devicemapper.UdevSyncSupported()) <add> logrus.Debugf("devicemapper: udev sync support: %v", devicemapper.UdevSyncSupported()) <ide> <ide> if err := os.MkdirAll(devices.metadataDir(), 0700); err != nil && !os.IsExist(err) { <ide> return err <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> // - The target of this device is at major <maj> and minor <min> <ide> // - If <inode> is defined, use that file inside the device as a loopback image. Otherwise use the device itself. <ide> devices.devicePrefix = fmt.Sprintf("docker-%d:%d-%d", major(sysSt.Dev), minor(sysSt.Dev), sysSt.Ino) <del> log.Debugf("Generated prefix: %s", devices.devicePrefix) <add> logrus.Debugf("Generated prefix: %s", devices.devicePrefix) <ide> <ide> // Check for the existence of the thin-pool device <del> log.Debugf("Checking for existence of the pool '%s'", devices.getPoolName()) <add> logrus.Debugf("Checking for existence of the pool '%s'", devices.getPoolName()) <ide> info, err := devicemapper.GetInfo(devices.getPoolName()) <ide> if info == nil { <del> log.Debugf("Error device devicemapper.GetInfo: %s", err) <add> logrus.Debugf("Error device devicemapper.GetInfo: %s", err) <ide> return err <ide> } <ide> <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> <ide> // If the pool doesn't exist, create it <ide> if info.Exists == 0 && devices.thinPoolDevice == "" { <del> log.Debugf("Pool doesn't exist. Creating it.") <add> logrus.Debugf("Pool doesn't exist. Creating it.") <ide> <ide> var ( <ide> dataFile *os.File <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> <ide> data, err := devices.ensureImage("data", devices.dataLoopbackSize) <ide> if err != nil { <del> log.Debugf("Error device ensureImage (data): %s", err) <add> logrus.Debugf("Error device ensureImage (data): %s", err) <ide> return err <ide> } <ide> <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> <ide> metadata, err := devices.ensureImage("metadata", devices.metaDataLoopbackSize) <ide> if err != nil { <del> log.Debugf("Error device ensureImage (metadata): %s", err) <add> logrus.Debugf("Error device ensureImage (metadata): %s", err) <ide> return err <ide> } <ide> <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> // Setup the base image <ide> if doInit { <ide> if err := devices.setupBaseImage(); err != nil { <del> log.Debugf("Error device setupBaseImage: %s", err) <add> logrus.Debugf("Error device setupBaseImage: %s", err) <ide> return err <ide> } <ide> } <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> } <ide> <ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error { <del> log.Debugf("[deviceset] AddDevice(hash=%s basehash=%s)", hash, baseHash) <del> defer log.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash) <add> logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s)", hash, baseHash) <add> defer logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash) <ide> <ide> baseInfo, err := devices.lookupDevice(baseHash) <ide> if err != nil { <ide> func (devices *DeviceSet) deleteDevice(info *DevInfo) error { <ide> // manually <ide> if err := devices.activateDeviceIfNeeded(info); err == nil { <ide> if err := devicemapper.BlockDeviceDiscard(info.DevName()); err != nil { <del> log.Debugf("Error discarding block on device: %s (ignoring)", err) <add> logrus.Debugf("Error discarding block on device: %s (ignoring)", err) <ide> } <ide> } <ide> } <ide> <ide> devinfo, _ := devicemapper.GetInfo(info.Name()) <ide> if devinfo != nil && devinfo.Exists != 0 { <ide> if err := devices.removeDeviceAndWait(info.Name()); err != nil { <del> log.Debugf("Error removing device: %s", err) <add> logrus.Debugf("Error removing device: %s", err) <ide> return err <ide> } <ide> } <ide> <ide> if err := devices.openTransaction(info.Hash, info.DeviceId); err != nil { <del> log.Debugf("Error opening transaction hash = %s deviceId = %d", "", info.DeviceId) <add> logrus.Debugf("Error opening transaction hash = %s deviceId = %d", "", info.DeviceId) <ide> return err <ide> } <ide> <ide> if err := devicemapper.DeleteDevice(devices.getPoolDevName(), info.DeviceId); err != nil { <del> log.Debugf("Error deleting device: %s", err) <add> logrus.Debugf("Error deleting device: %s", err) <ide> return err <ide> } <ide> <ide> func (devices *DeviceSet) DeleteDevice(hash string) error { <ide> } <ide> <ide> func (devices *DeviceSet) deactivatePool() error { <del> log.Debugf("[devmapper] deactivatePool()") <del> defer log.Debugf("[devmapper] deactivatePool END") <add> logrus.Debugf("[devmapper] deactivatePool()") <add> defer logrus.Debugf("[devmapper] deactivatePool END") <ide> devname := devices.getPoolDevName() <ide> <ide> devinfo, err := devicemapper.GetInfo(devname) <ide> func (devices *DeviceSet) deactivatePool() error { <ide> } <ide> if d, err := devicemapper.GetDeps(devname); err == nil { <ide> // Access to more Debug output <del> log.Debugf("[devmapper] devicemapper.GetDeps() %s: %#v", devname, d) <add> logrus.Debugf("[devmapper] devicemapper.GetDeps() %s: %#v", devname, d) <ide> } <ide> if devinfo.Exists != 0 { <ide> return devicemapper.RemoveDevice(devname) <ide> func (devices *DeviceSet) deactivatePool() error { <ide> } <ide> <ide> func (devices *DeviceSet) deactivateDevice(info *DevInfo) error { <del> log.Debugf("[devmapper] deactivateDevice(%s)", info.Hash) <del> defer log.Debugf("[devmapper] deactivateDevice END(%s)", info.Hash) <add> logrus.Debugf("[devmapper] deactivateDevice(%s)", info.Hash) <add> defer logrus.Debugf("[devmapper] deactivateDevice END(%s)", info.Hash) <ide> <ide> // Wait for the unmount to be effective, <ide> // by watching the value of Info.OpenCount for the device <ide> if err := devices.waitClose(info); err != nil { <del> log.Errorf("Error waiting for device %s to close: %s", info.Hash, err) <add> logrus.Errorf("Error waiting for device %s to close: %s", info.Hash, err) <ide> } <ide> <ide> devinfo, err := devicemapper.GetInfo(info.Name()) <ide> func (devices *DeviceSet) removeDeviceAndWait(devname string) error { <ide> // a) the device registered at <device_set_prefix>-<hash> is removed, <ide> // or b) the 10 second timeout expires. <ide> func (devices *DeviceSet) waitRemove(devname string) error { <del> log.Debugf("[deviceset %s] waitRemove(%s)", devices.devicePrefix, devname) <del> defer log.Debugf("[deviceset %s] waitRemove(%s) END", devices.devicePrefix, devname) <add> logrus.Debugf("[deviceset %s] waitRemove(%s)", devices.devicePrefix, devname) <add> defer logrus.Debugf("[deviceset %s] waitRemove(%s) END", devices.devicePrefix, devname) <ide> i := 0 <ide> for ; i < 1000; i++ { <ide> devinfo, err := devicemapper.GetInfo(devname) <ide> func (devices *DeviceSet) waitRemove(devname string) error { <ide> return nil <ide> } <ide> if i%100 == 0 { <del> log.Debugf("Waiting for removal of %s: exists=%d", devname, devinfo.Exists) <add> logrus.Debugf("Waiting for removal of %s: exists=%d", devname, devinfo.Exists) <ide> } <ide> if devinfo.Exists == 0 { <ide> break <ide> func (devices *DeviceSet) waitClose(info *DevInfo) error { <ide> return err <ide> } <ide> if i%100 == 0 { <del> log.Debugf("Waiting for unmount of %s: opencount=%d", info.Hash, devinfo.OpenCount) <add> logrus.Debugf("Waiting for unmount of %s: opencount=%d", info.Hash, devinfo.OpenCount) <ide> } <ide> if devinfo.OpenCount == 0 { <ide> break <ide> func (devices *DeviceSet) waitClose(info *DevInfo) error { <ide> } <ide> <ide> func (devices *DeviceSet) Shutdown() error { <del> log.Debugf("[deviceset %s] Shutdown()", devices.devicePrefix) <del> log.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root) <del> defer log.Debugf("[deviceset %s] Shutdown() END", devices.devicePrefix) <add> logrus.Debugf("[deviceset %s] Shutdown()", devices.devicePrefix) <add> logrus.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root) <add> defer logrus.Debugf("[deviceset %s] Shutdown() END", devices.devicePrefix) <ide> <ide> var devs []*DevInfo <ide> <ide> func (devices *DeviceSet) Shutdown() error { <ide> // container. This means it'll go away from the global scope directly, <ide> // and the device will be released when that container dies. <ide> if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil { <del> log.Debugf("Shutdown unmounting %s, error: %s", info.mountPath, err) <add> logrus.Debugf("Shutdown unmounting %s, error: %s", info.mountPath, err) <ide> } <ide> <ide> devices.Lock() <ide> if err := devices.deactivateDevice(info); err != nil { <del> log.Debugf("Shutdown deactivate %s , error: %s", info.Hash, err) <add> logrus.Debugf("Shutdown deactivate %s , error: %s", info.Hash, err) <ide> } <ide> devices.Unlock() <ide> } <ide> func (devices *DeviceSet) Shutdown() error { <ide> info.lock.Lock() <ide> devices.Lock() <ide> if err := devices.deactivateDevice(info); err != nil { <del> log.Debugf("Shutdown deactivate base , error: %s", err) <add> logrus.Debugf("Shutdown deactivate base , error: %s", err) <ide> } <ide> devices.Unlock() <ide> info.lock.Unlock() <ide> func (devices *DeviceSet) Shutdown() error { <ide> devices.Lock() <ide> if devices.thinPoolDevice == "" { <ide> if err := devices.deactivatePool(); err != nil { <del> log.Debugf("Shutdown deactivate pool , error: %s", err) <add> logrus.Debugf("Shutdown deactivate pool , error: %s", err) <ide> } <ide> } <ide> <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> } <ide> <ide> func (devices *DeviceSet) UnmountDevice(hash string) error { <del> log.Debugf("[devmapper] UnmountDevice(hash=%s)", hash) <del> defer log.Debugf("[devmapper] UnmountDevice(hash=%s) END", hash) <add> logrus.Debugf("[devmapper] UnmountDevice(hash=%s)", hash) <add> defer logrus.Debugf("[devmapper] UnmountDevice(hash=%s) END", hash) <ide> <ide> info, err := devices.lookupDevice(hash) <ide> if err != nil { <ide> func (devices *DeviceSet) UnmountDevice(hash string) error { <ide> return nil <ide> } <ide> <del> log.Debugf("[devmapper] Unmount(%s)", info.mountPath) <add> logrus.Debugf("[devmapper] Unmount(%s)", info.mountPath) <ide> if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil { <ide> return err <ide> } <del> log.Debugf("[devmapper] Unmount done") <add> logrus.Debugf("[devmapper] Unmount done") <ide> <ide> if err := devices.deactivateDevice(info); err != nil { <ide> return err <ide> func (devices *DeviceSet) getUnderlyingAvailableSpace(loopFile string) (uint64, <ide> buf := new(syscall.Statfs_t) <ide> err := syscall.Statfs(loopFile, buf) <ide> if err != nil { <del> log.Warnf("Couldn't stat loopfile filesystem %v: %v", loopFile, err) <add> logrus.Warnf("Couldn't stat loopfile filesystem %v: %v", loopFile, err) <ide> return 0, err <ide> } <ide> return buf.Bfree * uint64(buf.Bsize), nil <ide> func (devices *DeviceSet) isRealFile(loopFile string) (bool, error) { <ide> if loopFile != "" { <ide> fi, err := os.Stat(loopFile) <ide> if err != nil { <del> log.Warnf("Couldn't stat loopfile %v: %v", loopFile, err) <add> logrus.Warnf("Couldn't stat loopfile %v: %v", loopFile, err) <ide> return false, err <ide> } <ide> return fi.Mode().IsRegular(), nil <ide><path>daemon/graphdriver/devmapper/driver.go <ide> import ( <ide> "os" <ide> "path" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/devicemapper" <ide> "github.com/docker/docker/pkg/mount" <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> func (d *Driver) Put(id string) error { <ide> err := d.DeviceSet.UnmountDevice(id) <ide> if err != nil { <del> log.Errorf("Error unmounting device %s: %s", id, err) <add> logrus.Errorf("Error unmounting device %s: %s", id, err) <ide> } <ide> return err <ide> } <ide><path>daemon/graphdriver/driver.go <ide> import ( <ide> "path" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/archive" <ide> ) <ide> <ide> func checkPriorDriver(name, root string) { <ide> } <ide> } <ide> if len(priorDrivers) > 0 { <del> log.Warnf("Graphdriver %s selected. Your graphdriver directory %s already contains data managed by other graphdrivers: %s", name, root, strings.Join(priorDrivers, ",")) <add> logrus.Warnf("Graphdriver %s selected. Your graphdriver directory %s already contains data managed by other graphdrivers: %s", name, root, strings.Join(priorDrivers, ",")) <ide> } <ide> } <ide><path>daemon/graphdriver/fsdiff.go <ide> package graphdriver <ide> import ( <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/ioutils" <ide> func (gdw *naiveDiffDriver) ApplyDiff(id, parent string, diff archive.ArchiveRea <ide> defer driver.Put(id) <ide> <ide> start := time.Now().UTC() <del> log.Debugf("Start untar layer") <add> logrus.Debugf("Start untar layer") <ide> if size, err = chrootarchive.ApplyLayer(layerFs, diff); err != nil { <ide> return <ide> } <del> log.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds()) <add> logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds()) <ide> <ide> return <ide> } <ide><path>daemon/graphdriver/overlay/overlay.go <ide> import ( <ide> "sync" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> func Init(home string, options []string) (graphdriver.Driver, error) { <ide> // check if they are running over btrfs or aufs <ide> switch fsMagic { <ide> case graphdriver.FsMagicBtrfs: <del> log.Error("'overlay' is not supported over btrfs.") <add> logrus.Error("'overlay' is not supported over btrfs.") <ide> return nil, graphdriver.ErrIncompatibleFS <ide> case graphdriver.FsMagicAufs: <del> log.Error("'overlay' is not supported over aufs.") <add> logrus.Error("'overlay' is not supported over aufs.") <ide> return nil, graphdriver.ErrIncompatibleFS <ide> case graphdriver.FsMagicZfs: <del> log.Error("'overlay' is not supported over zfs.") <add> logrus.Error("'overlay' is not supported over zfs.") <ide> return nil, graphdriver.ErrIncompatibleFS <ide> } <ide> <ide> func supportsOverlay() error { <ide> return nil <ide> } <ide> } <del> log.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.") <add> logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.") <ide> return graphdriver.ErrNotSupported <ide> } <ide> <ide> func (d *Driver) Put(id string) error { <ide> <ide> mount := d.active[id] <ide> if mount == nil { <del> log.Debugf("Put on a non-mounted device %s", id) <add> logrus.Debugf("Put on a non-mounted device %s", id) <ide> return nil <ide> } <ide> <ide> func (d *Driver) Put(id string) error { <ide> if mount.mounted { <ide> err := syscall.Unmount(mount.path, 0) <ide> if err != nil { <del> log.Debugf("Failed to unmount %s overlay: %v", id, err) <add> logrus.Debugf("Failed to unmount %s overlay: %v", id, err) <ide> } <ide> return err <ide> } <ide><path>daemon/info.go <ide> import ( <ide> "runtime" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> func (daemon *Daemon) CmdInfo(job *engine.Job) error { <ide> operatingSystem = s <ide> } <ide> if inContainer, err := operatingsystem.IsContainerized(); err != nil { <del> log.Errorf("Could not determine if daemon is containerized: %v", err) <add> logrus.Errorf("Could not determine if daemon is containerized: %v", err) <ide> operatingSystem += " (error determining if containerized)" <ide> } else if inContainer { <ide> operatingSystem += " (containerized)" <ide> } <ide> <ide> meminfo, err := system.ReadMemInfo() <ide> if err != nil { <del> log.Errorf("Could not read system memory info: %v", err) <add> logrus.Errorf("Could not read system memory info: %v", err) <ide> } <ide> <ide> // if we still have the original dockerinit binary from before we copied it locally, let's return the path to that, since that's more intuitive (the copied path is trivial to derive by hand given VERSION) <ide><path>daemon/logs.go <ide> import ( <ide> "strconv" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/jsonlog" <ide> "github.com/docker/docker/pkg/tailfile" <ide> func (daemon *Daemon) ContainerLogs(job *engine.Job) error { <ide> cLog, err := container.ReadLog("json") <ide> if err != nil && os.IsNotExist(err) { <ide> // Legacy logs <del> log.Debugf("Old logs format") <add> logrus.Debugf("Old logs format") <ide> if stdout { <ide> cLog, err := container.ReadLog("stdout") <ide> if err != nil { <del> log.Errorf("Error reading logs (stdout): %s", err) <add> logrus.Errorf("Error reading logs (stdout): %s", err) <ide> } else if _, err := io.Copy(job.Stdout, cLog); err != nil { <del> log.Errorf("Error streaming logs (stdout): %s", err) <add> logrus.Errorf("Error streaming logs (stdout): %s", err) <ide> } <ide> } <ide> if stderr { <ide> cLog, err := container.ReadLog("stderr") <ide> if err != nil { <del> log.Errorf("Error reading logs (stderr): %s", err) <add> logrus.Errorf("Error reading logs (stderr): %s", err) <ide> } else if _, err := io.Copy(job.Stderr, cLog); err != nil { <del> log.Errorf("Error streaming logs (stderr): %s", err) <add> logrus.Errorf("Error streaming logs (stderr): %s", err) <ide> } <ide> } <ide> } else if err != nil { <del> log.Errorf("Error reading logs (json): %s", err) <add> logrus.Errorf("Error reading logs (json): %s", err) <ide> } else { <ide> if tail != "all" { <ide> var err error <ide> lines, err = strconv.Atoi(tail) <ide> if err != nil { <del> log.Errorf("Failed to parse tail %s, error: %v, show all logs", tail, err) <add> logrus.Errorf("Failed to parse tail %s, error: %v, show all logs", tail, err) <ide> lines = -1 <ide> } <ide> } <ide> func (daemon *Daemon) ContainerLogs(job *engine.Job) error { <ide> if err := dec.Decode(l); err == io.EOF { <ide> break <ide> } else if err != nil { <del> log.Errorf("Error streaming logs: %s", err) <add> logrus.Errorf("Error streaming logs: %s", err) <ide> break <ide> } <ide> logLine := l.Log <ide> func (daemon *Daemon) ContainerLogs(job *engine.Job) error { <ide> <ide> for err := range errors { <ide> if err != nil { <del> log.Errorf("%s", err) <add> logrus.Errorf("%s", err) <ide> } <ide> } <ide> <ide><path>daemon/monitor.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/runconfig" <ide> func (m *containerMonitor) Close() error { <ide> // because they share same runconfig and change image. Must be fixed <ide> // in builder/builder.go <ide> if err := m.container.toDisk(); err != nil { <del> log.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err) <add> logrus.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err) <ide> <ide> return err <ide> } <ide> func (m *containerMonitor) Start() error { <ide> return err <ide> } <ide> <del> log.Errorf("Error running container: %s", err) <add> logrus.Errorf("Error running container: %s", err) <ide> } <ide> <ide> // here container.Lock is already lost <ide> func (m *containerMonitor) shouldRestart(exitCode int) bool { <ide> case "on-failure": <ide> // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count <ide> if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max { <del> log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached", <add> logrus.Debugf("stopping restart of container %s because maximum failure could of %d has been reached", <ide> stringid.TruncateID(m.container.ID), max) <ide> return false <ide> } <ide> func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid <ide> } <ide> <ide> if err := m.container.ToDisk(); err != nil { <del> log.Debugf("%s", err) <add> logrus.Debugf("%s", err) <ide> } <ide> } <ide> <ide> func (m *containerMonitor) resetContainer(lock bool) { <ide> <ide> if container.Config.OpenStdin { <ide> if err := container.stdin.Close(); err != nil { <del> log.Errorf("%s: Error close stdin: %s", container.ID, err) <add> logrus.Errorf("%s: Error close stdin: %s", container.ID, err) <ide> } <ide> } <ide> <ide> if err := container.stdout.Clean(); err != nil { <del> log.Errorf("%s: Error close stdout: %s", container.ID, err) <add> logrus.Errorf("%s: Error close stdout: %s", container.ID, err) <ide> } <ide> <ide> if err := container.stderr.Clean(); err != nil { <del> log.Errorf("%s: Error close stderr: %s", container.ID, err) <add> logrus.Errorf("%s: Error close stderr: %s", container.ID, err) <ide> } <ide> <ide> if container.command != nil && container.command.ProcessConfig.Terminal != nil { <ide> if err := container.command.ProcessConfig.Terminal.Close(); err != nil { <del> log.Errorf("%s: Error closing terminal: %s", container.ID, err) <add> logrus.Errorf("%s: Error closing terminal: %s", container.ID, err) <ide> } <ide> } <ide> <ide> func (m *containerMonitor) resetContainer(lock bool) { <ide> }() <ide> select { <ide> case <-time.After(1 * time.Second): <del> log.Warnf("Logger didn't exit in time: logs may be truncated") <add> logrus.Warnf("Logger didn't exit in time: logs may be truncated") <ide> case <-exit: <ide> } <ide> } <ide><path>daemon/networkdriver/bridge/driver.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/networkdriver" <ide> "github.com/docker/docker/daemon/networkdriver/ipallocator" <ide> "github.com/docker/docker/daemon/networkdriver/portmapper" <ide> func InitDriver(job *engine.Job) error { <ide> <ide> if fixedCIDRv6 != "" { <ide> // Setting route to global IPv6 subnet <del> log.Infof("Adding route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface) <add> logrus.Infof("Adding route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface) <ide> if err := netlink.AddRoute(fixedCIDRv6, "", "", bridgeIface); err != nil { <del> log.Fatalf("Could not add route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface) <add> logrus.Fatalf("Could not add route to IPv6 network %q via device %q", fixedCIDRv6, bridgeIface) <ide> } <ide> } <ide> } else { <ide> func InitDriver(job *engine.Job) error { <ide> if ipForward { <ide> // Enable IPv4 forwarding <ide> if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte{'1', '\n'}, 0644); err != nil { <del> log.Warnf("WARNING: unable to enable IPv4 forwarding: %s\n", err) <add> logrus.Warnf("WARNING: unable to enable IPv4 forwarding: %s\n", err) <ide> } <ide> <ide> if fixedCIDRv6 != "" { <ide> // Enable IPv6 forwarding <ide> if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/default/forwarding", []byte{'1', '\n'}, 0644); err != nil { <del> log.Warnf("WARNING: unable to enable IPv6 default forwarding: %s\n", err) <add> logrus.Warnf("WARNING: unable to enable IPv6 default forwarding: %s\n", err) <ide> } <ide> if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/all/forwarding", []byte{'1', '\n'}, 0644); err != nil { <del> log.Warnf("WARNING: unable to enable IPv6 all forwarding: %s\n", err) <add> logrus.Warnf("WARNING: unable to enable IPv6 all forwarding: %s\n", err) <ide> } <ide> } <ide> } <ide> func InitDriver(job *engine.Job) error { <ide> if err != nil { <ide> return err <ide> } <del> log.Debugf("Subnet: %v", subnet) <add> logrus.Debugf("Subnet: %v", subnet) <ide> if err := ipAllocator.RegisterSubnet(bridgeIPv4Network, subnet); err != nil { <ide> return err <ide> } <ide> func InitDriver(job *engine.Job) error { <ide> if err != nil { <ide> return err <ide> } <del> log.Debugf("Subnet: %v", subnet) <add> logrus.Debugf("Subnet: %v", subnet) <ide> if err := ipAllocator.RegisterSubnet(subnet, subnet); err != nil { <ide> return err <ide> } <ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error { <ide> iptables.Raw(append([]string{"-D", "FORWARD"}, acceptArgs...)...) <ide> <ide> if !iptables.Exists(iptables.Filter, "FORWARD", dropArgs...) { <del> log.Debugf("Disable inter-container communication") <add> logrus.Debugf("Disable inter-container communication") <ide> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, dropArgs...)...); err != nil { <ide> return fmt.Errorf("Unable to prevent intercontainer communication: %s", err) <ide> } else if len(output) != 0 { <ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error { <ide> iptables.Raw(append([]string{"-D", "FORWARD"}, dropArgs...)...) <ide> <ide> if !iptables.Exists(iptables.Filter, "FORWARD", acceptArgs...) { <del> log.Debugf("Enable inter-container communication") <add> logrus.Debugf("Enable inter-container communication") <ide> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, acceptArgs...)...); err != nil { <ide> return fmt.Errorf("Unable to allow intercontainer communication: %s", err) <ide> } else if len(output) != 0 { <ide> func configureBridge(bridgeIP string, bridgeIPv6 string, enableIPv6 bool) error <ide> ifaceAddr = addr <ide> break <ide> } else { <del> log.Debugf("%s %s", addr, err) <add> logrus.Debugf("%s %s", addr, err) <ide> } <ide> } <ide> } <ide> func configureBridge(bridgeIP string, bridgeIPv6 string, enableIPv6 bool) error <ide> if ifaceAddr == "" { <ide> return fmt.Errorf("Could not find a free IP address range for interface '%s'. Please configure its address manually and run 'docker -b %s'", bridgeIface, bridgeIface) <ide> } <del> log.Debugf("Creating bridge %s with network %s", bridgeIface, ifaceAddr) <add> logrus.Debugf("Creating bridge %s with network %s", bridgeIface, ifaceAddr) <ide> <ide> if err := createBridgeIface(bridgeIface); err != nil { <ide> // The bridge may already exist, therefore we can ignore an "exists" error <ide> func createBridgeIface(name string) error { <ide> // Only set the bridge's mac address if the kernel version is > 3.3 <ide> // before that it was not supported <ide> setBridgeMacAddr := err == nil && (kv.Kernel >= 3 && kv.Major >= 3) <del> log.Debugf("setting bridge mac address = %v", setBridgeMacAddr) <add> logrus.Debugf("setting bridge mac address = %v", setBridgeMacAddr) <ide> return netlink.CreateBridge(name, setBridgeMacAddr) <ide> } <ide> <ide> func Allocate(job *engine.Job) error { <ide> <ide> globalIPv6, err = ipAllocator.RequestIP(globalIPv6Network, requestedIPv6) <ide> if err != nil { <del> log.Errorf("Allocator: RequestIP v6: %v", err) <add> logrus.Errorf("Allocator: RequestIP v6: %v", err) <ide> return err <ide> } <del> log.Infof("Allocated IPv6 %s", globalIPv6) <add> logrus.Infof("Allocated IPv6 %s", globalIPv6) <ide> } <ide> <ide> out := engine.Env{} <ide> func Release(job *engine.Job) error { <ide> <ide> for _, nat := range containerInterface.PortMappings { <ide> if err := portmapper.Unmap(nat); err != nil { <del> log.Infof("Unable to unmap port %s: %s", nat, err) <add> logrus.Infof("Unable to unmap port %s: %s", nat, err) <ide> } <ide> } <ide> <ide> if err := ipAllocator.ReleaseIP(bridgeIPv4Network, containerInterface.IP); err != nil { <del> log.Infof("Unable to release IPv4 %s", err) <add> logrus.Infof("Unable to release IPv4 %s", err) <ide> } <ide> if globalIPv6Network != nil { <ide> if err := ipAllocator.ReleaseIP(globalIPv6Network, containerInterface.IPv6); err != nil { <del> log.Infof("Unable to release IPv6 %s", err) <add> logrus.Infof("Unable to release IPv6 %s", err) <ide> } <ide> } <ide> return nil <ide> func AllocatePort(job *engine.Job) error { <ide> // There is no point in immediately retrying to map an explicitly <ide> // chosen port. <ide> if hostPort != 0 { <del> log.Warnf("Failed to allocate and map port %d: %s", hostPort, err) <add> logrus.Warnf("Failed to allocate and map port %d: %s", hostPort, err) <ide> break <ide> } <del> log.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1) <add> logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1) <ide> } <ide> <ide> if err != nil { <ide><path>daemon/networkdriver/ipallocator/allocator.go <ide> import ( <ide> "net" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/networkdriver" <ide> ) <ide> <ide> func ipToBigInt(ip net.IP) *big.Int { <ide> return x.SetBytes(ip6) <ide> } <ide> <del> log.Errorf("ipToBigInt: Wrong IP length! %s", ip) <add> logrus.Errorf("ipToBigInt: Wrong IP length! %s", ip) <ide> return nil <ide> } <ide> <ide><path>daemon/networkdriver/portallocator/portallocator.go <ide> import ( <ide> "os" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> const ( <ide> func init() { <ide> <ide> file, err := os.Open(portRangeKernelParam) <ide> if err != nil { <del> log.Warnf("port allocator - %s due to error: %v", portRangeFallback, err) <add> logrus.Warnf("port allocator - %s due to error: %v", portRangeFallback, err) <ide> return <ide> } <ide> var start, end int <ide> func init() { <ide> if err == nil { <ide> err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) <ide> } <del> log.Errorf("port allocator - failed to parse system ephemeral port range from %s - %s: %v", portRangeKernelParam, portRangeFallback, err) <add> logrus.Errorf("port allocator - failed to parse system ephemeral port range from %s - %s: %v", portRangeKernelParam, portRangeFallback, err) <ide> return <ide> } <ide> beginPortRange = start <ide><path>daemon/networkdriver/portmapper/mapper.go <ide> import ( <ide> "net" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/networkdriver/portallocator" <ide> "github.com/docker/docker/pkg/iptables" <ide> ) <ide> func (pm *PortMapper) Unmap(host net.Addr) error { <ide> containerIP, containerPort := getIPAndPort(data.container) <ide> hostIP, hostPort := getIPAndPort(data.host) <ide> if err := pm.forward(iptables.Delete, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { <del> log.Errorf("Error on iptables delete: %s", err) <add> logrus.Errorf("Error on iptables delete: %s", err) <ide> } <ide> <ide> switch a := host.(type) { <ide><path>daemon/stats_collector.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/pubsub" <ide> "github.com/docker/libcontainer/system" <ide> func (s *statsCollector) run() { <ide> for container, publisher := range s.publishers { <ide> systemUsage, err := s.getSystemCpuUsage() <ide> if err != nil { <del> log.Errorf("collecting system cpu usage for %s: %v", container.ID, err) <add> logrus.Errorf("collecting system cpu usage for %s: %v", container.ID, err) <ide> continue <ide> } <ide> stats, err := container.Stats() <ide> if err != nil { <ide> if err != execdriver.ErrNotRunning { <del> log.Errorf("collecting stats for %s: %v", container.ID, err) <add> logrus.Errorf("collecting stats for %s: %v", container.ID, err) <ide> } <ide> continue <ide> } <ide><path>daemon/volumes.go <ide> import ( <ide> "sort" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/symlink" <ide> func (container *Container) registerVolumes() { <ide> } <ide> v, err := container.daemon.volumes.FindOrCreateVolume(path, writable) <ide> if err != nil { <del> log.Debugf("error registering volume %s: %v", path, err) <add> logrus.Debugf("error registering volume %s: %v", path, err) <ide> continue <ide> } <ide> v.AddContainer(container.ID) <ide> func (container *Container) derefVolumes() { <ide> for path := range container.VolumePaths() { <ide> vol := container.daemon.volumes.Get(path) <ide> if vol == nil { <del> log.Debugf("Volume %s was not found and could not be dereferenced", path) <add> logrus.Debugf("Volume %s was not found and could not be dereferenced", path) <ide> continue <ide> } <ide> vol.RemoveContainer(container.ID) <ide><path>docker/daemon.go <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builtins" <ide> func migrateKey() (err error) { <ide> if err == nil { <ide> err = os.Remove(oldPath) <ide> } else { <del> log.Warnf("Key migration failed, key file not removed at %s", oldPath) <add> logrus.Warnf("Key migration failed, key file not removed at %s", oldPath) <ide> } <ide> }() <ide> <ide> func migrateKey() (err error) { <ide> return fmt.Errorf("error copying key: %s", err) <ide> } <ide> <del> log.Infof("Migrated key from %s to %s", oldPath, newPath) <add> logrus.Infof("Migrated key from %s to %s", oldPath, newPath) <ide> } <ide> <ide> return nil <ide> func mainDaemon() { <ide> signal.Trap(eng.Shutdown) <ide> <ide> if err := migrateKey(); err != nil { <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> daemonCfg.TrustKeyPath = *flTrustKey <ide> <ide> // Load builtins <ide> if err := builtins.Register(eng); err != nil { <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> <ide> // load registry service <ide> if err := registry.NewService(registryCfg).Install(eng); err != nil { <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> <ide> // load the daemon in the background so we can immediately start <ide> func mainDaemon() { <ide> return <ide> } <ide> <del> log.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s", <add> logrus.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s", <ide> dockerversion.VERSION, <ide> dockerversion.GITCOMMIT, <ide> d.ExecutionDriver().Name(), <ide> func mainDaemon() { <ide> serveAPIWait := make(chan error) <ide> go func() { <ide> if err := job.Run(); err != nil { <del> log.Errorf("ServeAPI error: %v", err) <add> logrus.Errorf("ServeAPI error: %v", err) <ide> serveAPIWait <- err <ide> return <ide> } <ide> func mainDaemon() { <ide> <ide> // Wait for the daemon startup goroutine to finish <ide> // This makes sure we can actually cleanly shutdown the daemon <del> log.Debug("waiting for daemon to initialize") <add> logrus.Debug("waiting for daemon to initialize") <ide> errDaemon := <-daemonInitWait <ide> if errDaemon != nil { <ide> eng.Shutdown() <ide> func mainDaemon() { <ide> } <ide> // we must "fatal" exit here as the API server may be happy to <ide> // continue listening forever if the error had no impact to API <del> log.Fatal(outStr) <add> logrus.Fatal(outStr) <ide> } else { <del> log.Info("Daemon has completed initialization") <add> logrus.Info("Daemon has completed initialization") <ide> } <ide> <ide> // Daemon is fully initialized and handling API traffic <ide> func mainDaemon() { <ide> // exited the daemon process above) <ide> eng.Shutdown() <ide> if errAPI != nil { <del> log.Fatalf("Shutting down due to ServeAPI error: %v", errAPI) <add> logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI) <ide> } <ide> <ide> } <ide><path>docker/docker.go <ide> import ( <ide> "os" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/api/client" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> func main() { <ide> } <ide> <ide> if *flLogLevel != "" { <del> lvl, err := log.ParseLevel(*flLogLevel) <add> lvl, err := logrus.ParseLevel(*flLogLevel) <ide> if err != nil { <del> log.Fatalf("Unable to parse logging level: %s", *flLogLevel) <add> logrus.Fatalf("Unable to parse logging level: %s", *flLogLevel) <ide> } <ide> setLogLevel(lvl) <ide> } else { <del> setLogLevel(log.InfoLevel) <add> setLogLevel(logrus.InfoLevel) <ide> } <ide> <ide> // -D, --debug, -l/--log-level=debug processing <ide> // When/if -D is removed this block can be deleted <ide> if *flDebug { <ide> os.Setenv("DEBUG", "1") <del> setLogLevel(log.DebugLevel) <add> setLogLevel(logrus.DebugLevel) <ide> } <ide> <ide> if len(flHosts) == 0 { <ide> func main() { <ide> } <ide> defaultHost, err := api.ValidateHost(defaultHost) <ide> if err != nil { <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> flHosts = append(flHosts, defaultHost) <ide> } <ide> func main() { <ide> } <ide> <ide> if len(flHosts) > 1 { <del> log.Fatal("Please specify only one -H") <add> logrus.Fatal("Please specify only one -H") <ide> } <ide> protoAddrParts := strings.SplitN(flHosts[0], "://", 2) <ide> <ide> func main() { <ide> certPool := x509.NewCertPool() <ide> file, err := ioutil.ReadFile(*flCa) <ide> if err != nil { <del> log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err) <add> logrus.Fatalf("Couldn't read ca cert %s: %s", *flCa, err) <ide> } <ide> certPool.AppendCertsFromPEM(file) <ide> tlsConfig.RootCAs = certPool <ide> func main() { <ide> *flTls = true <ide> cert, err := tls.LoadX509KeyPair(*flCert, *flKey) <ide> if err != nil { <del> log.Fatalf("Couldn't load X509 key pair: %q. Make sure the key is encrypted", err) <add> logrus.Fatalf("Couldn't load X509 key pair: %q. Make sure the key is encrypted", err) <ide> } <ide> tlsConfig.Certificates = []tls.Certificate{cert} <ide> } <ide> func main() { <ide> if err := cli.Cmd(flag.Args()...); err != nil { <ide> if sterr, ok := err.(*utils.StatusError); ok { <ide> if sterr.Status != "" { <del> log.Println(sterr.Status) <add> logrus.Println(sterr.Status) <ide> } <ide> os.Exit(sterr.StatusCode) <ide> } <del> log.Fatal(err) <add> logrus.Fatal(err) <ide> } <ide> } <ide> <ide><path>docker/log.go <ide> package main <ide> <ide> import ( <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "io" <ide> ) <ide> <del>func setLogLevel(lvl log.Level) { <del> log.SetLevel(lvl) <add>func setLogLevel(lvl logrus.Level) { <add> logrus.SetLevel(lvl) <ide> } <ide> <ide> func initLogging(stderr io.Writer) { <del> log.SetOutput(stderr) <add> logrus.SetOutput(stderr) <ide> } <ide><path>engine/job.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> // A job is the fundamental unit of work in the docker engine. <ide> func (job *Job) Run() error { <ide> } <ide> // Log beginning and end of the job <ide> if job.Eng.Logging { <del> log.Infof("+job %s", job.CallString()) <add> logrus.Infof("+job %s", job.CallString()) <ide> defer func() { <ide> // what if err is nil? <del> log.Infof("-job %s%s", job.CallString(), job.err) <add> logrus.Infof("-job %s%s", job.CallString(), job.err) <ide> }() <ide> } <ide> var errorMessage = bytes.NewBuffer(nil) <ide><path>graph/export.go <ide> import ( <ide> "os" <ide> "path" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/parsers" <ide> func (s *TagStore) CmdImageExport(job *engine.Job) error { <ide> <ide> rootRepoMap := map[string]Repository{} <ide> addKey := func(name string, tag string, id string) { <del> log.Debugf("add key [%s:%s]", name, tag) <add> logrus.Debugf("add key [%s:%s]", name, tag) <ide> if repo, ok := rootRepoMap[name]; !ok { <ide> rootRepoMap[name] = Repository{tag: id} <ide> } else { <ide> func (s *TagStore) CmdImageExport(job *engine.Job) error { <ide> } <ide> for _, name := range job.Args { <ide> name = registry.NormalizeLocalName(name) <del> log.Debugf("Serializing %s", name) <add> logrus.Debugf("Serializing %s", name) <ide> rootRepo := s.Repositories[name] <ide> if rootRepo != nil { <ide> // this is a base repo name, like 'busybox' <ide> func (s *TagStore) CmdImageExport(job *engine.Job) error { <ide> } <ide> } <ide> } <del> log.Debugf("End Serializing %s", name) <add> logrus.Debugf("End Serializing %s", name) <ide> } <ide> // write repositories, if there is something to write <ide> if len(rootRepoMap) > 0 { <ide> func (s *TagStore) CmdImageExport(job *engine.Job) error { <ide> return err <ide> } <ide> } else { <del> log.Debugf("There were no repositories to write") <add> logrus.Debugf("There were no repositories to write") <ide> } <ide> <ide> fs, err := archive.Tar(tempdir, archive.Uncompressed) <ide> func (s *TagStore) CmdImageExport(job *engine.Job) error { <ide> if _, err := io.Copy(job.Stdout, fs); err != nil { <ide> return err <ide> } <del> log.Debugf("End export job: %s", job.Name) <add> logrus.Debugf("End export job: %s", job.Name) <ide> return nil <ide> } <ide> <ide><path>graph/graph.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/image" <ide> func (graph *Graph) restore() error { <ide> } <ide> } <ide> graph.idIndex = truncindex.NewTruncIndex(ids) <del> log.Debugf("Restored %d elements", len(dir)) <add> logrus.Debugf("Restored %d elements", len(dir)) <ide> return nil <ide> } <ide> <ide><path>graph/import.go <ide> import ( <ide> "net/http" <ide> "net/url" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/progressreader" <ide> func (s *TagStore) CmdImport(job *engine.Job) error { <ide> logID = utils.ImageReference(logID, tag) <ide> } <ide> if err = job.Eng.Job("log", "import", logID, "").Run(); err != nil { <del> log.Errorf("Error logging event 'import' for %s: %s", logID, err) <add> logrus.Errorf("Error logging event 'import' for %s: %s", logID, err) <ide> } <ide> return nil <ide> } <ide><path>graph/load.go <ide> import ( <ide> "os" <ide> "path" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/archive" <ide> func (s *TagStore) CmdLoad(job *engine.Job) error { <ide> <ide> func (s *TagStore) recursiveLoad(eng *engine.Engine, address, tmpImageDir string) error { <ide> if err := eng.Job("image_get", address).Run(); err != nil { <del> log.Debugf("Loading %s", address) <add> logrus.Debugf("Loading %s", address) <ide> <ide> imageJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", address, "json")) <ide> if err != nil { <del> log.Debugf("Error reading json", err) <add> logrus.Debugf("Error reading json", err) <ide> return err <ide> } <ide> <ide> layer, err := os.Open(path.Join(tmpImageDir, "repo", address, "layer.tar")) <ide> if err != nil { <del> log.Debugf("Error reading embedded tar", err) <add> logrus.Debugf("Error reading embedded tar", err) <ide> return err <ide> } <ide> img, err := image.NewImgJSON(imageJson) <ide> if err != nil { <del> log.Debugf("Error unmarshalling json", err) <add> logrus.Debugf("Error unmarshalling json", err) <ide> return err <ide> } <ide> if err := utils.ValidateID(img.ID); err != nil { <del> log.Debugf("Error validating ID: %s", err) <add> logrus.Debugf("Error validating ID: %s", err) <ide> return err <ide> } <ide> <ide> // ensure no two downloads of the same layer happen at the same time <ide> if c, err := s.poolAdd("pull", "layer:"+img.ID); err != nil { <ide> if c != nil { <del> log.Debugf("Image (id: %s) load is already running, waiting: %v", img.ID, err) <add> logrus.Debugf("Image (id: %s) load is already running, waiting: %v", img.ID, err) <ide> <-c <ide> return nil <ide> } <ide> func (s *TagStore) recursiveLoad(eng *engine.Engine, address, tmpImageDir string <ide> return err <ide> } <ide> } <del> log.Debugf("Completed processing %s", address) <add> logrus.Debugf("Completed processing %s", address) <ide> <ide> return nil <ide> } <ide><path>graph/manifest.go <ide> import ( <ide> "encoding/json" <ide> "fmt" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/registry" <ide> func (s *TagStore) loadManifest(eng *engine.Engine, manifestBytes []byte, dgst, <ide> return nil, false, fmt.Errorf("error running key check: %s", err) <ide> } <ide> result := engine.Tail(stdoutBuffer, 1) <del> log.Debugf("Key check result: %q", result) <add> logrus.Debugf("Key check result: %q", result) <ide> if result == "verified" { <ide> verified = true <ide> } <ide><path>graph/pull.go <ide> import ( <ide> "strings" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> func (s *TagStore) CmdPull(job *engine.Job) error { <ide> } <ide> defer s.poolRemove("pull", utils.ImageReference(repoInfo.LocalName, tag)) <ide> <del> log.Debugf("pulling image from host %q with remote name %q", repoInfo.Index.Name, repoInfo.RemoteName) <add> logrus.Debugf("pulling image from host %q with remote name %q", repoInfo.Index.Name, repoInfo.RemoteName) <ide> endpoint, err := repoInfo.GetEndpoint() <ide> if err != nil { <ide> return err <ide> func (s *TagStore) CmdPull(job *engine.Job) error { <ide> if repoInfo.Official { <ide> j := job.Eng.Job("trust_update_base") <ide> if err = j.Run(); err != nil { <del> log.Errorf("error updating trust base graph: %s", err) <add> logrus.Errorf("error updating trust base graph: %s", err) <ide> } <ide> } <ide> <del> log.Debugf("pulling v2 repository with local name %q", repoInfo.LocalName) <add> logrus.Debugf("pulling v2 repository with local name %q", repoInfo.LocalName) <ide> if err := s.pullV2Repository(job.Eng, r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel")); err == nil { <ide> if err = job.Eng.Job("log", "pull", logName, "").Run(); err != nil { <del> log.Errorf("Error logging event 'pull' for %s: %s", logName, err) <add> logrus.Errorf("Error logging event 'pull' for %s: %s", logName, err) <ide> } <ide> return nil <ide> } else if err != registry.ErrDoesNotExist && err != ErrV2RegistryUnavailable { <del> log.Errorf("Error from V2 registry: %s", err) <add> logrus.Errorf("Error from V2 registry: %s", err) <ide> } <ide> <del> log.Debug("image does not exist on v2 registry, falling back to v1") <add> logrus.Debug("image does not exist on v2 registry, falling back to v1") <ide> } <ide> <del> log.Debugf("pulling v1 repository with local name %q", repoInfo.LocalName) <add> logrus.Debugf("pulling v1 repository with local name %q", repoInfo.LocalName) <ide> if err = s.pullRepository(r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel")); err != nil { <ide> return err <ide> } <ide> <ide> if err = job.Eng.Job("log", "pull", logName, "").Run(); err != nil { <del> log.Errorf("Error logging event 'pull' for %s: %s", logName, err) <add> logrus.Errorf("Error logging event 'pull' for %s: %s", logName, err) <ide> } <ide> <ide> return nil <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> return err <ide> } <ide> <del> log.Debugf("Retrieving the tag list") <add> logrus.Debugf("Retrieving the tag list") <ide> tagsList, err := r.GetRemoteTags(repoData.Endpoints, repoInfo.RemoteName, repoData.Tokens) <ide> if err != nil { <del> log.Errorf("unable to get remote tags: %s", err) <add> logrus.Errorf("unable to get remote tags: %s", err) <ide> return err <ide> } <ide> <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> } <ide> } <ide> <del> log.Debugf("Registering tags") <add> logrus.Debugf("Registering tags") <ide> // If no tag has been specified, pull them all <ide> if askedTag == "" { <ide> for tag, id := range tagsList { <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> } <ide> <ide> if img.Tag == "" { <del> log.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID) <add> logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID) <ide> if parallel { <ide> errors <- nil <ide> } <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> <-c <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) <ide> } else { <del> log.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <add> logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <ide> } <ide> if parallel { <ide> errors <- nil <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, repoInfo.CanonicalName, ep), nil)) <ide> if is_downloaded, err = s.pullImage(r, out, img.ID, ep, repoData.Tokens, sf); err != nil { <ide> // Don't report errors when pulling from mirrors. <del> log.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, repoInfo.CanonicalName, ep, err) <add> logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, repoInfo.CanonicalName, ep, err) <ide> continue <ide> } <ide> layers_downloaded = layers_downloaded || is_downloaded <ide> func (s *TagStore) pullImage(r *registry.Session, out io.Writer, imgID, endpoint <ide> <ide> // ensure no two downloads of the same layer happen at the same time <ide> if c, err := s.poolAdd("pull", "layer:"+id); err != nil { <del> log.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err) <add> logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err) <ide> <-c <ide> } <ide> defer s.poolRemove("pull", "layer:"+id) <ide> func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out <ide> endpoint, err := r.V2RegistryEndpoint(repoInfo.Index) <ide> if err != nil { <ide> if repoInfo.Index.Official { <del> log.Debugf("Unable to pull from V2 registry, falling back to v1: %s", err) <add> logrus.Debugf("Unable to pull from V2 registry, falling back to v1: %s", err) <ide> return ErrV2RegistryUnavailable <ide> } <ide> return fmt.Errorf("error getting registry endpoint: %s", err) <ide> func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out <ide> } <ide> var layersDownloaded bool <ide> if tag == "" { <del> log.Debugf("Pulling tag list from V2 registry for %s", repoInfo.CanonicalName) <add> logrus.Debugf("Pulling tag list from V2 registry for %s", repoInfo.CanonicalName) <ide> tags, err := r.GetV2RemoteTags(endpoint, repoInfo.RemoteName, auth) <ide> if err != nil { <ide> return err <ide> func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out <ide> } <ide> <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, endpoint *registry.Endpoint, repoInfo *registry.RepositoryInfo, tag string, sf *streamformatter.StreamFormatter, parallel bool, auth *registry.RequestAuthorization) (bool, error) { <del> log.Debugf("Pulling tag from V2 registry: %q", tag) <add> logrus.Debugf("Pulling tag from V2 registry: %q", tag) <ide> <ide> manifestBytes, manifestDigest, err := r.GetV2ImageManifest(endpoint, repoInfo.RemoteName, tag, auth) <ide> if err != nil { <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> } <ide> <ide> if verified { <del> log.Printf("Image manifest for %s has been verified", utils.ImageReference(repoInfo.CanonicalName, tag)) <add> logrus.Printf("Image manifest for %s has been verified", utils.ImageReference(repoInfo.CanonicalName, tag)) <ide> } <ide> out.Write(sf.FormatStatus(tag, "Pulling from %s", repoInfo.CanonicalName)) <ide> <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> <ide> // Check if exists <ide> if s.graph.Exists(img.ID) { <del> log.Debugf("Image already exists: %s", img.ID) <add> logrus.Debugf("Image already exists: %s", img.ID) <ide> continue <ide> } <ide> <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Pulling fs layer", nil)) <ide> <ide> downloadFunc := func(di *downloadInfo) error { <del> log.Debugf("pulling blob %q to V1 img %s", sumStr, img.ID) <add> logrus.Debugf("pulling blob %q to V1 img %s", sumStr, img.ID) <ide> <ide> if c, err := s.poolAdd("pull", "img:"+img.ID); err != nil { <ide> if c != nil { <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil)) <ide> <-c <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) <ide> } else { <del> log.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <add> logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <ide> } <ide> } else { <ide> defer s.poolRemove("pull", "img:"+img.ID) <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Verifying Checksum", nil)) <ide> <ide> if !verifier.Verified() { <del> log.Infof("Image verification failed: checksum mismatch for %q", di.digest.String()) <add> logrus.Infof("Image verification failed: checksum mismatch for %q", di.digest.String()) <ide> verified = false <ide> } <ide> <ide> out.Write(sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) <ide> <del> log.Debugf("Downloaded %s to tempfile %s", img.ID, tmpFile.Name()) <add> logrus.Debugf("Downloaded %s to tempfile %s", img.ID, tmpFile.Name()) <ide> di.tmpFile = tmpFile <ide> di.length = l <ide> di.downloaded = true <ide><path>graph/push.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> func (s *TagStore) getImageList(localRepo map[string]string, requestedTag string <ide> if len(imageList) == 0 { <ide> return nil, nil, fmt.Errorf("No images found for the requested repository / tag") <ide> } <del> log.Debugf("Image list: %v", imageList) <del> log.Debugf("Tags by image: %v", tagsByImage) <add> logrus.Debugf("Image list: %v", imageList) <add> logrus.Debugf("Tags by image: %v", tagsByImage) <ide> <ide> return imageList, tagsByImage, nil <ide> } <ide> <ide> func (s *TagStore) getImageTags(localRepo map[string]string, askedTag string) ([]string, error) { <del> log.Debugf("Checking %s against %#v", askedTag, localRepo) <add> logrus.Debugf("Checking %s against %#v", askedTag, localRepo) <ide> if len(askedTag) > 0 { <ide> if _, ok := localRepo[askedTag]; !ok || utils.DigestReference(askedTag) { <ide> return nil, fmt.Errorf("Tag does not exist: %s", askedTag) <ide> func lookupImageOnEndpoint(wg *sync.WaitGroup, r *registry.Session, out io.Write <ide> defer wg.Done() <ide> for image := range images { <ide> if err := r.LookupRemoteImage(image.id, image.endpoint, image.tokens); err != nil { <del> log.Errorf("Error in LookupRemoteImage: %s", err) <add> logrus.Errorf("Error in LookupRemoteImage: %s", err) <ide> imagesToPush <- image.id <ide> continue <ide> } <ide> func (s *TagStore) pushImageToEndpoint(endpoint string, out io.Writer, remoteNam <ide> func (s *TagStore) pushRepository(r *registry.Session, out io.Writer, <ide> repoInfo *registry.RepositoryInfo, localRepo map[string]string, <ide> tag string, sf *streamformatter.StreamFormatter) error { <del> log.Debugf("Local repo: %s", localRepo) <add> logrus.Debugf("Local repo: %s", localRepo) <ide> out = utils.NewWriteFlusher(out) <ide> imgList, tags, err := s.getImageList(localRepo, tag) <ide> if err != nil { <ide> func (s *TagStore) pushRepository(r *registry.Session, out io.Writer, <ide> out.Write(sf.FormatStatus("", "Sending image list")) <ide> <ide> imageIndex := s.createImageIndex(imgList, tags) <del> log.Debugf("Preparing to push %s with the following images and tags", localRepo) <add> logrus.Debugf("Preparing to push %s with the following images and tags", localRepo) <ide> for _, data := range imageIndex { <del> log.Debugf("Pushing ID: %s with Tag: %s", data.ID, data.Tag) <add> logrus.Debugf("Pushing ID: %s with Tag: %s", data.ID, data.Tag) <ide> } <ide> // Register all the images in a repository with the registry <ide> // If an image is not in this list it will not be associated with the repository <ide> func (s *TagStore) pushImage(r *registry.Session, out io.Writer, imgID, ep strin <ide> defer os.RemoveAll(layerData.Name()) <ide> <ide> // Send the layer <del> log.Debugf("rendered layer for %s of [%d] size", imgData.ID, layerData.Size) <add> logrus.Debugf("rendered layer for %s of [%d] size", imgData.ID, layerData.Size) <ide> <ide> checksum, checksumPayload, err := r.PushImageLayerRegistry(imgData.ID, <ide> progressreader.New(progressreader.Config{ <ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o <ide> endpoint, err := r.V2RegistryEndpoint(repoInfo.Index) <ide> if err != nil { <ide> if repoInfo.Index.Official { <del> log.Debugf("Unable to push to V2 registry, falling back to v1: %s", err) <add> logrus.Debugf("Unable to push to V2 registry, falling back to v1: %s", err) <ide> return ErrV2RegistryUnavailable <ide> } <ide> return fmt.Errorf("error getting registry endpoint: %s", err) <ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o <ide> } <ide> <ide> for _, tag := range tags { <del> log.Debugf("Pushing repository: %s:%s", repoInfo.CanonicalName, tag) <add> logrus.Debugf("Pushing repository: %s:%s", repoInfo.CanonicalName, tag) <ide> <ide> layerId, exists := localRepo[tag] <ide> if !exists { <ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o <ide> <ide> // Schema version 1 requires layer ordering from top to root <ide> for i, layer := range layers { <del> log.Debugf("Pushing layer: %s", layer.ID) <add> logrus.Debugf("Pushing layer: %s", layer.ID) <ide> <ide> if layer.Config != nil && metadata.Image != layer.ID { <ide> err = runconfig.Merge(&metadata, layer.Config) <ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o <ide> return fmt.Errorf("invalid manifest: %s", err) <ide> } <ide> <del> log.Debugf("Pushing %s:%s to v2 repository", repoInfo.LocalName, tag) <add> logrus.Debugf("Pushing %s:%s to v2 repository", repoInfo.LocalName, tag) <ide> mBytes, err := json.MarshalIndent(m, "", " ") <ide> if err != nil { <ide> return err <ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o <ide> if err != nil { <ide> return err <ide> } <del> log.Infof("Signed manifest for %s:%s using daemon's key: %s", repoInfo.LocalName, tag, s.trustKey.KeyID()) <add> logrus.Infof("Signed manifest for %s:%s using daemon's key: %s", repoInfo.LocalName, tag, s.trustKey.KeyID()) <ide> <ide> // push the manifest <ide> digest, err := r.PutV2ImageManifest(endpoint, repoInfo.RemoteName, tag, signedBody, mBytes, auth) <ide> func (s *TagStore) pushV2Image(r *registry.Session, img *image.Image, endpoint * <ide> dgst := digest.NewDigest("sha256", h) <ide> <ide> // Send the layer <del> log.Debugf("rendered layer for %s of [%d] size", img.ID, size) <add> logrus.Debugf("rendered layer for %s of [%d] size", img.ID, size) <ide> <ide> if err := r.PutV2ImageBlob(endpoint, imageName, dgst.Algorithm(), dgst.Hex(), <ide> progressreader.New(progressreader.Config{ <ide><path>graph/service.go <ide> import ( <ide> "fmt" <ide> "io" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> ) <ide> func (s *TagStore) CmdTarLayer(job *engine.Job) error { <ide> if err != nil { <ide> return err <ide> } <del> log.Debugf("rendered layer for %s of [%d] size", image.ID, written) <add> logrus.Debugf("rendered layer for %s of [%d] size", image.ID, written) <ide> return nil <ide> } <ide> return fmt.Errorf("No such image: %s", name) <ide><path>integration/commands_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/client" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/stringid" <ide> func TestAttachDisconnect(t *testing.T) { <ide> go func() { <ide> // Start a process in daemon mode <ide> if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil { <del> log.Debugf("Error CmdRun: %s", err) <add> logrus.Debugf("Error CmdRun: %s", err) <ide> } <ide> }() <ide> <ide><path>integration/runtime_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/engine" <ide> func init() { <ide> } <ide> <ide> if uid := syscall.Geteuid(); uid != 0 { <del> log.Fatalf("docker tests need to be run as root") <add> logrus.Fatalf("docker tests need to be run as root") <ide> } <ide> <ide> // Copy dockerinit into our current testing directory, if provided (so we can test a separate dockerinit binary) <ide> if dockerinit := os.Getenv("TEST_DOCKERINIT_PATH"); dockerinit != "" { <ide> src, err := os.Open(dockerinit) <ide> if err != nil { <del> log.Fatalf("Unable to open TEST_DOCKERINIT_PATH: %s", err) <add> logrus.Fatalf("Unable to open TEST_DOCKERINIT_PATH: %s", err) <ide> } <ide> defer src.Close() <ide> dst, err := os.OpenFile(filepath.Join(filepath.Dir(utils.SelfPath()), "dockerinit"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0555) <ide> if err != nil { <del> log.Fatalf("Unable to create dockerinit in test directory: %s", err) <add> logrus.Fatalf("Unable to create dockerinit in test directory: %s", err) <ide> } <ide> defer dst.Close() <ide> if _, err := io.Copy(dst, src); err != nil { <del> log.Fatalf("Unable to copy dockerinit to TEST_DOCKERINIT_PATH: %s", err) <add> logrus.Fatalf("Unable to copy dockerinit to TEST_DOCKERINIT_PATH: %s", err) <ide> } <ide> dst.Close() <ide> src.Close() <ide> func setupBaseImage() { <ide> job = eng.Job("pull", unitTestImageName) <ide> job.Stdout.Add(ioutils.NopWriteCloser(os.Stdout)) <ide> if err := job.Run(); err != nil { <del> log.Fatalf("Unable to pull the test image: %s", err) <add> logrus.Fatalf("Unable to pull the test image: %s", err) <ide> } <ide> } <ide> } <ide> <ide> func spawnGlobalDaemon() { <ide> if globalDaemon != nil { <del> log.Debugf("Global daemon already exists. Skipping.") <add> logrus.Debugf("Global daemon already exists. Skipping.") <ide> return <ide> } <ide> t := std_log.New(os.Stderr, "", 0) <ide> func spawnGlobalDaemon() { <ide> <ide> // Spawn a Daemon <ide> go func() { <del> log.Debugf("Spawning global daemon for integration tests") <add> logrus.Debugf("Spawning global daemon for integration tests") <ide> listenURL := &url.URL{ <ide> Scheme: testDaemonProto, <ide> Host: testDaemonAddr, <ide> } <ide> job := eng.Job("serveapi", listenURL.String()) <ide> job.SetenvBool("Logging", true) <ide> if err := job.Run(); err != nil { <del> log.Fatalf("Unable to spawn the test daemon: %s", err) <add> logrus.Fatalf("Unable to spawn the test daemon: %s", err) <ide> } <ide> }() <ide> <ide> func spawnGlobalDaemon() { <ide> time.Sleep(time.Second) <ide> <ide> if err := eng.Job("acceptconnections").Run(); err != nil { <del> log.Fatalf("Unable to accept connections for test api: %s", err) <add> logrus.Fatalf("Unable to accept connections for test api: %s", err) <ide> } <ide> } <ide> <ide> func spawnHttpsDaemon(addr, cacert, cert, key string) *engine.Engine { <ide> <ide> // Spawn a Daemon <ide> go func() { <del> log.Debugf("Spawning https daemon for integration tests") <add> logrus.Debugf("Spawning https daemon for integration tests") <ide> listenURL := &url.URL{ <ide> Scheme: testDaemonHttpsProto, <ide> Host: addr, <ide> func spawnHttpsDaemon(addr, cacert, cert, key string) *engine.Engine { <ide> job.Setenv("TlsCert", cert) <ide> job.Setenv("TlsKey", key) <ide> if err := job.Run(); err != nil { <del> log.Fatalf("Unable to spawn the test daemon: %s", err) <add> logrus.Fatalf("Unable to spawn the test daemon: %s", err) <ide> } <ide> }() <ide> <ide> // Give some time to ListenAndServer to actually start <ide> time.Sleep(time.Second) <ide> <ide> if err := eng.Job("acceptconnections").Run(); err != nil { <del> log.Fatalf("Unable to accept connections for test api: %s", err) <add> logrus.Fatalf("Unable to accept connections for test api: %s", err) <ide> } <ide> return eng <ide> } <ide> func spawnHttpsDaemon(addr, cacert, cert, key string) *engine.Engine { <ide> func GetTestImage(daemon *daemon.Daemon) *image.Image { <ide> imgs, err := daemon.Graph().Map() <ide> if err != nil { <del> log.Fatalf("Unable to get the test image: %s", err) <add> logrus.Fatalf("Unable to get the test image: %s", err) <ide> } <ide> for _, image := range imgs { <ide> if image.ID == unitTestImageID { <ide> return image <ide> } <ide> } <del> log.Fatalf("Test image %v not found in %s: %s", unitTestImageID, daemon.Graph().Root, imgs) <add> logrus.Fatalf("Test image %v not found in %s: %s", unitTestImageID, daemon.Graph().Root, imgs) <ide> return nil <ide> } <ide> <ide> func TestRandomContainerName(t *testing.T) { <ide> } <ide> <ide> if c, err := daemon.Get(container.Name); err != nil { <del> log.Fatalf("Could not lookup container %s by its name", container.Name) <add> logrus.Fatalf("Could not lookup container %s by its name", container.Name) <ide> } else if c.ID != containerID { <del> log.Fatalf("Looking up container name %s returned id %s instead of %s", container.Name, c.ID, containerID) <add> logrus.Fatalf("Looking up container name %s returned id %s instead of %s", container.Name, c.ID, containerID) <ide> } <ide> } <ide> <ide><path>pkg/archive/archive.go <ide> import ( <ide> <ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/pools" <ide> "github.com/docker/docker/pkg/promise" <ide> func DetectCompression(source []byte) Compression { <ide> Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, <ide> } { <ide> if len(source) < len(m) { <del> log.Debugf("Len too short") <add> logrus.Debugf("Len too short") <ide> continue <ide> } <ide> if bytes.Compare(m, source[:len(m)]) == 0 { <ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, L <ide> } <ide> <ide> case tar.TypeXGlobalHeader: <del> log.Debugf("PAX Global Extended Headers found and ignored") <add> logrus.Debugf("PAX Global Extended Headers found and ignored") <ide> return nil <ide> <ide> default: <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> for _, include := range options.IncludeFiles { <ide> filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error { <ide> if err != nil { <del> log.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) <add> logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) <ide> return nil <ide> } <ide> <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> if include != relFilePath { <ide> skip, err = fileutils.Matches(relFilePath, options.ExcludePatterns) <ide> if err != nil { <del> log.Debugf("Error matching %s", relFilePath, err) <add> logrus.Debugf("Error matching %s", relFilePath, err) <ide> return err <ide> } <ide> } <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> } <ide> <ide> if err := ta.addTarFile(filePath, relFilePath); err != nil { <del> log.Debugf("Can't add file %s to tar: %s", filePath, err) <add> logrus.Debugf("Can't add file %s to tar: %s", filePath, err) <ide> } <ide> return nil <ide> }) <ide> } <ide> <ide> // Make sure to check the error on Close. <ide> if err := ta.TarWriter.Close(); err != nil { <del> log.Debugf("Can't close tar writer: %s", err) <add> logrus.Debugf("Can't close tar writer: %s", err) <ide> } <ide> if err := compressWriter.Close(); err != nil { <del> log.Debugf("Can't close compress writer: %s", err) <add> logrus.Debugf("Can't close compress writer: %s", err) <ide> } <ide> if err := pipeWriter.Close(); err != nil { <del> log.Debugf("Can't close pipe writer: %s", err) <add> logrus.Debugf("Can't close pipe writer: %s", err) <ide> } <ide> }() <ide> <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> } <ide> <ide> func (archiver *Archiver) TarUntar(src, dst string) error { <del> log.Debugf("TarUntar(%s %s)", src, dst) <add> logrus.Debugf("TarUntar(%s %s)", src, dst) <ide> archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) <ide> if err != nil { <ide> return err <ide> func (archiver *Archiver) CopyWithTar(src, dst string) error { <ide> return archiver.CopyFileWithTar(src, dst) <ide> } <ide> // Create dst, copy src's content into it <del> log.Debugf("Creating dest directory: %s", dst) <add> logrus.Debugf("Creating dest directory: %s", dst) <ide> if err := os.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) { <ide> return err <ide> } <del> log.Debugf("Calling TarUntar(%s, %s)", src, dst) <add> logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) <ide> return archiver.TarUntar(src, dst) <ide> } <ide> <ide> func CopyWithTar(src, dst string) error { <ide> } <ide> <ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <del> log.Debugf("CopyFileWithTar(%s, %s)", src, dst) <add> logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) <ide> srcSt, err := os.Stat(src) <ide> if err != nil { <ide> return err <ide><path>pkg/archive/changes.go <ide> import ( <ide> <ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/pools" <ide> "github.com/docker/docker/pkg/system" <ide> ) <ide> func ExportChanges(dir string, changes []Change) (Archive, error) { <ide> ChangeTime: timestamp, <ide> } <ide> if err := ta.TarWriter.WriteHeader(hdr); err != nil { <del> log.Debugf("Can't write whiteout header: %s", err) <add> logrus.Debugf("Can't write whiteout header: %s", err) <ide> } <ide> } else { <ide> path := filepath.Join(dir, change.Path) <ide> if err := ta.addTarFile(path, change.Path[1:]); err != nil { <del> log.Debugf("Can't add file %s to tar: %s", path, err) <add> logrus.Debugf("Can't add file %s to tar: %s", path, err) <ide> } <ide> } <ide> } <ide> <ide> // Make sure to check the error on Close. <ide> if err := ta.TarWriter.Close(); err != nil { <del> log.Debugf("Can't close layer: %s", err) <add> logrus.Debugf("Can't close layer: %s", err) <ide> } <ide> if err := writer.Close(); err != nil { <del> log.Debugf("failed close Changes writer: %s", err) <add> logrus.Debugf("failed close Changes writer: %s", err) <ide> } <ide> }() <ide> return reader, nil <ide><path>pkg/broadcastwriter/broadcastwriter.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/jsonlog" <ide> ) <ide> <ide> func (w *BroadcastWriter) Write(p []byte) (n int, err error) { <ide> jsonLog := jsonlog.JSONLog{Log: line, Stream: stream, Created: created} <ide> err = jsonLog.MarshalJSONBuf(w.jsLogBuf) <ide> if err != nil { <del> log.Errorf("Error making JSON log line: %s", err) <add> logrus.Errorf("Error making JSON log line: %s", err) <ide> continue <ide> } <ide> w.jsLogBuf.WriteByte('\n') <ide><path>pkg/devicemapper/attach_loopback.go <ide> import ( <ide> "os" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> func stringToLoopName(src string) [LoNameSize]uint8 { <ide> func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.Fil <ide> fi, err := os.Stat(target) <ide> if err != nil { <ide> if os.IsNotExist(err) { <del> log.Errorf("There are no more loopback devices available.") <add> logrus.Errorf("There are no more loopback devices available.") <ide> } <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide> <ide> if fi.Mode()&os.ModeDevice != os.ModeDevice { <del> log.Errorf("Loopback device %s is not a block device.", target) <add> logrus.Errorf("Loopback device %s is not a block device.", target) <ide> continue <ide> } <ide> <ide> // OpenFile adds O_CLOEXEC <ide> loopFile, err = os.OpenFile(target, os.O_RDWR, 0644) <ide> if err != nil { <del> log.Errorf("Error opening loopback device: %s", err) <add> logrus.Errorf("Error opening loopback device: %s", err) <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide> <ide> func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.Fil <ide> <ide> // If the error is EBUSY, then try the next loopback <ide> if err != syscall.EBUSY { <del> log.Errorf("Cannot set up loopback device %s: %s", target, err) <add> logrus.Errorf("Cannot set up loopback device %s: %s", target, err) <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide> <ide> func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.Fil <ide> <ide> // This can't happen, but let's be sure <ide> if loopFile == nil { <del> log.Errorf("Unreachable code reached! Error attaching %s to a loopback device.", sparseFile.Name()) <add> logrus.Errorf("Unreachable code reached! Error attaching %s to a loopback device.", sparseFile.Name()) <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide> <ide> func AttachLoopDevice(sparseName string) (loop *os.File, err error) { <ide> // loopback from index 0. <ide> startIndex, err := getNextFreeLoopbackIndex() <ide> if err != nil { <del> log.Debugf("Error retrieving the next available loopback: %s", err) <add> logrus.Debugf("Error retrieving the next available loopback: %s", err) <ide> } <ide> <ide> // OpenFile adds O_CLOEXEC <ide> sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644) <ide> if err != nil { <del> log.Errorf("Error opening sparse file %s: %s", sparseName, err) <add> logrus.Errorf("Error opening sparse file %s: %s", sparseName, err) <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide> defer sparseFile.Close() <ide> func AttachLoopDevice(sparseName string) (loop *os.File, err error) { <ide> } <ide> <ide> if err := ioctlLoopSetStatus64(loopFile.Fd(), loopInfo); err != nil { <del> log.Errorf("Cannot set up loopback device info: %s", err) <add> logrus.Errorf("Cannot set up loopback device info: %s", err) <ide> <ide> // If the call failed, then free the loopback device <ide> if err := ioctlLoopClrFd(loopFile.Fd()); err != nil { <del> log.Errorf("Error while cleaning up the loopback device") <add> logrus.Errorf("Error while cleaning up the loopback device") <ide> } <ide> loopFile.Close() <ide> return nil, ErrAttachLoopbackDevice <ide><path>pkg/devicemapper/devmapper.go <ide> import ( <ide> "runtime" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> type DevmapperLogger interface { <ide> func (t *Task) GetNextTarget(next uintptr) (nextPtr uintptr, start uint64, <ide> func getLoopbackBackingFile(file *os.File) (uint64, uint64, error) { <ide> loopInfo, err := ioctlLoopGetStatus64(file.Fd()) <ide> if err != nil { <del> log.Errorf("Error get loopback backing file: %s", err) <add> logrus.Errorf("Error get loopback backing file: %s", err) <ide> return 0, 0, ErrGetLoopbackBackingFile <ide> } <ide> return loopInfo.loDevice, loopInfo.loInode, nil <ide> } <ide> <ide> func LoopbackSetCapacity(file *os.File) error { <ide> if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil { <del> log.Errorf("Error loopbackSetCapacity: %s", err) <add> logrus.Errorf("Error loopbackSetCapacity: %s", err) <ide> return ErrLoopbackSetCapacity <ide> } <ide> return nil <ide> func FindLoopDeviceFor(file *os.File) *os.File { <ide> <ide> func UdevWait(cookie uint) error { <ide> if res := DmUdevWait(cookie); res != 1 { <del> log.Debugf("Failed to wait on udev cookie %d", cookie) <add> logrus.Debugf("Failed to wait on udev cookie %d", cookie) <ide> return ErrUdevWait <ide> } <ide> return nil <ide> func LogInit(logger DevmapperLogger) { <ide> <ide> func SetDevDir(dir string) error { <ide> if res := DmSetDevDir(dir); res != 1 { <del> log.Debugf("Error dm_set_dev_dir") <add> logrus.Debugf("Error dm_set_dev_dir") <ide> return ErrSetDevDir <ide> } <ide> return nil <ide> func CookieSupported() bool { <ide> <ide> // Useful helper for cleanup <ide> func RemoveDevice(name string) error { <del> log.Debugf("[devmapper] RemoveDevice START(%s)", name) <del> defer log.Debugf("[devmapper] RemoveDevice END(%s)", name) <add> logrus.Debugf("[devmapper] RemoveDevice START(%s)", name) <add> defer logrus.Debugf("[devmapper] RemoveDevice END(%s)", name) <ide> task, err := TaskCreateNamed(DeviceRemove, name) <ide> if task == nil { <ide> return err <ide> func RemoveDevice(name string) error { <ide> func GetBlockDeviceSize(file *os.File) (uint64, error) { <ide> size, err := ioctlBlkGetSize64(file.Fd()) <ide> if err != nil { <del> log.Errorf("Error getblockdevicesize: %s", err) <add> logrus.Errorf("Error getblockdevicesize: %s", err) <ide> return 0, ErrGetBlockSize <ide> } <ide> return uint64(size), nil <ide> func GetDriverVersion() (string, error) { <ide> func GetStatus(name string) (uint64, uint64, string, string, error) { <ide> task, err := TaskCreateNamed(DeviceStatus, name) <ide> if task == nil { <del> log.Debugf("GetStatus: Error TaskCreateNamed: %s", err) <add> logrus.Debugf("GetStatus: Error TaskCreateNamed: %s", err) <ide> return 0, 0, "", "", err <ide> } <ide> if err := task.Run(); err != nil { <del> log.Debugf("GetStatus: Error Run: %s", err) <add> logrus.Debugf("GetStatus: Error Run: %s", err) <ide> return 0, 0, "", "", err <ide> } <ide> <ide> devinfo, err := task.GetInfo() <ide> if err != nil { <del> log.Debugf("GetStatus: Error GetInfo: %s", err) <add> logrus.Debugf("GetStatus: Error GetInfo: %s", err) <ide> return 0, 0, "", "", err <ide> } <ide> if devinfo.Exists == 0 { <del> log.Debugf("GetStatus: Non existing device %s", name) <add> logrus.Debugf("GetStatus: Non existing device %s", name) <ide> return 0, 0, "", "", fmt.Errorf("Non existing device %s", name) <ide> } <ide> <ide> func ResumeDevice(name string) error { <ide> } <ide> <ide> func CreateDevice(poolName string, deviceId int) error { <del> log.Debugf("[devmapper] CreateDevice(poolName=%v, deviceId=%v)", poolName, deviceId) <add> logrus.Debugf("[devmapper] CreateDevice(poolName=%v, deviceId=%v)", poolName, deviceId) <ide> task, err := TaskCreateNamed(DeviceTargetMsg, poolName) <ide> if task == nil { <ide> return err <ide><path>pkg/fileutils/fileutils.go <ide> package fileutils <ide> <ide> import ( <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "path/filepath" <ide> ) <ide> <ide> func Matches(relFilePath string, patterns []string) (bool, error) { <ide> for _, exclude := range patterns { <ide> matched, err := filepath.Match(exclude, relFilePath) <ide> if err != nil { <del> log.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude) <add> logrus.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude) <ide> return false, err <ide> } <ide> if matched { <ide> if filepath.Clean(relFilePath) == "." { <del> log.Errorf("Can't exclude whole path, excluding pattern: %s", exclude) <add> logrus.Errorf("Can't exclude whole path, excluding pattern: %s", exclude) <ide> continue <ide> } <del> log.Debugf("Skipping excluded path: %s", relFilePath) <add> logrus.Debugf("Skipping excluded path: %s", relFilePath) <ide> return true, nil <ide> } <ide> } <ide><path>pkg/httputils/resumablerequestreader.go <ide> import ( <ide> "net/http" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> type resumableRequestReader struct { <ide> func (r *resumableRequestReader) Read(p []byte) (n int, err error) { <ide> r.cleanUpResponse() <ide> } <ide> if err != nil && err != io.EOF { <del> log.Infof("encountered error during pull and clearing it before resume: %s", err) <add> logrus.Infof("encountered error during pull and clearing it before resume: %s", err) <ide> err = nil <ide> } <ide> return n, err <ide><path>pkg/iptables/iptables.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> type Action string <ide> func Raw(args ...string) ([]byte, error) { <ide> args = append([]string{"--wait"}, args...) <ide> } <ide> <del> log.Debugf("%s, %v", iptablesPath, args) <add> logrus.Debugf("%s, %v", iptablesPath, args) <ide> <ide> output, err := exec.Command(iptablesPath, args...).CombinedOutput() <ide> if err != nil { <ide><path>pkg/jsonlog/jsonlog.go <ide> import ( <ide> "io" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> type JSONLog struct { <ide> func WriteLog(src io.Reader, dst io.Writer, format string) error { <ide> if err := dec.Decode(l); err == io.EOF { <ide> return nil <ide> } else if err != nil { <del> log.Printf("Error streaming logs: %s", err) <add> logrus.Printf("Error streaming logs: %s", err) <ide> return err <ide> } <ide> line, err := l.Format(format) <ide><path>pkg/proxy/tcp_proxy.go <ide> import ( <ide> "net" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> type TCPProxy struct { <ide> func NewTCPProxy(frontendAddr, backendAddr *net.TCPAddr) (*TCPProxy, error) { <ide> func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) { <ide> backend, err := net.DialTCP("tcp", nil, proxy.backendAddr) <ide> if err != nil { <del> log.Printf("Can't forward traffic to backend tcp/%v: %s\n", proxy.backendAddr, err) <add> logrus.Printf("Can't forward traffic to backend tcp/%v: %s\n", proxy.backendAddr, err) <ide> client.Close() <ide> return <ide> } <ide> func (proxy *TCPProxy) Run() { <ide> for { <ide> client, err := proxy.listener.Accept() <ide> if err != nil { <del> log.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) <add> logrus.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) <ide> return <ide> } <ide> go proxy.clientLoop(client.(*net.TCPConn), quit) <ide><path>pkg/proxy/udp_proxy.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> const ( <ide> func (proxy *UDPProxy) Run() { <ide> // ECONNREFUSED like Read do (see comment in <ide> // UDPProxy.replyLoop) <ide> if !isClosedError(err) { <del> log.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) <add> logrus.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) <ide> } <ide> break <ide> } <ide> func (proxy *UDPProxy) Run() { <ide> if !hit { <ide> proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr) <ide> if err != nil { <del> log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) <add> logrus.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) <ide> proxy.connTrackLock.Unlock() <ide> continue <ide> } <ide> func (proxy *UDPProxy) Run() { <ide> for i := 0; i != read; { <ide> written, err := proxyConn.Write(readBuf[i:read]) <ide> if err != nil { <del> log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) <add> logrus.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) <ide> break <ide> } <ide> i += written <ide><path>pkg/resolvconf/resolvconf.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <ide> func FilterResolvDns(resolvConf []byte, ipv6Enabled bool) ([]byte, bool) { <ide> // if the resulting resolvConf has no more nameservers defined, add appropriate <ide> // default DNS servers for IPv4 and (optionally) IPv6 <ide> if len(GetNameservers(cleanedResolvConf)) == 0 { <del> log.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultIPv4Dns) <add> logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultIPv4Dns) <ide> dns := defaultIPv4Dns <ide> if ipv6Enabled { <del> log.Infof("IPv6 enabled; Adding default IPv6 external servers : %v", defaultIPv6Dns) <add> logrus.Infof("IPv6 enabled; Adding default IPv6 external servers : %v", defaultIPv6Dns) <ide> dns = append(dns, defaultIPv6Dns...) <ide> } <ide> cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...) <ide><path>pkg/signal/trap.go <ide> import ( <ide> "sync/atomic" <ide> "syscall" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> // Trap sets up a simplified signal "trap", appropriate for common <ide> func Trap(cleanup func()) { <ide> interruptCount := uint32(0) <ide> for sig := range c { <ide> go func(sig os.Signal) { <del> log.Infof("Received signal '%v', starting shutdown of docker...", sig) <add> logrus.Infof("Received signal '%v', starting shutdown of docker...", sig) <ide> switch sig { <ide> case os.Interrupt, syscall.SIGTERM: <ide> // If the user really wants to interrupt, let him do so. <ide> func Trap(cleanup func()) { <ide> return <ide> } <ide> } else { <del> log.Infof("Force shutdown of docker, interrupting cleanup") <add> logrus.Infof("Force shutdown of docker, interrupting cleanup") <ide> } <ide> case syscall.SIGQUIT: <ide> } <ide><path>pkg/stdcopy/stdcopy.go <ide> import ( <ide> "errors" <ide> "io" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> const ( <ide> func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) <ide> nr += nr2 <ide> if er == io.EOF { <ide> if nr < StdWriterPrefixLen { <del> log.Debugf("Corrupted prefix: %v", buf[:nr]) <add> logrus.Debugf("Corrupted prefix: %v", buf[:nr]) <ide> return written, nil <ide> } <ide> break <ide> } <ide> if er != nil { <del> log.Debugf("Error reading header: %s", er) <add> logrus.Debugf("Error reading header: %s", er) <ide> return 0, er <ide> } <ide> } <ide> func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) <ide> // Write on stderr <ide> out = dsterr <ide> default: <del> log.Debugf("Error selecting output fd: (%d)", buf[StdWriterFdIndex]) <add> logrus.Debugf("Error selecting output fd: (%d)", buf[StdWriterFdIndex]) <ide> return 0, ErrInvalidStdHeader <ide> } <ide> <ide> // Retrieve the size of the frame <ide> frameSize = int(binary.BigEndian.Uint32(buf[StdWriterSizeIndex : StdWriterSizeIndex+4])) <del> log.Debugf("framesize: %d", frameSize) <add> logrus.Debugf("framesize: %d", frameSize) <ide> <ide> // Check if the buffer is big enough to read the frame. <ide> // Extend it if necessary. <ide> if frameSize+StdWriterPrefixLen > bufLen { <del> log.Debugf("Extending buffer cap by %d (was %d)", frameSize+StdWriterPrefixLen-bufLen+1, len(buf)) <add> logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+StdWriterPrefixLen-bufLen+1, len(buf)) <ide> buf = append(buf, make([]byte, frameSize+StdWriterPrefixLen-bufLen+1)...) <ide> bufLen = len(buf) <ide> } <ide> func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) <ide> nr += nr2 <ide> if er == io.EOF { <ide> if nr < frameSize+StdWriterPrefixLen { <del> log.Debugf("Corrupted frame: %v", buf[StdWriterPrefixLen:nr]) <add> logrus.Debugf("Corrupted frame: %v", buf[StdWriterPrefixLen:nr]) <ide> return written, nil <ide> } <ide> break <ide> } <ide> if er != nil { <del> log.Debugf("Error reading frame: %s", er) <add> logrus.Debugf("Error reading frame: %s", er) <ide> return 0, er <ide> } <ide> } <ide> <ide> // Write the retrieved frame (without header) <ide> nw, ew = out.Write(buf[StdWriterPrefixLen : frameSize+StdWriterPrefixLen]) <ide> if ew != nil { <del> log.Debugf("Error writing frame: %s", ew) <add> logrus.Debugf("Error writing frame: %s", ew) <ide> return 0, ew <ide> } <ide> // If the frame has not been fully written: error <ide> if nw != frameSize { <del> log.Debugf("Error Short Write: (%d on %d)", nw, frameSize) <add> logrus.Debugf("Error Short Write: (%d on %d)", nw, frameSize) <ide> return 0, io.ErrShortWrite <ide> } <ide> written += int64(nw) <ide><path>pkg/sysinfo/sysinfo.go <ide> import ( <ide> "os" <ide> "path" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/libcontainer/cgroups" <ide> ) <ide> <ide> func New(quiet bool) *SysInfo { <ide> sysInfo := &SysInfo{} <ide> if cgroupMemoryMountpoint, err := cgroups.FindCgroupMountpoint("memory"); err != nil { <ide> if !quiet { <del> log.Warnf("%s", err) <add> logrus.Warnf("%s", err) <ide> } <ide> } else { <ide> _, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.limit_in_bytes")) <ide> _, err2 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.soft_limit_in_bytes")) <ide> sysInfo.MemoryLimit = err1 == nil && err2 == nil <ide> if !sysInfo.MemoryLimit && !quiet { <del> log.Warnf("Your kernel does not support cgroup memory limit.") <add> logrus.Warnf("Your kernel does not support cgroup memory limit.") <ide> } <ide> <ide> _, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes")) <ide> sysInfo.SwapLimit = err == nil <ide> if !sysInfo.SwapLimit && !quiet { <del> log.Warnf("Your kernel does not support cgroup swap limit.") <add> logrus.Warnf("Your kernel does not support cgroup swap limit.") <ide> } <ide> } <ide> <ide><path>registry/auth.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <ide> func (auth *RequestAuthorization) getToken() (string, error) { <ide> defer auth.tokenLock.Unlock() <ide> now := time.Now() <ide> if now.Before(auth.tokenExpiration) { <del> log.Debugf("Using cached token for %s", auth.authConfig.Username) <add> logrus.Debugf("Using cached token for %s", auth.authConfig.Username) <ide> return auth.tokenCache, nil <ide> } <ide> <ide> func (auth *RequestAuthorization) getToken() (string, error) { <ide> case "basic": <ide> // no token necessary <ide> case "bearer": <del> log.Debugf("Getting bearer token with %s for %s", challenge.Parameters, auth.authConfig.Username) <add> logrus.Debugf("Getting bearer token with %s for %s", challenge.Parameters, auth.authConfig.Username) <ide> params := map[string]string{} <ide> for k, v := range challenge.Parameters { <ide> params[k] = v <ide> func (auth *RequestAuthorization) getToken() (string, error) { <ide> <ide> return token, nil <ide> default: <del> log.Infof("Unsupported auth scheme: %q", challenge.Scheme) <add> logrus.Infof("Unsupported auth scheme: %q", challenge.Scheme) <ide> } <ide> } <ide> <ide> func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils. <ide> serverAddress = authConfig.ServerAddress <ide> ) <ide> <del> log.Debugf("attempting v1 login to registry endpoint %s", registryEndpoint) <add> logrus.Debugf("attempting v1 login to registry endpoint %s", registryEndpoint) <ide> <ide> if serverAddress == "" { <ide> return "", fmt.Errorf("Server Error: Server Address not set.") <ide> func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils. <ide> // served by the v2 registry service provider. Whether this will be supported in the future <ide> // is to be determined. <ide> func loginV2(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) { <del> log.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint) <add> logrus.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint) <ide> var ( <ide> err error <ide> allErrors []error <ide> client = registryEndpoint.HTTPClient() <ide> ) <ide> <ide> for _, challenge := range registryEndpoint.AuthChallenges { <del> log.Debugf("trying %q auth challenge with params %s", challenge.Scheme, challenge.Parameters) <add> logrus.Debugf("trying %q auth challenge with params %s", challenge.Scheme, challenge.Parameters) <ide> <ide> switch strings.ToLower(challenge.Scheme) { <ide> case "basic": <ide> func loginV2(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils. <ide> return "Login Succeeded", nil <ide> } <ide> <del> log.Debugf("error trying auth challenge %q: %s", challenge.Scheme, err) <add> logrus.Debugf("error trying auth challenge %q: %s", challenge.Scheme, err) <ide> <ide> allErrors = append(allErrors, err) <ide> } <ide><path>registry/endpoint.go <ide> import ( <ide> "net/url" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/registry/v2" <ide> "github.com/docker/docker/utils" <ide> ) <ide> func NewEndpoint(index *IndexInfo) (*Endpoint, error) { <ide> } <ide> <ide> func validateEndpoint(endpoint *Endpoint) error { <del> log.Debugf("pinging registry endpoint %s", endpoint) <add> logrus.Debugf("pinging registry endpoint %s", endpoint) <ide> <ide> // Try HTTPS ping to registry <ide> endpoint.URL.Scheme = "https" <ide> func validateEndpoint(endpoint *Endpoint) error { <ide> } <ide> <ide> // If registry is insecure and HTTPS failed, fallback to HTTP. <del> log.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) <add> logrus.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) <ide> endpoint.URL.Scheme = "http" <ide> <ide> var err2 error <ide> func (e *Endpoint) Ping() (RegistryInfo, error) { <ide> } <ide> <ide> func (e *Endpoint) pingV1(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { <del> log.Debugf("attempting v1 ping for registry endpoint %s", e) <add> logrus.Debugf("attempting v1 ping for registry endpoint %s", e) <ide> <ide> if e.String() == IndexServerAddress() { <ide> // Skip the check, we know this one is valid <ide> func (e *Endpoint) pingV1(factory *utils.HTTPRequestFactory) (RegistryInfo, erro <ide> Standalone: true, <ide> } <ide> if err := json.Unmarshal(jsonString, &info); err != nil { <del> log.Debugf("Error unmarshalling the _ping RegistryInfo: %s", err) <add> logrus.Debugf("Error unmarshalling the _ping RegistryInfo: %s", err) <ide> // don't stop here. Just assume sane defaults <ide> } <ide> if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { <del> log.Debugf("Registry version header: '%s'", hdr) <add> logrus.Debugf("Registry version header: '%s'", hdr) <ide> info.Version = hdr <ide> } <del> log.Debugf("RegistryInfo.Version: %q", info.Version) <add> logrus.Debugf("RegistryInfo.Version: %q", info.Version) <ide> <ide> standalone := resp.Header.Get("X-Docker-Registry-Standalone") <del> log.Debugf("Registry standalone header: '%s'", standalone) <add> logrus.Debugf("Registry standalone header: '%s'", standalone) <ide> // Accepted values are "true" (case-insensitive) and "1". <ide> if strings.EqualFold(standalone, "true") || standalone == "1" { <ide> info.Standalone = true <ide> } else if len(standalone) > 0 { <ide> // there is a header set, and it is not "true" or "1", so assume fails <ide> info.Standalone = false <ide> } <del> log.Debugf("RegistryInfo.Standalone: %t", info.Standalone) <add> logrus.Debugf("RegistryInfo.Standalone: %t", info.Standalone) <ide> return info, nil <ide> } <ide> <ide> func (e *Endpoint) pingV2(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { <del> log.Debugf("attempting v2 ping for registry endpoint %s", e) <add> logrus.Debugf("attempting v2 ping for registry endpoint %s", e) <ide> <ide> req, err := factory.NewRequest("GET", e.Path(""), nil) <ide> if err != nil { <ide><path>registry/registry.go <ide> import ( <ide> "strings" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/timeoutconn" <ide> ) <ide> <ide> func doRequest(req *http.Request, jar http.CookieJar, timeout TimeoutType, secur <ide> } <ide> <ide> hostDir := path.Join("/etc/docker/certs.d", req.URL.Host) <del> log.Debugf("hostDir: %s", hostDir) <add> logrus.Debugf("hostDir: %s", hostDir) <ide> fs, err := ioutil.ReadDir(hostDir) <ide> if err != nil && !os.IsNotExist(err) { <ide> return nil, nil, err <ide> func doRequest(req *http.Request, jar http.CookieJar, timeout TimeoutType, secur <ide> if pool == nil { <ide> pool = x509.NewCertPool() <ide> } <del> log.Debugf("crt: %s", hostDir+"/"+f.Name()) <add> logrus.Debugf("crt: %s", hostDir+"/"+f.Name()) <ide> data, err := ioutil.ReadFile(path.Join(hostDir, f.Name())) <ide> if err != nil { <ide> return nil, nil, err <ide> func doRequest(req *http.Request, jar http.CookieJar, timeout TimeoutType, secur <ide> if strings.HasSuffix(f.Name(), ".cert") { <ide> certName := f.Name() <ide> keyName := certName[:len(certName)-5] + ".key" <del> log.Debugf("cert: %s", hostDir+"/"+f.Name()) <add> logrus.Debugf("cert: %s", hostDir+"/"+f.Name()) <ide> if !hasFile(fs, keyName) { <ide> return nil, nil, fmt.Errorf("Missing key %s for certificate %s", keyName, certName) <ide> } <ide> func doRequest(req *http.Request, jar http.CookieJar, timeout TimeoutType, secur <ide> if strings.HasSuffix(f.Name(), ".key") { <ide> keyName := f.Name() <ide> certName := keyName[:len(keyName)-4] + ".cert" <del> log.Debugf("key: %s", hostDir+"/"+f.Name()) <add> logrus.Debugf("key: %s", hostDir+"/"+f.Name()) <ide> if !hasFile(fs, certName) { <ide> return nil, nil, fmt.Errorf("Missing certificate %s for key %s", certName, keyName) <ide> } <ide><path>registry/registry_mock_test.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> "github.com/gorilla/mux" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> var ( <ide> func init() { <ide> <ide> func handlerAccessLog(handler http.Handler) http.Handler { <ide> logHandler := func(w http.ResponseWriter, r *http.Request) { <del> log.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL) <add> logrus.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL) <ide> handler.ServeHTTP(w, r) <ide> } <ide> return http.HandlerFunc(logHandler) <ide> func TestPing(t *testing.T) { <ide> * WARNING: Don't push on the repos uncommented, it'll block the tests <ide> * <ide> func TestWait(t *testing.T) { <del> log.Println("Test HTTP server ready and waiting:", testHttpServer.URL) <add> logrus.Println("Test HTTP server ready and waiting:", testHttpServer.URL) <ide> c := make(chan int) <ide> <-c <ide> } <ide><path>registry/service.go <ide> package registry <ide> import ( <ide> "fmt" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> ) <ide> <ide> func (s *Service) Auth(job *engine.Job) error { <ide> } <ide> <ide> if endpoint, err = NewEndpoint(index); err != nil { <del> log.Errorf("unable to get new registry endpoint: %s", err) <add> logrus.Errorf("unable to get new registry endpoint: %s", err) <ide> return err <ide> } <ide> <ide> authConfig.ServerAddress = endpoint.String() <ide> <ide> if status, err = Login(authConfig, endpoint, HTTPRequestFactory(nil)); err != nil { <del> log.Errorf("unable to login against registry endpoint %s: %s", endpoint, err) <add> logrus.Errorf("unable to login against registry endpoint %s: %s", endpoint, err) <ide> return err <ide> } <ide> <del> log.Infof("successful registry login for endpoint %s: %s", endpoint, status) <add> logrus.Infof("successful registry login for endpoint %s: %s", endpoint, status) <ide> job.Printf("%s\n", status) <ide> <ide> return nil <ide><path>registry/session.go <ide> import ( <ide> "strings" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/tarsum" <ide> "github.com/docker/docker/utils" <ide> func NewSession(authConfig *AuthConfig, factory *utils.HTTPRequestFactory, endpo <ide> return nil, err <ide> } <ide> if info.Standalone { <del> log.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", r.indexEndpoint.String()) <add> logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", r.indexEndpoint.String()) <ide> dec := utils.NewHTTPAuthDecorator(authConfig.Username, authConfig.Password) <ide> factory.AddDecorator(dec) <ide> } <ide> func (r *Session) GetRemoteHistory(imgID, registry string, token []string) ([]st <ide> return nil, fmt.Errorf("Error while reading the http response: %s", err) <ide> } <ide> <del> log.Debugf("Ancestry: %s", jsonString) <add> logrus.Debugf("Ancestry: %s", jsonString) <ide> history := new([]string) <ide> if err := json.Unmarshal(jsonString, history); err != nil { <ide> return nil, err <ide> func (r *Session) GetRemoteImageLayer(imgID, registry string, token []string, im <ide> statusCode = 0 <ide> res, client, err = r.doRequest(req) <ide> if err != nil { <del> log.Debugf("Error contacting registry: %s", err) <add> logrus.Debugf("Error contacting registry: %s", err) <ide> if res != nil { <ide> if res.Body != nil { <ide> res.Body.Close() <ide> func (r *Session) GetRemoteImageLayer(imgID, registry string, token []string, im <ide> } <ide> <ide> if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { <del> log.Debugf("server supports resume") <add> logrus.Debugf("server supports resume") <ide> return httputils.ResumableRequestReaderWithInitialResponse(client, req, 5, imgSize, res), nil <ide> } <del> log.Debugf("server doesn't support resume") <add> logrus.Debugf("server doesn't support resume") <ide> return res.Body, nil <ide> } <ide> <ide> func (r *Session) GetRemoteTags(registries []string, repository string, token [] <ide> return nil, err <ide> } <ide> <del> log.Debugf("Got status code %d from %s", res.StatusCode, endpoint) <add> logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) <ide> defer res.Body.Close() <ide> <ide> if res.StatusCode != 200 && res.StatusCode != 404 { <ide> func buildEndpointsList(headers []string, indexEp string) ([]string, error) { <ide> func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) { <ide> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.VersionString(1), remote) <ide> <del> log.Debugf("[registry] Calling GET %s", repositoryTarget) <add> logrus.Debugf("[registry] Calling GET %s", repositoryTarget) <ide> <ide> req, err := r.reqFactory.NewRequest("GET", repositoryTarget, nil) <ide> if err != nil { <ide> func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) { <ide> } else if res.StatusCode != 200 { <ide> errBody, err := ioutil.ReadAll(res.Body) <ide> if err != nil { <del> log.Debugf("Error reading response body: %s", err) <add> logrus.Debugf("Error reading response body: %s", err) <ide> } <ide> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, remote, errBody), res) <ide> } <ide> func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) { <ide> <ide> func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string, token []string) error { <ide> <del> log.Debugf("[registry] Calling PUT %s", registry+"images/"+imgData.ID+"/checksum") <add> logrus.Debugf("[registry] Calling PUT %s", registry+"images/"+imgData.ID+"/checksum") <ide> <ide> req, err := r.reqFactory.NewRequest("PUT", registry+"images/"+imgData.ID+"/checksum", nil) <ide> if err != nil { <ide> func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string, t <ide> // Push a local image to the registry <ide> func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string, token []string) error { <ide> <del> log.Debugf("[registry] Calling PUT %s", registry+"images/"+imgData.ID+"/json") <add> logrus.Debugf("[registry] Calling PUT %s", registry+"images/"+imgData.ID+"/json") <ide> <ide> req, err := r.reqFactory.NewRequest("PUT", registry+"images/"+imgData.ID+"/json", bytes.NewReader(jsonRaw)) <ide> if err != nil { <ide> func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, regist <ide> <ide> func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, token []string, jsonRaw []byte) (checksum string, checksumPayload string, err error) { <ide> <del> log.Debugf("[registry] Calling PUT %s", registry+"images/"+imgID+"/layer") <add> logrus.Debugf("[registry] Calling PUT %s", registry+"images/"+imgID+"/layer") <ide> <ide> tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0) <ide> if err != nil { <ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate <ide> suffix = "images" <ide> } <ide> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.VersionString(1), remote, suffix) <del> log.Debugf("[registry] PUT %s", u) <del> log.Debugf("Image list pushed to index:\n%s", imgListJSON) <add> logrus.Debugf("[registry] PUT %s", u) <add> logrus.Debugf("Image list pushed to index:\n%s", imgListJSON) <ide> headers := map[string][]string{ <ide> "Content-type": {"application/json"}, <ide> "X-Docker-Token": {"true"}, <ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate <ide> } <ide> res.Body.Close() <ide> u = res.Header.Get("Location") <del> log.Debugf("Redirected to %s", u) <add> logrus.Debugf("Redirected to %s", u) <ide> } <ide> defer res.Body.Close() <ide> <ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate <ide> if res.StatusCode != 200 && res.StatusCode != 201 { <ide> errBody, err := ioutil.ReadAll(res.Body) <ide> if err != nil { <del> log.Debugf("Error reading response body: %s", err) <add> logrus.Debugf("Error reading response body: %s", err) <ide> } <ide> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote, errBody), res) <ide> } <ide> if res.Header.Get("X-Docker-Token") != "" { <ide> tokens = res.Header["X-Docker-Token"] <del> log.Debugf("Auth token: %v", tokens) <add> logrus.Debugf("Auth token: %v", tokens) <ide> } else { <ide> return nil, fmt.Errorf("Index response didn't contain an access token") <ide> } <ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate <ide> if res.StatusCode != 204 { <ide> errBody, err := ioutil.ReadAll(res.Body) <ide> if err != nil { <del> log.Debugf("Error reading response body: %s", err) <add> logrus.Debugf("Error reading response body: %s", err) <ide> } <ide> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote, errBody), res) <ide> } <ide> func shouldRedirect(response *http.Response) bool { <ide> } <ide> <ide> func (r *Session) SearchRepositories(term string) (*SearchResults, error) { <del> log.Debugf("Index server: %s", r.indexEndpoint) <add> logrus.Debugf("Index server: %s", r.indexEndpoint) <ide> u := r.indexEndpoint.VersionString(1) + "search?q=" + url.QueryEscape(term) <ide> req, err := r.reqFactory.NewRequest("GET", u, nil) <ide> if err != nil { <ide><path>registry/session_v2.go <ide> import ( <ide> "net/http" <ide> "strconv" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/registry/v2" <ide> "github.com/docker/docker/utils" <ide> func (r *Session) GetV2Authorization(ep *Endpoint, imageName string, readOnly bo <ide> scopes = append(scopes, "push") <ide> } <ide> <del> log.Debugf("Getting authorization for %s %s", imageName, scopes) <add> logrus.Debugf("Getting authorization for %s %s", imageName, scopes) <ide> return NewRequestAuthorization(r.GetAuthConfig(true), ep, "repository", imageName, scopes), nil <ide> } <ide> <ide> func (r *Session) GetV2ImageManifest(ep *Endpoint, imageName, tagName string, au <ide> } <ide> <ide> method := "GET" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> <ide> req, err := r.reqFactory.NewRequest(method, routeURL, nil) <ide> if err != nil { <ide> func (r *Session) HeadV2ImageBlob(ep *Endpoint, imageName, sumType, sum string, <ide> } <ide> <ide> method := "HEAD" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> <ide> req, err := r.reqFactory.NewRequest(method, routeURL, nil) <ide> if err != nil { <ide> func (r *Session) GetV2ImageBlob(ep *Endpoint, imageName, sumType, sum string, b <ide> } <ide> <ide> method := "GET" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> req, err := r.reqFactory.NewRequest(method, routeURL, nil) <ide> if err != nil { <ide> return err <ide> func (r *Session) GetV2ImageBlobReader(ep *Endpoint, imageName, sumType, sum str <ide> } <ide> <ide> method := "GET" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> req, err := r.reqFactory.NewRequest(method, routeURL, nil) <ide> if err != nil { <ide> return nil, 0, err <ide> func (r *Session) PutV2ImageBlob(ep *Endpoint, imageName, sumType, sumStr string <ide> } <ide> <ide> method := "PUT" <del> log.Debugf("[registry] Calling %q %s", method, location) <add> logrus.Debugf("[registry] Calling %q %s", method, location) <ide> req, err := r.reqFactory.NewRequest(method, location, ioutil.NopCloser(blobRdr)) <ide> if err != nil { <ide> return err <ide> func (r *Session) PutV2ImageBlob(ep *Endpoint, imageName, sumType, sumStr string <ide> if err != nil { <ide> return err <ide> } <del> log.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <add> logrus.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <ide> return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s blob - %s:%s", res.StatusCode, imageName, sumType, sumStr), res) <ide> } <ide> <ide> func (r *Session) initiateBlobUpload(ep *Endpoint, imageName string, auth *Reque <ide> return "", err <ide> } <ide> <del> log.Debugf("[registry] Calling %q %s", "POST", routeURL) <add> logrus.Debugf("[registry] Calling %q %s", "POST", routeURL) <ide> req, err := r.reqFactory.NewRequest("POST", routeURL, nil) <ide> if err != nil { <ide> return "", err <ide> func (r *Session) initiateBlobUpload(ep *Endpoint, imageName string, auth *Reque <ide> return "", err <ide> } <ide> <del> log.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <add> logrus.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <ide> return "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: unexpected %d response status trying to initiate upload of %s", res.StatusCode, imageName), res) <ide> } <ide> <ide> func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, si <ide> } <ide> <ide> method := "PUT" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> req, err := r.reqFactory.NewRequest(method, routeURL, bytes.NewReader(signedManifest)) <ide> if err != nil { <ide> return "", err <ide> func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, si <ide> if err != nil { <ide> return "", err <ide> } <del> log.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <add> logrus.Debugf("Unexpected response from server: %q %#v", errBody, res.Header) <ide> return "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s:%s manifest", res.StatusCode, imageName, tagName), res) <ide> } <ide> <ide> func (r *Session) GetV2RemoteTags(ep *Endpoint, imageName string, auth *RequestA <ide> } <ide> <ide> method := "GET" <del> log.Debugf("[registry] Calling %q %s", method, routeURL) <add> logrus.Debugf("[registry] Calling %q %s", method, routeURL) <ide> <ide> req, err := r.reqFactory.NewRequest(method, routeURL, nil) <ide> if err != nil { <ide><path>runconfig/merge.go <ide> package runconfig <ide> import ( <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/nat" <ide> ) <ide> <ide> func Merge(userConf, imageConf *Config) error { <ide> } <ide> if len(imageConf.PortSpecs) > 0 { <ide> // FIXME: I think we can safely remove this. Leaving it for now for the sake of reverse-compat paranoia. <del> log.Debugf("Migrating image port specs to containter: %s", strings.Join(imageConf.PortSpecs, ", ")) <add> logrus.Debugf("Migrating image port specs to containter: %s", strings.Join(imageConf.PortSpecs, ", ")) <ide> if userConf.ExposedPorts == nil { <ide> userConf.ExposedPorts = make(nat.PortSet) <ide> } <ide><path>trust/service.go <ide> import ( <ide> "fmt" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/libtrust" <ide> ) <ide> func (t *TrustStore) CmdCheckKey(job *engine.Job) error { <ide> return fmt.Errorf("Error verifying key to namespace: %s", namespace) <ide> } <ide> if !verified { <del> log.Debugf("Verification failed for %s using key %s", namespace, pk.KeyID()) <add> logrus.Debugf("Verification failed for %s using key %s", namespace, pk.KeyID()) <ide> job.Stdout.Write([]byte("not verified")) <ide> } else if t.expiration.Before(time.Now()) { <ide> job.Stdout.Write([]byte("expired")) <ide><path>trust/trusts.go <ide> import ( <ide> "sync" <ide> "time" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/libtrust/trustgraph" <ide> ) <ide> <ide> func (t *TrustStore) reload() error { <ide> } <ide> if len(statements) == 0 { <ide> if t.autofetch { <del> log.Debugf("No grants, fetching") <add> logrus.Debugf("No grants, fetching") <ide> t.fetcher = time.AfterFunc(t.fetchTime, t.fetch) <ide> } <ide> return nil <ide> func (t *TrustStore) reload() error { <ide> <ide> t.expiration = expiration <ide> t.graph = trustgraph.NewMemoryGraph(grants) <del> log.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration) <add> logrus.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration) <ide> <ide> if t.autofetch { <ide> nextFetch := expiration.Sub(time.Now()) <ide> func (t *TrustStore) fetch() { <ide> for bg, ep := range t.baseEndpoints { <ide> statement, err := t.fetchBaseGraph(ep) <ide> if err != nil { <del> log.Infof("Trust graph fetch failed: %s", err) <add> logrus.Infof("Trust graph fetch failed: %s", err) <ide> continue <ide> } <ide> b, err := statement.Bytes() <ide> if err != nil { <del> log.Infof("Bad trust graph statement: %s", err) <add> logrus.Infof("Bad trust graph statement: %s", err) <ide> continue <ide> } <ide> // TODO check if value differs <ide> err = ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600) <ide> if err != nil { <del> log.Infof("Error writing trust graph statement: %s", err) <add> logrus.Infof("Error writing trust graph statement: %s", err) <ide> } <ide> fetchCount++ <ide> } <del> log.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now()) <add> logrus.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now()) <ide> <ide> if fetchCount > 0 { <ide> go func() { <ide> err := t.reload() <ide> if err != nil { <del> log.Infof("Reload of trust graph failed: %s", err) <add> logrus.Infof("Reload of trust graph failed: %s", err) <ide> } <ide> }() <ide> t.fetchTime = defaultFetchtime <ide><path>utils/http.go <ide> import ( <ide> "net/http" <ide> "strings" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> ) <ide> <ide> // VersionInfo is used to model entities which has a version. <ide> func (h *HTTPRequestFactory) NewRequest(method, urlStr string, body io.Reader, d <ide> return nil, err <ide> } <ide> } <del> log.Debugf("%v -- HEADERS: %v", req.URL, req.Header) <add> logrus.Debugf("%v -- HEADERS: %v", req.URL, req.Header) <ide> return req, err <ide> } <ide><path>utils/utils.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/fileutils" <ide> func DockerInitPath(localCopy string) string { <ide> <ide> func GetTotalUsedFds() int { <ide> if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { <del> log.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) <add> logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) <ide> } else { <ide> return len(fds) <ide> } <ide><path>volumes/repository.go <ide> import ( <ide> "path/filepath" <ide> "sync" <ide> <del> log "github.com/Sirupsen/logrus" <add> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/stringid" <ide> ) <ide> func (r *Repository) restore() error { <ide> } <ide> if err := vol.FromDisk(); err != nil { <ide> if !os.IsNotExist(err) { <del> log.Debugf("Error restoring volume: %v", err) <add> logrus.Debugf("Error restoring volume: %v", err) <ide> continue <ide> } <ide> if err := vol.initialize(); err != nil { <del> log.Debugf("%s", err) <add> logrus.Debugf("%s", err) <ide> continue <ide> } <ide> } <ide> if err := r.add(vol); err != nil { <del> log.Debugf("Error restoring volume: %v", err) <add> logrus.Debugf("Error restoring volume: %v", err) <ide> } <ide> } <ide> return nil
82
PHP
PHP
update version in deprecated tag
beccf7f6b05bc2527b1bfa287c9908e594053f5a
<ide><path>src/ORM/AssociationCollection.php <ide> public function keys() <ide> * @param string|array $class The type of associations you want. <ide> * For example 'BelongsTo' or array like ['BelongsTo', 'HasOne'] <ide> * @return array An array of Association objects. <del> * @deprecated 3.6.0 Use getByType() instead. <add> * @deprecated 3.5.3 Use getByType() instead. <ide> */ <ide> public function type($class) <ide> {
1
Javascript
Javascript
make reactperf.start() work during reconciliation
1a0e3a32150468223d6f9fd0125db0f8503b76d6
<ide><path>src/renderers/dom/client/ReactMount.js <ide> var ReactMount = { <ide> shouldReuseMarkup, <ide> context <ide> ) { <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onBeginFlush(); <del> } <del> <ide> // Various parts of our code (such as ReactCompositeComponent's <ide> // _renderValidatedComponent) assume that calls to render aren't nested; <ide> // verify that that's the case. <ide> var ReactMount = { <ide> ReactInstrumentation.debugTool.onMountRootComponent( <ide> componentInstance._renderedComponent._debugID <ide> ); <del> ReactInstrumentation.debugTool.onEndFlush(); <ide> } <ide> <ide> return componentInstance; <ide><path>src/renderers/dom/client/ReactReconcileTransaction.js <ide> var CallbackQueue = require('CallbackQueue'); <ide> var PooledClass = require('PooledClass'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> var ReactInputSelection = require('ReactInputSelection'); <add>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var Transaction = require('Transaction'); <ide> var ReactUpdateQueue = require('ReactUpdateQueue'); <ide> <ide> var TRANSACTION_WRAPPERS = [ <ide> ON_DOM_READY_QUEUEING, <ide> ]; <ide> <add>if (__DEV__) { <add> TRANSACTION_WRAPPERS.push({ <add> initialize: ReactInstrumentation.debugTool.onBeginFlush, <add> close: ReactInstrumentation.debugTool.onEndFlush, <add> }); <add>} <add> <ide> /** <ide> * Currently: <ide> * - The order that these are listed in the transaction is critical: <ide><path>src/renderers/dom/server/ReactServerRendering.js <ide> function renderToStringImpl(element, makeStaticMarkup) { <ide> transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup); <ide> <ide> return transaction.perform(function() { <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onBeginFlush(); <del> } <ide> var componentInstance = instantiateReactComponent(element, true); <ide> var markup = ReactReconciler.mountComponent( <ide> componentInstance, <ide> function renderToStringImpl(element, makeStaticMarkup) { <ide> ReactInstrumentation.debugTool.onUnmountComponent( <ide> componentInstance._debugID <ide> ); <del> ReactInstrumentation.debugTool.onEndFlush(); <ide> } <ide> if (!makeStaticMarkup) { <ide> markup = ReactMarkupChecksum.addChecksumToMarkup(markup); <ide><path>src/renderers/dom/server/ReactServerRenderingTransaction.js <ide> <ide> var PooledClass = require('PooledClass'); <ide> var Transaction = require('Transaction'); <add>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactServerUpdateQueue = require('ReactServerUpdateQueue'); <ide> <ide> <ide> var ReactServerUpdateQueue = require('ReactServerUpdateQueue'); <ide> */ <ide> var TRANSACTION_WRAPPERS = []; <ide> <add>if (__DEV__) { <add> TRANSACTION_WRAPPERS.push({ <add> initialize: ReactInstrumentation.debugTool.onBeginFlush, <add> close: ReactInstrumentation.debugTool.onEndFlush, <add> }); <add>} <add> <ide> var noopCallbackQueue = { <ide> enqueue: function() {}, <ide> }; <ide><path>src/renderers/native/ReactNativeMount.js <ide> var ReactNativeMount = { <ide> var instance = instantiateReactComponent(nextWrappedElement, false); <ide> ReactNativeMount._instancesByContainerID[containerTag] = instance; <ide> <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onBeginFlush(); <del> } <del> <ide> // The initial render is synchronous but any updates that happen during <ide> // rendering, in componentWillMount or componentDidMount, will be batched <ide> // according to the current batching strategy. <ide> var ReactNativeMount = { <ide> ReactInstrumentation.debugTool.onMountRootComponent( <ide> instance._renderedComponent._debugID <ide> ); <del> ReactInstrumentation.debugTool.onEndFlush(); <ide> } <ide> var component = instance.getPublicInstance(); <ide> if (callback) { <ide><path>src/renderers/native/ReactNativeReconcileTransaction.js <ide> var CallbackQueue = require('CallbackQueue'); <ide> var PooledClass = require('PooledClass'); <ide> var Transaction = require('Transaction'); <add>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactUpdateQueue = require('ReactUpdateQueue'); <ide> <ide> /** <ide> var ON_DOM_READY_QUEUEING = { <ide> */ <ide> var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; <ide> <add>if (__DEV__) { <add> TRANSACTION_WRAPPERS.push({ <add> initialize: ReactInstrumentation.debugTool.onBeginFlush, <add> close: ReactInstrumentation.debugTool.onEndFlush, <add> }); <add>} <add> <ide> /** <ide> * Currently: <ide> * - The order that these are listed in the transaction is critical: <ide><path>src/renderers/shared/ReactDebugTool.js <ide> function resetMeasurements() { <ide> var previousMeasurements = currentFlushMeasurements || []; <ide> var previousOperations = ReactHostOperationHistoryDevtool.getHistory(); <ide> <del> if (!isProfiling || currentFlushNesting === 0) { <add> if (currentFlushNesting === 0) { <ide> currentFlushStartTime = null; <ide> currentFlushMeasurements = null; <ide> clearHistory(); <ide> function checkDebugID(debugID) { <ide> } <ide> <ide> function beginLifeCycleTimer(debugID, timerType) { <del> if (!isProfiling || currentFlushNesting === 0) { <add> if (currentFlushNesting === 0) { <ide> return; <ide> } <ide> warning( <ide> function beginLifeCycleTimer(debugID, timerType) { <ide> } <ide> <ide> function endLifeCycleTimer(debugID, timerType) { <del> if (!isProfiling || currentFlushNesting === 0) { <add> if (currentFlushNesting === 0) { <ide> return; <ide> } <ide> warning( <ide> function endLifeCycleTimer(debugID, timerType) { <ide> currentTimerType || 'no', <ide> (debugID === currentTimerDebugID) ? 'the same' : 'another' <ide> ); <del> currentFlushMeasurements.push({ <del> timerType, <del> instanceID: debugID, <del> duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration, <del> }); <add> if (isProfiling) { <add> currentFlushMeasurements.push({ <add> timerType, <add> instanceID: debugID, <add> duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration, <add> }); <add> } <ide> currentTimerStartTime = null; <ide> currentTimerNestedFlushDuration = null; <ide> currentTimerDebugID = null; <ide> var ReactDebugTool = { <ide> isProfiling = true; <ide> flushHistory.length = 0; <ide> resetMeasurements(); <add> ReactDebugTool.addDevtool(ReactHostOperationHistoryDevtool); <ide> }, <ide> endProfiling() { <ide> if (!isProfiling) { <ide> var ReactDebugTool = { <ide> <ide> isProfiling = false; <ide> resetMeasurements(); <add> ReactDebugTool.removeDevtool(ReactHostOperationHistoryDevtool); <ide> }, <ide> getFlushHistory() { <ide> return flushHistory; <ide> var ReactDebugTool = { <ide> checkDebugID(debugID); <ide> emitEvent('onEndReconcilerTimer', debugID, timerType); <ide> }, <add> onError(debugID) { <add> if (currentTimerDebugID != null) { <add> endLifeCycleTimer(currentTimerDebugID, currentTimerType); <add> } <add> emitEvent('onError', debugID); <add> }, <ide> onBeginProcessingChildContext() { <ide> emitEvent('onBeginProcessingChildContext'); <ide> }, <ide> var ReactDebugTool = { <ide> <ide> ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool); <ide> ReactDebugTool.addDevtool(ReactComponentTreeDevtool); <del>ReactDebugTool.addDevtool(ReactHostOperationHistoryDevtool); <ide> ReactDebugTool.addDevtool(ReactChildrenMutationWarningDevtool); <ide> var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; <ide> if ((/[?&]react_perf\b/).test(url)) { <ide><path>src/renderers/shared/__tests__/ReactPerf-test.js <ide> describe('ReactPerf', function() { <ide> expect(console.error.calls.count()).toBe(1); <ide> <ide> __DEV__ = true; <del> }) <add> }); <add> <add> it('should work when measurement starts during reconciliation', () => { <add> // https://github.com/facebook/react/issues/6949#issuecomment-230371009 <add> var Measurer = React.createClass({ <add> componentWillMount() { <add> ReactPerf.start(); <add> }, <add> componentDidMount() { <add> ReactPerf.stop(); <add> }, <add> componentWillUpdate() { <add> ReactPerf.start(); <add> }, <add> componentDidUpdate() { <add> ReactPerf.stop(); <add> }, <add> render() { <add> // Force reconciliation despite constant element <add> return React.cloneElement(this.props.children); <add> }, <add> }); <add> <add> var container = document.createElement('div'); <add> ReactDOM.render(<Measurer><App /></Measurer>, container); <add> expect(ReactPerf.getWasted()).toEqual([]); <add> <add> ReactDOM.render(<Measurer><App /></Measurer>, container); <add> expect(ReactPerf.getWasted()).toEqual([{ <add> key: 'Measurer', <add> instanceCount: 1, <add> inclusiveRenderDuration: 4, <add> renderCount: 1, <add> }, { <add> key: 'App', <add> instanceCount: 1, <add> inclusiveRenderDuration: 3, <add> renderCount: 1, <add> }, { <add> key: 'App > Box', <add> instanceCount: 2, <add> inclusiveRenderDuration: 2, <add> renderCount: 2, <add> }]); <add> }); <ide> }); <ide><path>src/renderers/shared/devtools/__tests__/ReactHostOperationHistoryDevtool-test.js <ide> <ide> describe('ReactHostOperationHistoryDevtool', () => { <ide> var React; <add> var ReactPerf; <ide> var ReactDOM; <ide> var ReactDOMComponentTree; <ide> var ReactDOMFeatureFlags; <ide> describe('ReactHostOperationHistoryDevtool', () => { <ide> jest.resetModuleRegistry(); <ide> <ide> React = require('React'); <add> ReactPerf = require('ReactPerf'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactDOMComponentTree = require('ReactDOMComponentTree'); <ide> ReactDOMFeatureFlags = require('ReactDOMFeatureFlags'); <ide> ReactHostOperationHistoryDevtool = require('ReactHostOperationHistoryDevtool'); <add> <add> ReactPerf.start(); <ide> }); <ide> <add> afterEach(() => { <add> ReactPerf.stop(); <add> }) <add> <ide> function assertHistoryMatches(expectedHistory) { <ide> var actualHistory = ReactHostOperationHistoryDevtool.getHistory(); <ide> expect(actualHistory).toEqual(expectedHistory); <ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> try { <ide> markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); <ide> } catch (e) { <add> if (__DEV__) { <add> if (this._debugID !== 0) { <add> ReactInstrumentation.debugTool.onError(); <add> } <add> } <ide> // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint <ide> transaction.rollback(checkpoint); <ide> this._instance.unstable_handleError(e); <ide><path>src/renderers/shared/stack/reconciler/ReactUpdates.js <ide> var CallbackQueue = require('CallbackQueue'); <ide> var PooledClass = require('PooledClass'); <ide> var ReactFeatureFlags = require('ReactFeatureFlags'); <del>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> var Transaction = require('Transaction'); <ide> <ide> function runBatchedUpdates(transaction) { <ide> } <ide> <ide> var flushBatchedUpdates = function() { <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onBeginFlush(); <del> } <del> <ide> // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents <ide> // array and perform any updates enqueued by mount-ready handlers (i.e., <ide> // componentDidUpdate) but we need to check here too in order to catch <ide> var flushBatchedUpdates = function() { <ide> CallbackQueue.release(queue); <ide> } <ide> } <del> <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onEndFlush(); <del> } <ide> }; <ide> <ide> /** <ide><path>src/renderers/testing/ReactTestMount.js <ide> var ReactHostMount = { <ide> <ide> var instance = instantiateReactComponent(nextWrappedElement, false); <ide> <del> if (__DEV__) { <del> ReactInstrumentation.debugTool.onBeginFlush(); <del> } <del> <ide> // The initial render is synchronous but any updates that happen during <ide> // rendering, in componentWillMount or componentDidMount, will be batched <ide> // according to the current batching strategy. <ide> var ReactHostMount = { <ide> ReactInstrumentation.debugTool.onMountRootComponent( <ide> instance._renderedComponent._debugID <ide> ); <del> ReactInstrumentation.debugTool.onEndFlush(); <ide> } <ide> return new ReactTestInstance(instance); <ide> },
12
Javascript
Javascript
remove unnecessary checks
baa7bec6fd58d7b0baef2cf79847a91fca495bca
<ide><path>examples/js/loaders/VTKLoader.js <ide> Object.assign( THREE.VTKLoader.prototype, THREE.EventDispatcher.prototype, { <ide> <ide> delete ele[ '#text' ]; <ide> <del> // Get the content and optimize it <del> if ( ele.attributes.type === 'Float32' ) { <del> <del> if ( ele.attributes.format === 'binary' ) { <del> <del> if ( ! compressed ) { <del> <del> txt = txt.filter( function ( el, idx ) { <del> <del> if ( idx !== 0 ) return true; <del> <del> } ); <del> <del> } <del> <del> } <del> <del> } else if ( ele.attributes.type === 'Int64' ) { <add> if ( ele.attributes.type === 'Int64' ) { <ide> <ide> if ( ele.attributes.format === 'binary' ) { <ide> <del> if ( ! compressed ) { <del> <del> txt = txt.filter( function ( el, idx ) { <del> <del> if ( idx !== 0 ) return true; <del> <del> } ); <del> <del> } <del> <ide> txt = txt.filter( function ( el, idx ) { <ide> <ide> if ( idx % 2 !== 1 ) return true;
1