content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
add notes about the deployments
4facf4a1bd10e2857da09da1cac5dab2b59ae22b
<ide><path>docs/how-to-enable-new-languages.md <ide> Then commit and push your branch directly to the News repo. <ide> <ide> Finally, open a PR for review. <ide> <del>Once both your PRs to the CDN and News repo have been approved, they can be merged. Deployment will be handled subsequently by the staff. <add>Once both your PRs to the CDN and News repo have been approved, they can be merged. <add> <add>> [!NOTE] <add>> Deployment will be handled subsequently by the staff. Here is a sample PR: [freeCodeCamp/news#485](https://github.com/freeCodeCamp/news/pull/485) of how they do it and more details are available in the [staff-wiki](https://staff-wiki.freecodecamp.org/docs/flight-manuals/news-instances#jamstack---news--assets).
1
Javascript
Javascript
destroy socket on dns error
4671e54495a29696ae8e5f9bd17ba4c63f5d1b23
<ide><path>lib/net.js <ide> Socket.prototype.connect = function(port /* [host], [cb] */) { <ide> // error event to the next tick. <ide> process.nextTick(function() { <ide> self.emit('error', err); <add> self.destroy(); <ide> }); <ide> } else { <ide> timers.active(self);
1
Mixed
Javascript
fix stoppable events in tests and docs
e3fcd96dc4b3e51e9b1260a85fe477c2a8901a75
<ide><path>actionview/test/ujs/public/test/call-remote-callbacks.js <ide> asyncTest('setting data("with-credentials",true) with "ajax:before" uses new set <ide> <ide> asyncTest('stopping the "ajax:beforeSend" event aborts the request', 1, function() { <ide> submit(function(form) { <del> form.bindNative('ajax:beforeSend', function() { <add> form.bindNative('ajax:beforeSend', function(e) { <ide> ok(true, 'aborting request in ajax:beforeSend') <del> return false <add> e.preventDefault() <ide> }) <ide> form.unbind('ajax:send').bindNative('ajax:send', function() { <ide> ok(false, 'ajax:send should not run') <ide> function skipIt() { <ide> .bind('iframe:loading', function() { <ide> ok(false, 'form should not get submitted') <ide> }) <del> .bindNative('ajax:aborted:file', function() { <del> return false <add> .bindNative('ajax:aborted:file', function(e) { <add> e.preventDefault() <ide> }) <ide> .triggerNative('submit') <ide> <ide> function skipIt() { <ide> } <ide> <ide> asyncTest('"ajax:beforeSend" can be observed and stopped with event delegation', 1, function() { <del> $(document).delegate('form[data-remote]', 'ajax:beforeSend', function() { <add> $(document).delegate('form[data-remote]', 'ajax:beforeSend', function(e) { <ide> ok(true, 'ajax:beforeSend observed with event delegation') <del> return false <add> e.preventDefault() <ide> }) <ide> <ide> submit(function(form) { <ide><path>actionview/test/ujs/public/test/call-remote.js <ide> asyncTest('allow empty form "action"', 1, function() { <ide> buildForm({ action: '' }) <ide> <ide> $('#qunit-fixture').find('form') <del> .bindNative('ajax:beforeSend', function(e, xhr, settings) { <add> .bindNative('ajax:beforeSend', function(evt, xhr, settings) { <ide> // Get current location (the same way jQuery does) <ide> try { <ide> currentLocation = location.href <ide> asyncTest('allow empty form "action"', 1, function() { <ide> <ide> // Prevent the request from actually getting sent to the current page and <ide> // causing an error. <del> return false <add> evt.preventDefault() <ide> }) <ide> .triggerNative('submit') <ide> <ide> asyncTest('intelligently guesses crossDomain behavior when target URL has a diff <ide> equal(settings.crossDomain, true, 'crossDomain should be set to true') <ide> <ide> // prevent request from actually getting sent off-domain <del> return false <add> evt.preventDefault() <ide> }) <ide> .triggerNative('submit') <ide> <ide> asyncTest('intelligently guesses crossDomain behavior when target URL consists o <ide> equal(settings.crossDomain, false, 'crossDomain should be set to false') <ide> <ide> // prevent request from actually getting sent off-domain <del> return false <add> evt.preventDefault() <ide> }) <ide> .triggerNative('submit') <ide> <ide><path>actionview/test/ujs/public/test/data-confirm.js <ide> asyncTest('binding to confirm event of a link and returning false', 1, function( <ide> } <ide> <ide> $('a[data-confirm]') <del> .bindNative('confirm', function() { <add> .bindNative('confirm', function(e) { <ide> App.assertCallbackInvoked('confirm') <del> return false <add> e.preventDefault() <ide> }) <ide> .bindNative('confirm:complete', function() { <ide> App.assertCallbackNotInvoked('confirm:complete') <ide> asyncTest('binding to confirm event of a button and returning false', 1, functio <ide> } <ide> <ide> $('button[data-confirm]') <del> .bindNative('confirm', function() { <add> .bindNative('confirm', function(e) { <ide> App.assertCallbackInvoked('confirm') <del> return false <add> e.preventDefault() <ide> }) <ide> .bindNative('confirm:complete', function() { <ide> App.assertCallbackNotInvoked('confirm:complete') <ide> asyncTest('binding to confirm:complete event of a link and returning false', 2, <ide> } <ide> <ide> $('a[data-confirm]') <del> .bindNative('confirm:complete', function() { <add> .bindNative('confirm:complete', function(e) { <ide> App.assertCallbackInvoked('confirm:complete') <del> return false <add> e.preventDefault() <ide> }) <ide> .bindNative('ajax:beforeSend', function() { <ide> App.assertCallbackNotInvoked('ajax:beforeSend') <ide> asyncTest('binding to confirm:complete event of a button and returning false', 2 <ide> } <ide> <ide> $('button[data-confirm]') <del> .bindNative('confirm:complete', function() { <add> .bindNative('confirm:complete', function(e) { <ide> App.assertCallbackInvoked('confirm:complete') <del> return false <add> e.preventDefault() <ide> }) <ide> .bindNative('ajax:beforeSend', function() { <ide> App.assertCallbackNotInvoked('ajax:beforeSend') <ide><path>actionview/test/ujs/public/test/data-disable-with.js <ide> test('form input[type=submit][data-disable-with] re-enables when `pageshow` even <ide> }) <ide> <ide> asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced in ajax callback', 2, function() { <del> var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html() <add> var form = $('#qunit-fixture form:not([data-remote])').attr('data-remote', 'true'), <add> origFormContents = form.html() <ide> <ide> form.bindNative('ajax:success', function() { <ide> form.html(origFormContents) <ide> asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced i <ide> }) <ide> <ide> asyncTest('form[data-remote] input[data-disable-with] is replaced with disabled field in ajax callback', 2, function() { <del> var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'), <add> var form = $('#qunit-fixture form:not([data-remote])').attr('data-remote', 'true'), <add> input = form.find('input[type=submit]'), <ide> newDisabledInput = input.clone().attr('disabled', 'disabled') <ide> <ide> form.bindNative('ajax:success', function() { <ide> asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:before` event <ide> App.checkEnabledState(link, 'Click me') <ide> <ide> link <del> .bindNative('ajax:before', function() { <add> .bindNative('ajax:before', function(e) { <ide> App.checkDisabledState(link, 'clicking...') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:beforeSend` e <ide> App.checkEnabledState(link, 'Click me') <ide> <ide> link <del> .bindNative('ajax:beforeSend', function() { <add> .bindNative('ajax:beforeSend', function(e) { <ide> App.checkDisabledState(link, 'clicking...') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not d <ide> submit = $('<input type="submit" data-disable-with="submitting ..." name="submit2" value="Submit" />').appendTo(form) <ide> <ide> form <del> .bindNative('ajax:beforeSend', function() { <del> return false <add> .bindNative('ajax:beforeSend', function(e) { <add> e.preventDefault() <add> e.stopPropagation() <ide> }) <ide> .triggerNative('submit') <ide> <ide> asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:before` <ide> App.checkEnabledState(button, 'Click me') <ide> <ide> button <del> .bindNative('ajax:before', function() { <add> .bindNative('ajax:before', function(e) { <ide> App.checkDisabledState(button, 'clicking...') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:beforeSe <ide> App.checkEnabledState(button, 'Click me') <ide> <ide> button <del> .bindNative('ajax:beforeSend', function() { <add> .bindNative('ajax:beforeSend', function(e) { <ide> App.checkDisabledState(button, 'clicking...') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide><path>actionview/test/ujs/public/test/data-disable.js <ide> asyncTest('form input[type=submit][data-disable] disables', 6, function() { <ide> }) <ide> <ide> asyncTest('form[data-remote] input[type=submit][data-disable] is replaced in ajax callback', 2, function() { <del> var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html() <add> var form = $('#qunit-fixture form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html() <ide> <ide> form.bindNative('ajax:success', function() { <ide> form.html(origFormContents) <ide> asyncTest('form[data-remote] input[type=submit][data-disable] is replaced in aja <ide> }) <ide> <ide> asyncTest('form[data-remote] input[data-disable] is replaced with disabled field in ajax callback', 2, function() { <del> var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'), <add> var form = $('#qunit-fixture form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'), <ide> newDisabledInput = input.clone().attr('disabled', 'disabled') <ide> <ide> form.bindNative('ajax:success', function() { <ide> asyncTest('a[data-remote][data-disable] re-enables when `ajax:before` event is c <ide> App.checkEnabledState(link, 'Click me') <ide> <ide> link <del> .bindNative('ajax:before', function() { <add> .bindNative('ajax:before', function(e) { <ide> App.checkDisabledState(link, 'Click me') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('a[data-remote][data-disable] re-enables when `ajax:beforeSend` event <ide> App.checkEnabledState(link, 'Click me') <ide> <ide> link <del> .bindNative('ajax:beforeSend', function() { <add> .bindNative('ajax:beforeSend', function(e) { <ide> App.checkDisabledState(link, 'Click me') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('form[data-remote] input|button|textarea[data-disable] does not disabl <ide> submit = $('<input type="submit" data-disable="submitting ..." name="submit2" value="Submit" />').appendTo(form) <ide> <ide> form <del> .bindNative('ajax:beforeSend', function() { <del> return false <add> .bindNative('ajax:beforeSend', function(e) { <add> e.preventDefault() <add> e.stopPropagation() <ide> }) <ide> .triggerNative('submit') <ide> <ide> asyncTest('button[data-remote][data-disable] re-enables when `ajax:before` event <ide> App.checkEnabledState(button, 'Click me') <ide> <ide> button <del> .bindNative('ajax:before', function() { <add> .bindNative('ajax:before', function(e) { <ide> App.checkDisabledState(button, 'Click me') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('button[data-remote][data-disable] re-enables when `ajax:beforeSend` e <ide> App.checkEnabledState(button, 'Click me') <ide> <ide> button <del> .bindNative('ajax:beforeSend', function() { <add> .bindNative('ajax:beforeSend', function(e) { <ide> App.checkDisabledState(button, 'Click me') <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide><path>actionview/test/ujs/public/test/data-remote.js <ide> asyncTest('returning false in form\'s submit bindings in non-submit-bubbling bro <ide> <ide> form <ide> .append($('<input type="submit" />')) <del> .bindNative('submit', function() { <add> .bindNative('submit', function(e) { <ide> ok(true, 'binding handler is called') <del> return false <add> e.preventDefault() <add> e.stopPropagation() <ide> }) <ide> .bindNative('ajax:beforeSend', function() { <ide> ok(false, 'form should not be submitted') <ide> asyncTest('clicking on a link with falsy "data-remote" attribute does not fire a <ide> .bindNative('ajax:beforeSend', function() { <ide> ok(false, 'ajax should not be triggered') <ide> }) <del> .bindNative('click', function() { <del> return false <add> .bindNative('click', function(e) { <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('ctrl-clicking on a link with falsy "data-remote" attribute does not f <ide> .bindNative('ajax:beforeSend', function() { <ide> ok(false, 'ajax should not be triggered') <ide> }) <del> .bindNative('click', function() { <del> return false <add> .bindNative('click', function(e) { <add> e.preventDefault() <ide> }) <ide> .triggerNative('click', { metaKey: true }) <ide> <ide> asyncTest('clicking on a button with falsy "data-remote" attribute', 0, function <ide> .bindNative('ajax:beforeSend', function() { <ide> ok(false, 'ajax should not be triggered') <ide> }) <del> .bindNative('click', function() { <del> return false <add> .bindNative('click', function(e) { <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> <ide> asyncTest('submitting a form with falsy "data-remote" attribute', 0, function() <ide> .bindNative('ajax:beforeSend', function() { <ide> ok(false, 'ajax should not be triggered') <ide> }) <del> .bindNative('submit', function() { <del> return false <add> .bindNative('submit', function(e) { <add> e.preventDefault() <ide> }) <ide> .triggerNative('submit') <ide> <ide> asyncTest('changing a select option without "data-url" attribute still fires aja <ide> ajaxLocation = settings.url.replace(settings.data, '').replace(/&$/, '').replace(/\?$/, '') <ide> equal(ajaxLocation, currentLocation, 'URL should be current page by default') <ide> <del> return false <add> e.preventDefault() <ide> }) <ide> .val('optionValue2') <ide> .triggerNative('change') <ide><path>actionview/test/ujs/public/test/override.js <ide> asyncTest('the getter for an element\'s href is overridable', 1, function() { <ide> $('#qunit-fixture a') <ide> .bindNative('ajax:beforeSend', function(e, xhr, options) { <ide> equal('/data/href', options.url) <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> start() <ide> asyncTest('the getter for an element\'s href works normally if not overridden', <ide> $('#qunit-fixture a') <ide> .bindNative('ajax:beforeSend', function(e, xhr, options) { <ide> equal(location.protocol + '//' + location.host + '/real/href', options.url) <del> return false <add> e.preventDefault() <ide> }) <ide> .triggerNative('click') <ide> start() <ide><path>actionview/test/ujs/public/test/settings.js <ide> $.fn.extend({ <ide> bindNative: function(event, handler) { <ide> if (!handler) return this <ide> <del> this.bind(event, function(e) { <add> var el = this[0] <add> el.addEventListener(event, function(e) { <ide> var args = [] <del> if (e.originalEvent.detail) { <del> args = e.originalEvent.detail.slice() <add> if (e.detail) { <add> args = e.detail.slice() <ide> } <ide> args.unshift(e) <del> return handler.apply(this, args) <del> }) <add> return handler.apply(el, args) <add> }, false) <add> <ide> return this <ide> } <ide> }) <ide><path>guides/source/working_with_javascript_in_rails.md <ide> have been bundled into `event.detail`. For information about the previously used <ide> `jquery-ujs` in Rails 5 and earlier, read the [`jquery-ujs` wiki](https://github.com/rails/jquery-ujs/wiki/ajax). <ide> <ide> ### Stoppable events <del> <del>If you stop `ajax:before` or `ajax:beforeSend` by returning false from the <del>handler method, the Ajax request will never take place. The `ajax:before` event <del>can manipulate form data before serialization and the <add>You can stop execution of the Ajax request by running `event.preventDefault()` <add>from the handlers methods `ajax:before` or `ajax:beforeSend`. <add>The `ajax:before` event can manipulate form data before serialization and the <ide> `ajax:beforeSend` event is useful for adding custom request headers. <ide> <ide> If you stop the `ajax:aborted:file` event, the default behavior of allowing the <ide> browser to submit the form via normal means (i.e. non-Ajax submission) will be <ide> canceled and the form will not be submitted at all. This is useful for <ide> implementing your own Ajax file upload workaround. <ide> <add>Note, you should use `return false` to prevent event for `jquery-ujs` and <add>`e.preventDefault()` for `rails-ujs` <add> <ide> Server-Side Concerns <ide> -------------------- <ide>
9
PHP
PHP
add tests for name
87c4af7de4baecc13b8195a9672259b33d0687b3
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php <ide> public function testParse() <ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']); <ide> $routes->connect('/', ['controller' => 'Articles']); <ide> $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']); <del> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search']); <add> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search'], ['_name' => 'media_search']); <ide> <ide> $result = $this->collection->parse('/b/'); <ide> $expected = [ <ide> public function testParse() <ide> 'controller' => 'Media', <ide> 'action' => 'search', <ide> '_matchedRoute' => '/b/media/search/*', <add> '_name' => 'media_search' <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testParse() <ide> 'controller' => 'Media', <ide> 'action' => 'search', <ide> '_matchedRoute' => '/b/media/search/*', <add> '_name' => 'media_search' <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testParseRequest() <ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']); <ide> $routes->connect('/', ['controller' => 'Articles']); <ide> $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']); <del> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search']); <add> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search'], ['_name' => 'media_search']); <ide> <ide> $request = new ServerRequest(['url' => '/b/']); <ide> $result = $this->collection->parseRequest($request); <ide> public function testParseRequest() <ide> 'controller' => 'Media', <ide> 'action' => 'search', <ide> '_matchedRoute' => '/b/media/search/*', <add> '_name' => 'media_search' <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testParseRequest() <ide> 'controller' => 'Media', <ide> 'action' => 'search', <ide> '_matchedRoute' => '/b/media/search/*', <add> '_name' => 'media_search' <ide> ]; <ide> $this->assertEquals($expected, $result); <ide>
1
Go
Go
add support for service-level 'volumes' key
0884e3c86892a0f51b8feeeb30ff486c821796f5
<ide><path>cli/command/stack/deploy.go <ide> import ( <ide> "fmt" <ide> "io/ioutil" <ide> "os" <add> "strings" <ide> "time" <ide> <ide> "github.com/spf13/cobra" <ide> import ( <ide> "github.com/aanand/compose-file/loader" <ide> composetypes "github.com/aanand/compose-file/types" <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/mount" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/cli" <ide> func getConfigFile(filename string) (*composetypes.ConfigFile, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> return loader.ParseYAML(bytes, filename) <add> config, err := loader.ParseYAML(bytes) <add> if err != nil { <add> return nil, err <add> } <add> return &composetypes.ConfigFile{ <add> Filename: filename, <add> Config: config, <add> }, nil <ide> } <ide> <ide> func createNetworks( <ide> func createNetworks( <ide> } <ide> <ide> for internalName, network := range networks { <del> if network.ExternalName != "" { <add> if network.External.Name != "" { <ide> continue <ide> } <ide> <ide> func convertNetworks( <ide> return nets <ide> } <ide> <add>func convertVolumes( <add> serviceVolumes []string, <add> stackVolumes map[string]composetypes.VolumeConfig, <add> namespace string, <add>) ([]mount.Mount, error) { <add> var mounts []mount.Mount <add> <add> for _, volumeString := range serviceVolumes { <add> var ( <add> source, target string <add> mountType mount.Type <add> readOnly bool <add> volumeOptions *mount.VolumeOptions <add> ) <add> <add> // TODO: split Windows path mappings properly <add> parts := strings.SplitN(volumeString, ":", 3) <add> <add> if len(parts) == 3 { <add> source = parts[0] <add> target = parts[1] <add> if parts[2] == "ro" { <add> readOnly = true <add> } <add> } else if len(parts) == 2 { <add> source = parts[0] <add> target = parts[1] <add> } else if len(parts) == 1 { <add> target = parts[0] <add> } <add> <add> // TODO: catch Windows paths here <add> if strings.HasPrefix(source, "/") { <add> mountType = mount.TypeBind <add> } else { <add> mountType = mount.TypeVolume <add> <add> stackVolume, exists := stackVolumes[source] <add> if !exists { <add> // TODO: better error message (include service name) <add> return nil, fmt.Errorf("Undefined volume: %s", source) <add> } <add> <add> if stackVolume.External.Name != "" { <add> source = stackVolume.External.Name <add> } else { <add> volumeOptions = &mount.VolumeOptions{ <add> Labels: stackVolume.Labels, <add> } <add> <add> if stackVolume.Driver != "" { <add> volumeOptions.DriverConfig = &mount.Driver{ <add> Name: stackVolume.Driver, <add> Options: stackVolume.DriverOpts, <add> } <add> } <add> <add> // TODO: remove this duplication <add> source = fmt.Sprintf("%s_%s", namespace, source) <add> } <add> } <add> <add> mounts = append(mounts, mount.Mount{ <add> Type: mountType, <add> Source: source, <add> Target: target, <add> ReadOnly: readOnly, <add> VolumeOptions: volumeOptions, <add> }) <add> } <add> <add> return mounts, nil <add>} <add> <ide> func deployServices( <ide> ctx context.Context, <ide> dockerCli *command.DockerCli, <ide> func convertService( <ide> return swarm.ServiceSpec{}, err <ide> } <ide> <add> mounts, err := convertVolumes(service.Volumes, volumes, namespace) <add> if err != nil { <add> return swarm.ServiceSpec{}, err <add> } <add> <ide> serviceSpec := swarm.ServiceSpec{ <ide> Annotations: swarm.Annotations{ <ide> Name: name, <ide> Labels: getStackLabels(namespace, service.Labels), <ide> }, <ide> TaskTemplate: swarm.TaskSpec{ <ide> ContainerSpec: swarm.ContainerSpec{ <del> Image: service.Image, <del> Command: service.Entrypoint, <del> Args: service.Command, <del> Env: convertEnvironment(service.Environment), <del> Labels: getStackLabels(namespace, service.Deploy.Labels), <del> Dir: service.WorkingDir, <del> User: service.User, <add> Image: service.Image, <add> Command: service.Entrypoint, <add> Args: service.Command, <add> Hostname: service.Hostname, <add> Env: convertEnvironment(service.Environment), <add> Labels: getStackLabels(namespace, service.Deploy.Labels), <add> Dir: service.WorkingDir, <add> User: service.User, <add> Mounts: mounts, <ide> }, <ide> Placement: &swarm.Placement{ <ide> Constraints: service.Deploy.Placement.Constraints,
1
Text
Text
add comparison table with new models
f740177c878778fc2f55ba33ad610b47f996a925
<ide><path>model_cards/mrm8488/bert-mini-finetuned-squadv2/README.md <ide> The script for fine tuning can be found [here](https://github.com/huggingface/tr <ide> | Model | EM | F1 score | SIZE (MB) | <ide> | ----------------------------------------------------------------------------------------- | --------- | --------- | --------- | <ide> | [bert-tiny-finetuned-squadv2](https://huggingface.co/mrm8488/bert-tiny-finetuned-squadv2) | 48.60 | 49.73 | **16.74** | <del>| [bert-mini-finetuned-squadv2](https://huggingface.co/mrm8488/bert-mini-finetuned-squadv2) | **56.31** | **59.65** | 42.63 | <add>| [bert-tiny-5-finetuned-squadv2](https://huggingface.co/mrm8488/bert-tiny-5-finetuned-squadv2) | 57.12 | 60.86 | 24.34 | <add>| [bert-mini-finetuned-squadv2](https://huggingface.co/mrm8488/bert-mini-finetuned-squadv2) | 56.31 | 59.65 | 42.63 | <add>| [bert-mini-5-finetuned-squadv2](https://huggingface.co/mrm8488/bert-mini-5-finetuned-squadv2) | **63.51** | **66.78** | 66.76 | <ide> <ide> ## Model in action <ide>
1
Python
Python
add m2m repointing
375178fc19c1170fe046ad26befeba02fc19548c
<ide><path>django/db/backends/schema.py <ide> class BaseDatabaseSchemaEditor(object): <ide> commit() is called. <ide> <ide> TODO: <del> - Repointing of M2Ms <ide> - Check constraints (PosIntField) <ide> """ <ide> <ide> def effective_default(self, field): <ide> <ide> # Actions <ide> <del> def create_model(self, model): <add> def create_model(self, model, force=False): <ide> """ <ide> Takes a model and creates a table for it in the database. <ide> Will also create any accompanying indexes or unique constraints. <ide> """ <ide> # Do nothing if this is an unmanaged or proxy model <del> if not model._meta.managed or model._meta.proxy: <add> if not force and (not model._meta.managed or model._meta.proxy): <ide> return <ide> # Create column SQL, add FK deferreds if needed <ide> column_sqls = [] <ide> def create_model(self, model): <ide> "definition": ", ".join(column_sqls) <ide> } <ide> self.execute(sql, params) <add> # Make M2M tables <add> for field in model._meta.local_many_to_many: <add> self.create_model(field.rel.through, force=True) <ide> <del> def delete_model(self, model): <add> def delete_model(self, model, force=False): <ide> """ <ide> Deletes a model from the database. <ide> """ <ide> # Do nothing if this is an unmanaged or proxy model <del> if not model._meta.managed or model._meta.proxy: <add> if not force and (not model._meta.managed or model._meta.proxy): <ide> return <ide> # Delete the table <ide> self.execute(self.sql_delete_table % { <ide> def create_field(self, model, field, keep_default=False): <ide> """ <ide> # Special-case implicit M2M tables <ide> if isinstance(field, ManyToManyField) and field.rel.through._meta.auto_created: <del> return self.create_model(field.rel.through) <add> return self.create_model(field.rel.through, force=True) <ide> # Get the column's definition <ide> definition, params = self.column_sql(model, field, include_default=True) <ide> # It might not actually have a column behind it <ide> def alter_field(self, model, old_field, new_field, strict=False): <ide> # Ensure this field is even column-based <ide> old_type = old_field.db_type(connection=self.connection) <ide> new_type = self._type_for_alter(new_field) <del> if old_type is None and new_type is None: <del> # TODO: Handle M2M fields being repointed <del> return <add> if old_type is None and new_type is None and (old_field.rel.through and new_field.rel.through and old_field.rel.through._meta.auto_created and new_field.rel.through._meta.auto_created): <add> return self._alter_many_to_many(model, old_field, new_field, strict) <ide> elif old_type is None or new_type is None: <del> raise ValueError("Cannot alter field %s into %s - they are not compatible types" % ( <add> raise ValueError("Cannot alter field %s into %s - they are not compatible types (probably means only one is an M2M with implicit through model)" % ( <ide> old_field, <ide> new_field, <ide> )) <ide> def alter_field(self, model, old_field, new_field, strict=False): <ide> } <ide> ) <ide> <add> def _alter_many_to_many(self, model, old_field, new_field, strict): <add> "Alters M2Ms to repoint their to= endpoints." <add> # Rename the through table <add> self.alter_db_table(old_field.rel.through, old_field.rel.through._meta.db_table, new_field.rel.through._meta.db_table) <add> # Repoint the FK to the other side <add> self.alter_field( <add> new_field.rel.through, <add> old_field.rel.through._meta.get_field_by_name(old_field.m2m_reverse_field_name())[0], <add> new_field.rel.through._meta.get_field_by_name(new_field.m2m_reverse_field_name())[0], <add> ) <add> <ide> def _type_for_alter(self, field): <ide> """ <ide> Returns a field's type suitable for ALTER COLUMN. <ide><path>django/db/backends/sqlite3/schema.py <ide> def alter_field(self, model, old_field, new_field, strict=False): <ide> # Ensure this field is even column-based <ide> old_type = old_field.db_type(connection=self.connection) <ide> new_type = self._type_for_alter(new_field) <del> if old_type is None and new_type is None: <del> # TODO: Handle M2M fields being repointed <del> return <add> if old_type is None and new_type is None and (old_field.rel.through and new_field.rel.through and old_field.rel.through._meta.auto_created and new_field.rel.through._meta.auto_created): <add> return self._alter_many_to_many(model, old_field, new_field, strict) <ide> elif old_type is None or new_type is None: <del> raise ValueError("Cannot alter field %s into %s - they are not compatible types" % ( <add> raise ValueError("Cannot alter field %s into %s - they are not compatible types (probably means only one is an M2M with implicit through model)" % ( <ide> old_field, <ide> new_field, <ide> )) <ide> def alter_field(self, model, old_field, new_field, strict=False): <ide> <ide> def alter_unique_together(self, model, old_unique_together, new_unique_together): <ide> self._remake_table(model, override_uniques=new_unique_together) <add> <add> def _alter_many_to_many(self, model, old_field, new_field, strict): <add> "Alters M2Ms to repoint their to= endpoints." <add> # Make a new through table <add> self.create_model(new_field.rel.through) <add> # Copy the data across <add> self.execute("INSERT INTO %s (%s) SELECT %s FROM %s;" % ( <add> self.quote_name(new_field.rel.through._meta.db_table), <add> ', '.join([ <add> "id", <add> new_field.m2m_column_name(), <add> new_field.m2m_reverse_name(), <add> ]), <add> ', '.join([ <add> "id", <add> old_field.m2m_column_name(), <add> old_field.m2m_reverse_name(), <add> ]), <add> self.quote_name(old_field.rel.through._meta.db_table), <add> )) <add> # Delete the old through table <add> self.delete_model(old_field.rel.through, force=True) <ide><path>tests/modeltests/schema/models.py <ide> class Meta: <ide> managed = False <ide> <ide> <add>class BookWithM2M(models.Model): <add> author = models.ForeignKey(Author) <add> title = models.CharField(max_length=100, db_index=True) <add> pub_date = models.DateTimeField() <add> tags = models.ManyToManyField("Tag", related_name="books") <add> <add> class Meta: <add> managed = False <add> <add> <ide> class BookWithSlug(models.Model): <ide> author = models.ForeignKey(Author) <ide> title = models.CharField(max_length=100, db_index=True) <ide><path>tests/modeltests/schema/tests.py <ide> from django.db.models.fields import IntegerField, TextField, CharField, SlugField <ide> from django.db.models.fields.related import ManyToManyField, ForeignKey <ide> from django.db.models.loading import cache <del>from .models import Author, Book, BookWithSlug, AuthorWithM2M, Tag, TagUniqueRename, UniqueTest <add>from .models import Author, Book, BookWithSlug, BookWithM2M, AuthorWithM2M, Tag, TagUniqueRename, UniqueTest <ide> <ide> <ide> class SchemaTests(TestCase): <ide> class SchemaTests(TestCase): <ide> as the code it is testing. <ide> """ <ide> <del> models = [Author, Book, BookWithSlug, AuthorWithM2M, Tag, TagUniqueRename, UniqueTest] <add> models = [Author, Book, BookWithSlug, BookWithM2M, AuthorWithM2M, Tag, TagUniqueRename, UniqueTest] <ide> <ide> # Utility functions <ide> <ide> def test_rename(self): <ide> self.assertEqual(columns['display_name'][0], "CharField") <ide> self.assertNotIn("name", columns) <ide> <add> def test_m2m_create(self): <add> """ <add> Tests M2M fields on models during creation <add> """ <add> # Create the tables <add> editor = connection.schema_editor() <add> editor.start() <add> editor.create_model(Author) <add> editor.create_model(Tag) <add> editor.create_model(BookWithM2M) <add> editor.commit() <add> # Ensure there is now an m2m table there <add> columns = self.column_classes(BookWithM2M._meta.get_field_by_name("tags")[0].rel.through) <add> self.assertEqual(columns['tag_id'][0], "IntegerField") <add> <ide> def test_m2m(self): <ide> """ <ide> Tests adding/removing M2M fields on models <ide> def test_m2m(self): <ide> self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through) <ide> connection.rollback() <ide> <add> def test_m2m_repoint(self): <add> """ <add> Tests repointing M2M fields <add> """ <add> # Create the tables <add> editor = connection.schema_editor() <add> editor.start() <add> editor.create_model(Author) <add> editor.create_model(BookWithM2M) <add> editor.create_model(Tag) <add> editor.create_model(UniqueTest) <add> editor.commit() <add> # Ensure the M2M exists and points to Tag <add> constraints = connection.introspection.get_constraints(connection.cursor(), BookWithM2M._meta.get_field_by_name("tags")[0].rel.through._meta.db_table) <add> if connection.features.supports_foreign_keys: <add> for name, details in constraints.items(): <add> if details['columns'] == set(["tag_id"]) and details['foreign_key']: <add> self.assertEqual(details['foreign_key'], ('schema_tag', 'id')) <add> break <add> else: <add> self.fail("No FK constraint for tag_id found") <add> # Repoint the M2M <add> new_field = ManyToManyField(UniqueTest) <add> new_field.contribute_to_class(BookWithM2M, "uniques") <add> editor = connection.schema_editor() <add> editor.start() <add> editor.alter_field( <add> Author, <add> BookWithM2M._meta.get_field_by_name("tags")[0], <add> new_field, <add> ) <add> editor.commit() <add> # Ensure old M2M is gone <add> self.assertRaises(DatabaseError, self.column_classes, BookWithM2M._meta.get_field_by_name("tags")[0].rel.through) <add> connection.rollback() <add> # Ensure the new M2M exists and points to UniqueTest <add> constraints = connection.introspection.get_constraints(connection.cursor(), new_field.rel.through._meta.db_table) <add> if connection.features.supports_foreign_keys: <add> for name, details in constraints.items(): <add> if details['columns'] == set(["uniquetest_id"]) and details['foreign_key']: <add> self.assertEqual(details['foreign_key'], ('schema_uniquetest', 'id')) <add> break <add> else: <add> self.fail("No FK constraint for tag_id found") <add> <ide> def test_unique(self): <ide> """ <ide> Tests removing and adding unique constraints to a single column.
4
Python
Python
fix typo in mlir bridge flag definition
69c092e92e9e050a8c49c569633af1e6e492eaaf
<ide><path>official/nlp/nhnet/trainer.py <ide> def define_flags(): <ide> # Enables MLIR-based TF/XLA bridge. This is part of a soft rollout and will <ide> # eventually be the Google-wide default. <ide> flags.DEFINE_bool("enable_mlir_bridge", True, <del> "Use MLIR TF/XLA bridge (experimental) -- NHNet.") <add> "Use MLIR TF/XLA bridge (experimental).") <ide> <ide> <ide> # pylint: disable=protected-access
1
PHP
PHP
fix alphabetical order for password rules
52e99847d0e97ab87b53182d4beb1c091896b5c0
<ide><path>lang/en/validation.php <ide> 'not_regex' => 'The :attribute format is invalid.', <ide> 'numeric' => 'The :attribute must be a number.', <ide> 'password' => [ <del> 'mixed' => 'The :attribute must contain at least one uppercase and one lowercase letter.', <ide> 'letters' => 'The :attribute must contain at least one letter.', <del> 'symbols' => 'The :attribute must contain at least one symbol.', <add> 'mixed' => 'The :attribute must contain at least one uppercase and one lowercase letter.', <ide> 'numbers' => 'The :attribute must contain at least one number.', <add> 'symbols' => 'The :attribute must contain at least one symbol.', <ide> 'uncompromised' => 'The given :attribute has appeared in a data leak. Please choose a different :attribute.', <ide> ], <ide> 'present' => 'The :attribute field must be present.',
1
PHP
PHP
add test for merged wheres in withcount
03300b0632d1839b12139022bd0a3aa6055f6ddb
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testWithCountAndMergedWheres() <ide> { <ide> $model = new EloquentBuilderTestModelParentStub; <ide> <del> $builder = $model->select('id')->withCount(['activeFoo' => function($q){ <add> $builder = $model->select('id')->withCount(['activeFoo' => function ($q) { <ide> $q->where('bam', '>', 'qux'); <ide> }]); <ide>
1
PHP
PHP
add some docs for cookies
3680ee0f1f681398713e93805745aa049ccf109b
<ide><path>lib/Cake/Network/Http/HttpSocket.php <ide> protected function _buildHeader($header, $mode = 'standard') { <ide> /** <ide> * Builds cookie headers for a request. <ide> * <add> * Cookies can either be in the format returned in responses, or <add> * a simple key => value pair. <add> * <ide> * @param array $cookies Array of cookies to send with the request. <ide> * @return string Cookie header string to be sent with the request. <ide> */
1
Text
Text
fix minor typos in governance.md
2fbe15b82c33fac4d09624b071e5f59862fa1dee
<ide><path>GOVERNANCE.md <ide> responsibility for the change. In the case of pull requests proposed <ide> by an existing Collaborator, an additional Collaborator is required <ide> for sign-off. <ide> <del>If one or more Collaborators oppose a proposed change, then the change can not <add>If one or more Collaborators oppose a proposed change, then the change cannot <ide> be accepted unless: <ide> <ide> * Discussions and/or additional changes result in no Collaborators objecting to <ide> may request that the TSC restore them to active status. <ide> <ide> ## Technical Steering Committee <ide> <del>A subset of the Collaborators form the Technical Steering Committee (TSC). <add>A subset of the Collaborators forms the Technical Steering Committee (TSC). <ide> The TSC has final authority over this project, including: <ide> <ide> * Technical direction
1
Python
Python
make the split of batch outside gpus (#51)
57f839bf283b87fc33e30bbeea182c78b147357f
<ide><path>inception/inception/inception_train.py <ide> def train(dataset): <ide> # Number of classes in the Dataset label set plus 1. <ide> # Label 0 is reserved for an (unused) background class. <ide> num_classes = dataset.num_classes() + 1 <add> <add> # Split the batch of images and labels for towers. <add> images_splits = tf.split(0, FLAGS.num_gpus, images) <add> labels_splits = tf.split(0, FLAGS.num_gpus, labels) <ide> <ide> # Calculate the gradients for each model tower. <ide> tower_grads = [] <ide> for i in xrange(FLAGS.num_gpus): <ide> with tf.device('/gpu:%d' % i): <ide> with tf.name_scope('%s_%d' % (inception.TOWER_NAME, i)) as scope: <del> # Split the batch of images and labels. <del> batch_start = split_batch_size * i <del> images_batch = tf.slice(images, <del> begin=[batch_start, 0, 0, 0], <del> size=[split_batch_size, -1, -1, -1]) <del> labels_batch = tf.slice(labels, <del> begin=[batch_start], <del> size=[split_batch_size]) <del> <del> <ide> # Force all Variables to reside on the CPU. <ide> with slim.arg_scope([slim.variables.variable], device='/cpu:0'): <ide> # Calculate the loss for one tower of the ImageNet model. This <ide> # function constructs the entire ImageNet model but shares the <ide> # variables across all towers. <del> loss = _tower_loss(images_batch, labels_batch, num_classes, scope) <add> loss = _tower_loss(images_splits[i], labels_splits[i], num_classes, <add> scope) <ide> <ide> # Reuse variables for the next tower. <ide> tf.get_variable_scope().reuse_variables()
1
PHP
PHP
fix another fqn
2c9f2fce78c30e22c4607e1ce75135acaa549d9e
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Event\EventInterface; <add>use Cake\Http\Response; <add>use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Exception\XmlException; <ide> use Cake\Utility\Inflector; <ide> public function implementedEvents(): array <ide> * @param \Cake\Http\Response $response The response instance. <ide> * @return void <ide> */ <del> protected function _setExtension(\Cake\Http\ServerRequest $request, \Cake\Http\Response $response): void <add> protected function _setExtension(ServerRequest $request, Response $response): void <ide> { <ide> $accept = $request->parseAccept(); <ide> if (empty($accept) || current($accept)[0] === 'text/html') {
1
Javascript
Javascript
fix hot loader compatibility with java8 nashorn
ebe2f371c1a9ed303dd30f0c1ee51cd51718e4bd
<ide><path>lib/JsonpMainTemplate.runtime.js <ide> module.exports = function() { <ide> function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars <ide> hotAddUpdateChunk(chunkId, moreModules); <ide> if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); <del> } <add> } //$semicolon <ide> <ide> function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars <ide> var head = document.getElementsByTagName("head")[0]; <ide><path>lib/JsonpMainTemplatePlugin.js <ide> JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) { <ide> return source + "\n" + <ide> "var parentHotUpdateCallback = this[" + JSON.stringify(hotUpdateFunction) + "];\n" + <ide> "this[" + JSON.stringify(hotUpdateFunction) + "] = " + Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js")) <add> .replace(/\/\/\$semicolon/g, ";") <ide> .replace(/\$require\$/g, this.requireFn) <ide> .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) <ide> .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) <ide><path>lib/webworker/WebWorkerMainTemplate.runtime.js <ide> module.exports = function() { <ide> function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars <ide> hotAddUpdateChunk(chunkId, moreModules); <ide> if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); <del> } <add> } //$semicolon <ide> <ide> function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars <ide> importScripts($require$.p + $hotChunkFilename$); <ide><path>lib/webworker/WebWorkerMainTemplatePlugin.js <ide> WebWorkerMainTemplatePlugin.prototype.apply = function(mainTemplate) { <ide> return source + "\n" + <ide> "var parentHotUpdateCallback = this[" + JSON.stringify(hotUpdateFunction) + "];\n" + <ide> "this[" + JSON.stringify(hotUpdateFunction) + "] = " + Template.getFunctionContent(require("./WebWorkerMainTemplate.runtime.js")) <add> .replace(/\/\/\$semicolon/g, ";") <ide> .replace(/\$require\$/g, this.requireFn) <ide> .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) <ide> .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
4
Text
Text
add notes to contributing docs
e6f6bb5c7e3e882b0215c981e2f2b6a576820100
<ide><path>docs/topics/contributing.md <ide> If you want to draw attention to a note or warning, use a pair of enclosing line <ide> <ide> --- <ide> <add>## Third party packages <add> <add>New features to REST framework are generally recommended to be implemented as third party libraries that are developed outside of the core framework. Ideally third party libraries should be properly documented and packaged, and made available on PyPI. <add> <add>If you have some functionality that you would like to implement as a third party package it's worth contacting the [discussion group][google-group] as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging. <add> <add>Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main documentation. <add> <add>We recommend the [`django-reusable-app`][django-reusable-app] template as a good resource for getting up and running with implementing a third party Django package. <add> <ide> [cite]: http://www.w3.org/People/Berners-Lee/FAQ.html <ide> [code-of-conduct]: https://www.djangoproject.com/conduct/ <ide> [google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework <ide> If you want to draw attention to a note or warning, use a pair of enclosing line <ide> [markdown]: http://daringfireball.net/projects/markdown/basics <ide> [docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs <ide> [mou]: http://mouapp.com/ <add>[django-reusable-app]: https://github.com/dabapps/django-reusable-app
1
PHP
PHP
remove classes from aliases list
2ddf39f29ff1d82e69914318868884af7b24f8ef
<ide><path>config/app.php <ide> <ide> 'aliases' => [ <ide> <del> 'App' => 'Illuminate\Support\Facades\App', <del> 'Artisan' => 'Illuminate\Support\Facades\Artisan', <del> 'Auth' => 'Illuminate\Support\Facades\Auth', <del> 'Blade' => 'Illuminate\Support\Facades\Blade', <del> 'Cache' => 'Illuminate\Support\Facades\Cache', <del> 'Config' => 'Illuminate\Support\Facades\Config', <del> 'Cookie' => 'Illuminate\Support\Facades\Cookie', <del> 'Crypt' => 'Illuminate\Support\Facades\Crypt', <del> 'DB' => 'Illuminate\Support\Facades\DB', <del> 'Eloquent' => 'Illuminate\Database\Eloquent\Model', <del> 'Event' => 'Illuminate\Support\Facades\Event', <del> 'File' => 'Illuminate\Support\Facades\File', <del> 'FormRequest' => 'Illuminate\Foundation\Http\FormRequest', <del> 'Hash' => 'Illuminate\Support\Facades\Hash', <del> 'Input' => 'Illuminate\Support\Facades\Input', <del> 'Lang' => 'Illuminate\Support\Facades\Lang', <del> 'Log' => 'Illuminate\Support\Facades\Log', <del> 'Mail' => 'Illuminate\Support\Facades\Mail', <del> 'Paginator' => 'Illuminate\Support\Facades\Paginator', <del> 'Password' => 'Illuminate\Support\Facades\Password', <del> 'Queue' => 'Illuminate\Support\Facades\Queue', <del> 'Redirect' => 'Illuminate\Support\Facades\Redirect', <del> 'Redis' => 'Illuminate\Support\Facades\Redis', <del> 'Request' => 'Illuminate\Support\Facades\Request', <del> 'Response' => 'Illuminate\Support\Facades\Response', <del> 'Route' => 'Illuminate\Support\Facades\Route', <del> 'Schema' => 'Illuminate\Support\Facades\Schema', <del> 'Seeder' => 'Illuminate\Database\Seeder', <del> 'Session' => 'Illuminate\Support\Facades\Session', <del> 'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait', <del> 'Str' => 'Illuminate\Support\Str', <del> 'URL' => 'Illuminate\Support\Facades\URL', <del> 'Validator' => 'Illuminate\Support\Facades\Validator', <del> 'View' => 'Illuminate\Support\Facades\View', <add> 'App' => 'Illuminate\Support\Facades\App', <add> 'Artisan' => 'Illuminate\Support\Facades\Artisan', <add> 'Auth' => 'Illuminate\Support\Facades\Auth', <add> 'Blade' => 'Illuminate\Support\Facades\Blade', <add> 'Cache' => 'Illuminate\Support\Facades\Cache', <add> 'Config' => 'Illuminate\Support\Facades\Config', <add> 'Cookie' => 'Illuminate\Support\Facades\Cookie', <add> 'Crypt' => 'Illuminate\Support\Facades\Crypt', <add> 'DB' => 'Illuminate\Support\Facades\DB', <add> 'Event' => 'Illuminate\Support\Facades\Event', <add> 'File' => 'Illuminate\Support\Facades\File', <add> 'Hash' => 'Illuminate\Support\Facades\Hash', <add> 'Input' => 'Illuminate\Support\Facades\Input', <add> 'Lang' => 'Illuminate\Support\Facades\Lang', <add> 'Log' => 'Illuminate\Support\Facades\Log', <add> 'Mail' => 'Illuminate\Support\Facades\Mail', <add> 'Paginator' => 'Illuminate\Support\Facades\Paginator', <add> 'Password' => 'Illuminate\Support\Facades\Password', <add> 'Queue' => 'Illuminate\Support\Facades\Queue', <add> 'Redirect' => 'Illuminate\Support\Facades\Redirect', <add> 'Redis' => 'Illuminate\Support\Facades\Redis', <add> 'Request' => 'Illuminate\Support\Facades\Request', <add> 'Response' => 'Illuminate\Support\Facades\Response', <add> 'Route' => 'Illuminate\Support\Facades\Route', <add> 'Schema' => 'Illuminate\Support\Facades\Schema', <add> 'Session' => 'Illuminate\Support\Facades\Session', <add> 'URL' => 'Illuminate\Support\Facades\URL', <add> 'Validator' => 'Illuminate\Support\Facades\Validator', <add> 'View' => 'Illuminate\Support\Facades\View', <ide> <ide> ], <ide> <ide><path>database/seeds/DatabaseSeeder.php <ide> <?php <ide> <add>use Illuminate\Database\Seeder; <add> <ide> class DatabaseSeeder extends Seeder { <ide> <ide> /**
2
Ruby
Ruby
build rubygem beta version string correctly
e26da953400f698b0401ec47b6b90ee9f01d808b
<ide><path>lib/ember/version.rb <ide> module Ember <ide> # we might want to unify this with the ember version string, <ide> # but consistency? <ide> def rubygems_version_string <del> if VERSION =~ /rc/ <del> major, rc = VERSION.sub('-','.').scan(/(\d+\.\d+\.\d+\.rc)\.(\d+)/).first <add> if VERSION =~ /rc|beta/ <add> major, rc = VERSION.sub('-','.').scan(/(\d+\.\d+\.\d+\.(rc|beta))\.(\d+)/).first <ide> <ide> "#{major}#{rc}" <ide> else
1
Go
Go
fix lint issues
729d45379fedc4b8cfe692260ef520bbdcc8e3b6
<ide><path>libnetwork/cmd/dnet/dnet.go <ide> func startTestDriver() error { <ide> return err <ide> } <ide> <del> if err := ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644); err != nil { <del> return err <del> } <del> <del> return nil <add> return ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644) <ide> } <ide> <ide> func newDnetConnection(val string) (*dnetConnection, error) { <ide><path>libnetwork/drivers/bridge/bridge.go <ide> func (d *driver) createNetwork(config *networkConfiguration) error { <ide> <ide> // Apply the prepared list of steps, and abort at the first error. <ide> bridgeSetup.queueStep(setupDeviceUp) <del> if err = bridgeSetup.apply(); err != nil { <del> return err <del> } <del> <del> return nil <add> return bridgeSetup.apply() <ide> } <ide> <ide> func (d *driver) DeleteNetwork(nid string) error { <ide><path>libnetwork/drivers/bridge/setup_ip_tables.go <ide> func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairp <ide> } <ide> <ide> // Set Accept on all non-intercontainer outgoing packets. <del> if err := programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable); err != nil { <del> return err <del> } <del> <del> return nil <add> return programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable) <ide> } <ide> <ide> func programChainRule(rule iptRule, ruleDescr string, insert bool) error { <ide> func setupInternalNetworkRules(bridgeIface string, addr net.Addr, icc, insert bo <ide> return err <ide> } <ide> // Set Inter Container Communication. <del> if err := setIcc(bridgeIface, icc, insert); err != nil { <del> return err <del> } <del> return nil <add> return setIcc(bridgeIface, icc, insert) <ide> } <ide> <ide> func clearEndpointConnections(nlh *netlink.Handle, ep *bridgeEndpoint) { <ide><path>libnetwork/drivers/overlay/ov_endpoint.go <ide> func (d *driver) deleteEndpointFromStore(e *endpoint) error { <ide> return fmt.Errorf("overlay local store not initialized, ep not deleted") <ide> } <ide> <del> if err := d.localStore.DeleteObjectAtomic(e); err != nil { <del> return err <del> } <del> <del> return nil <add> return d.localStore.DeleteObjectAtomic(e) <ide> } <ide> <ide> func (d *driver) writeEndpointToStore(e *endpoint) error { <ide> if d.localStore == nil { <ide> return fmt.Errorf("overlay local store not initialized, ep not added") <ide> } <ide> <del> if err := d.localStore.PutObjectAtomic(e); err != nil { <del> return err <del> } <del> return nil <add> return d.localStore.PutObjectAtomic(e) <ide> } <ide> <ide> func (ep *endpoint) DataScope() string { <ide><path>libnetwork/drivers/solaris/overlay/ov_endpoint.go <ide> func (d *driver) deleteEndpointFromStore(e *endpoint) error { <ide> return fmt.Errorf("overlay local store not initialized, ep not deleted") <ide> } <ide> <del> if err := d.localStore.DeleteObjectAtomic(e); err != nil { <del> return err <del> } <del> <del> return nil <add> return d.localStore.DeleteObjectAtomic(e) <ide> } <ide> <ide> func (d *driver) writeEndpointToStore(e *endpoint) error { <ide> if d.localStore == nil { <ide> return fmt.Errorf("overlay local store not initialized, ep not added") <ide> } <ide> <del> if err := d.localStore.PutObjectAtomic(e); err != nil { <del> return err <del> } <del> return nil <add> return d.localStore.PutObjectAtomic(e) <ide> } <ide> <ide> func (ep *endpoint) DataScope() string { <ide><path>libnetwork/endpoint_info.go <ide> func (ep *endpoint) Info() EndpointInfo { <ide> return ep <ide> } <ide> <del> if epi := sb.getEndpoint(ep.ID()); epi != nil { <del> return epi <del> } <del> <del> return nil <add> return sb.getEndpoint(ep.ID()) <ide> } <ide> <ide> func (ep *endpoint) Iface() InterfaceInfo { <ide><path>libnetwork/iptables/iptables.go <ide> func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr <ide> "--dport", strconv.Itoa(destPort), <ide> "-j", "MASQUERADE", <ide> } <del> if err := ProgramRule(Nat, "POSTROUTING", action, args); err != nil { <del> return err <del> } <del> <del> return nil <add> return ProgramRule(Nat, "POSTROUTING", action, args) <ide> } <ide> <ide> // Link adds reciprocal ACCEPT rule for two supplied IP addresses. <ide> func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, <ide> // reverse <ide> args[7], args[9] = args[9], args[7] <ide> args[10] = "--sport" <del> if err := ProgramRule(Filter, c.Name, action, args); err != nil { <del> return err <del> } <del> return nil <add> return ProgramRule(Filter, c.Name, action, args) <ide> } <ide> <ide> // ProgramRule adds the rule specified by args only if the <ide><path>libnetwork/sandbox_dns_unix.go <ide> func (sb *sandbox) setupResolutionFiles() error { <ide> return err <ide> } <ide> <del> if err := sb.setupDNS(); err != nil { <del> return err <del> } <del> <del> return nil <add> return sb.setupDNS() <ide> } <ide> <ide> func (sb *sandbox) buildHostsFile() error {
8
Python
Python
fix closing connection dbapi.get_pandas_df
ab1f637e463011a34d950c306583400b7a2fceb3
<ide><path>airflow/hooks/dbapi.py <ide> def get_pandas_df(self, sql, parameters=None, **kwargs): <ide> with closing(self.get_conn()) as conn: <ide> return psql.read_sql(sql, con=conn, params=parameters, **kwargs) <ide> <add> def get_pandas_df_by_chunks(self, sql, parameters=None, *, chunksize, **kwargs): <add> """ <add> Executes the sql and returns a generator <add> <add> :param sql: the sql statement to be executed (str) or a list of <add> sql statements to execute <add> :param parameters: The parameters to render the SQL query with <add> :param chunksize: number of rows to include in each chunk <add> :param kwargs: (optional) passed into pandas.io.sql.read_sql method <add> """ <add> try: <add> from pandas.io import sql as psql <add> except ImportError: <add> raise Exception("pandas library not installed, run: pip install 'apache-airflow[pandas]'.") <add> <add> with closing(self.get_conn()) as conn: <add> yield from psql.read_sql(sql, con=conn, params=parameters, chunksize=chunksize, **kwargs) <add> <ide> def get_records(self, sql, parameters=None): <ide> """ <ide> Executes the sql and returns a set of records.
1
PHP
PHP
add ability to easily queue an artisan command
fa33e07b91b33da934d581874c0e8ae919d12be7
<ide><path>src/Illuminate/Contracts/Console/Kernel.php <ide> public function handle($input, $output = null); <ide> */ <ide> public function call($command, array $parameters = array()); <ide> <add> /** <add> * Queue an Artisan console command by name. <add> * <add> * @param string $command <add> * @param array $parameters <add> * @return int <add> */ <add> public function queue($command, array $parameters = array()); <add> <ide> /** <ide> * Get all of the commands registered with the console. <ide> * <ide><path>src/Illuminate/Foundation/Console/Kernel.php <ide> public function call($command, array $parameters = array()) <ide> return $this->getArtisan()->call($command, $parameters); <ide> } <ide> <add> /** <add> * Queue the given console command. <add> * <add> * @param string $command <add> * @param array $parameters <add> * @return void <add> */ <add> public function queue($command, array $parameters = array()) <add> { <add> $this->app['Illuminate\Contracts\Queue\Queue']->push( <add> 'Illuminate\Foundation\Console\QueuedJob', func_get_args() <add> ); <add> } <add> <ide> /** <ide> * Get all of the commands registered with the console. <ide> * <ide><path>src/Illuminate/Foundation/Console/QueuedJob.php <add><?php namespace Illuminate\Foundation\Console; <add> <add>use Illuminate\Contracts\Console\Kernel; <add> <add>class QueuedJob { <add> <add> /** <add> * The kernel instance. <add> * <add> * @var \Illuminate\Contracts\Console\Kernel <add> */ <add> protected $kernel; <add> <add> /** <add> * Create a new job instance. <add> * <add> * @param \Illuminate\Contracts\Console\Kernel $kernel <add> * @return void <add> */ <add> public function __construct(Kernel $kernel) <add> { <add> $this->kernel = $kernel; <add> } <add> <add> /** <add> * Fire the job. <add> * <add> * @param \Illuminate\Queue\Jobs\Job <add> * @param array $data <add> * @return void <add> */ <add> public function fire($job, $data) <add> { <add> $status = call_user_func_array([$this->kernel, 'call'], $data); <add> <add> $job->delete(); <add> } <add> <add>}
3
Ruby
Ruby
define opt_pkgshare helper method
68a13b240f765b9976dc45bfe97633534544e657
<ide><path>Library/Homebrew/formula.rb <ide> def opt_lib; opt_prefix+'lib' end <ide> def opt_libexec; opt_prefix+'libexec' end <ide> def opt_sbin; opt_prefix+'sbin' end <ide> def opt_share; opt_prefix+'share' end <add> def opt_pkgshare; opt_prefix+'share'+name end <ide> def opt_frameworks; opt_prefix+'Frameworks' end <ide> <ide> # Can be overridden to selectively disable bottles from formulae.
1
Javascript
Javascript
amend glyphmapforstandardfonts to fix issue 4276
0fa154be4e765e7e583bf4c6689482944925a8f5
<ide><path>src/core/fonts.js <ide> var symbolsFonts = { <ide> // glyphs, but common for some set of the standard fonts. <ide> var GlyphMapForStandardFonts = { <ide> '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38, <del> '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 173, <add> '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45, <ide> '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52, <ide> '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894, <ide> '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66, <ide> var GlyphMapForStandardFonts = { <ide> '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719, <ide> '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248, <ide> '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776, <del> '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '305': 963, <add> '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711, <add> '227': 353, '229': 382, '234': 253, '253': 268, '254': 269, '258': 258, <add> '268': 283, '269': 313, '278': 328, '284': 345, '292': 367, '305': 963, <ide> '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359, <ide> '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524, <ide> '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
1
PHP
PHP
fix postgres grammar for nested json arrays
53f3a817ea90964688948ed144e8bdb686a3662f
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> protected function wrapJsonBooleanValue($value) <ide> protected function wrapJsonPathAttributes($path) <ide> { <ide> return array_map(function ($attribute) { <add> if (\strval(\intval($attribute)) === $attribute) { <add> return $attribute; <add> } <add> <ide> return "'$attribute'"; <ide> }, $path); <ide> } <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testPostgresWrappingJson() <ide> $builder->select('*')->from('users')->where('items->price->in_usd', '=', 1)->where('items->age', '=', 2); <ide> $this->assertSame('select * from "users" where "items"->\'price\'->>\'in_usd\' = ? and "items"->>\'age\' = ?', $builder->toSql()); <ide> <add> $builder = $this->getPostgresBuilder(); <add> $builder->select('*')->from('users')->where('items->prices->0', '=', 1)->where('items->age', '=', 2); <add> $this->assertSame('select * from "users" where "items"->\'prices\'->>0 = ? and "items"->>\'age\' = ?', $builder->toSql()); <add> <ide> $builder = $this->getPostgresBuilder(); <ide> $builder->select('*')->from('users')->where('items->available', '=', true); <ide> $this->assertSame('select * from "users" where ("items"->\'available\')::jsonb = \'true\'::jsonb', $builder->toSql());
2
Python
Python
pin moto to <2
802159767baf1768d92c6047c2fdb2094ee7a2a8
<ide><path>setup.py <ide> def get_sphinx_theme_version() -> str: <ide> # See: https://github.com/spulec/moto/issues/3535 <ide> 'mock<4.0.3', <ide> 'mongomock', <del> 'moto', <add> 'moto<2', <ide> 'mypy==0.770', <ide> 'parameterized', <ide> 'paramiko',
1
Go
Go
add env variable to disable kernel version warning
e4aba11e80561d06e457453c58def970518b691c
<ide><path>engine/engine.go <ide> func New(root string) (*Engine, error) { <ide> log.Printf("WARNING: %s\n", err) <ide> } else { <ide> if utils.CompareKernelVersion(k, &utils.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 { <del> log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String()) <add> if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" { <add> log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String()) <add> } <ide> } <ide> } <ide> if err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {
1
PHP
PHP
fix errors on invalid cookies
4ee742dc4af84f4ebc9e4f93032a2c603d6e8188
<ide><path>src/Http/Cookie/CookieCollection.php <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> use Traversable; <add>use TypeError; <ide> <ide> /** <ide> * Cookie Collection <ide> public static function createFromHeader(array $header, array $defaults = []) <ide> foreach ($header as $value) { <ide> try { <ide> $cookies[] = Cookie::createFromHeaderString($value, $defaults); <del> } catch (Exception $e) { <add> } catch (Exception | TypeError $e) { <ide> // Don't blow up on invalid cookies <ide> } <ide> } <ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php <ide> public function testCreateFromHeader(): void <ide> 'http=name; HttpOnly; Secure;', <ide> 'expires=expiring; Expires=Wed, 15-Jun-2022 10:22:22; Path=/api; HttpOnly; Secure;', <ide> 'expired=expired; version=1; Expires=Wed, 15-Jun-2015 10:22:22;', <add> 'invalid=invalid-secure; Expires=Tue, 17 May 2022 22:19:06 GMT; Secure=true; SameSite=none', <ide> ]; <ide> $cookies = CookieCollection::createFromHeader($header); <ide> $this->assertCount(3, $cookies); <ide> $this->assertTrue($cookies->has('http')); <ide> $this->assertTrue($cookies->has('expires')); <ide> $this->assertFalse($cookies->has('version')); <ide> $this->assertTrue($cookies->has('expired'), 'Expired cookies should be present'); <add> $this->assertFalse($cookies->has('invalid'), 'Invalid cookies should not be present'); <ide> } <ide> <ide> /**
2
Ruby
Ruby
use comma consistently
c7c9919d3aaba19ea8974549d582bba189e0b2a1
<ide><path>Library/Homebrew/compilers.rb <ide> module CompilerConstants <ide> "gcc-4.0" => :gcc_4_0, <ide> "gcc-4.2" => :gcc, <ide> "llvm-gcc" => :llvm, <del> "clang" => :clang <add> "clang" => :clang, <ide> } <ide> <ide> COMPILERS = COMPILER_SYMBOL_MAP.values + <ide> def inspect <ide> create(:gcc => "4.3"), <ide> create(:gcc => "4.4"), <ide> create(:gcc => "4.5"), <del> create(:gcc => "4.6") <add> create(:gcc => "4.6"), <ide> ], <ide> :openmp => [ <ide> create(:clang), <del> create(:llvm) <del> ] <add> create(:llvm), <add> ], <ide> } <ide> end <ide> <ide> class CompilerSelector <ide> :clang => [:clang, :gcc, :llvm, :gnu, :gcc_4_0], <ide> :gcc => [:gcc, :llvm, :gnu, :clang, :gcc_4_0], <ide> :llvm => [:llvm, :gcc, :gnu, :clang, :gcc_4_0], <del> :gcc_4_0 => [:gcc_4_0, :gcc, :llvm, :gnu, :clang] <add> :gcc_4_0 => [:gcc_4_0, :gcc, :llvm, :gnu, :clang], <ide> } <ide> <ide> def self.select_for(formula, compilers = self.compilers)
1
Javascript
Javascript
remove duplicate word
e1fb8e64b5d2b783a0647d4b1c4d04f063a9e052
<ide><path>Libraries/StyleSheet/StyleSheet.js <ide> var StyleSheetValidation = require('StyleSheetValidation'); <ide> * Code quality: <ide> * <ide> * - By moving styles away from the render function, you're making the code <del> * code easier to understand. <add> * easier to understand. <ide> * - Naming the styles is a good way to add meaning to the low level components <ide> * in the render function. <ide> *
1
PHP
PHP
improve support for http/2 in http\client
28ed0d3d6d8ba797dc5a5afc7fbf530a8afbb278
<ide><path>src/Http/Client.php <ide> class Client <ide> 'ssl_verify_depth' => 5, <ide> 'ssl_verify_host' => true, <ide> 'redirect' => false, <add> 'protocolVersion' => '1.1', <ide> ]; <ide> <ide> /** <ide> class Client <ide> * - adapter - The adapter class name or instance. Defaults to <ide> * \Cake\Http\Client\Adapter\Curl if `curl` extension is loaded else <ide> * \Cake\Http\Client\Adapter\Stream. <add> * - protocolVersion - The HTTP protocol version to use. Defaults to 1.1 <ide> * <ide> * @param array $config Config options for scoped clients. <ide> * @throws \InvalidArgumentException <ide> protected function _createRequest($method, $url, $data, $options) <ide> } <ide> <ide> $request = new Request($url, $method, $headers, $data); <add> $request = $request->withProtocolVersion($this->getConfig('protocolVersion')); <add> <ide> $cookies = isset($options['cookies']) ? $options['cookies'] : []; <ide> /** @var \Cake\Http\Client\Request $request */ <ide> $request = $this->_cookies->addToRequest($request, $cookies); <ide><path>src/Http/Client/Adapter/Curl.php <ide> protected function getProtocolVersion(Request $request) <ide> return CURL_HTTP_VERSION_1_0; <ide> case '1.1': <ide> return CURL_HTTP_VERSION_1_1; <add> case '2': <ide> case '2.0': <add> if (defined('CURL_HTTP_VERSION_2TLS')) { <add> return CURL_HTTP_VERSION_2TLS; <add> } <ide> if (defined('CURL_HTTP_VERSION_2_0')) { <ide> return CURL_HTTP_VERSION_2_0; <ide> } <del> throw new HttpException('libcurl 7.33 needed for HTTP 2.0 support'); <add> throw new HttpException('libcurl 7.33 or greater required for HTTP/2 support'); <ide> } <ide> <ide> return CURL_HTTP_VERSION_NONE; <ide><path>tests/TestCase/Http/Client/Adapter/CurlTest.php <ide> public function testBuildOptionsCurlOptions() <ide> ]; <ide> $this->assertSame($expected, $result); <ide> } <add> <add> /** <add> * Test converting client options into curl ones. <add> * <add> * @return void <add> */ <add> public function testBuildOptionsProtocolVersion() <add> { <add> $this->skipIf(!defined('CURL_HTTP_VERSION_2TLS'), 'Requires libcurl 7.42'); <add> $options = []; <add> $request = new Request('http://localhost/things', 'GET'); <add> $request = $request->withProtocolVersion('2'); <add> <add> $result = $this->curl->buildOptions($request, $options); <add> $this->assertSame(CURL_HTTP_VERSION_2TLS, $result[CURLOPT_HTTP_VERSION]); <add> } <ide> } <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testConstructConfig() <ide> 'scheme' => 'http', <ide> 'host' => 'example.org', <ide> 'auth' => ['username' => 'mark', 'password' => 'secret'], <add> 'protocolVersion' => '1.1', <ide> ]; <ide> foreach ($expected as $key => $val) { <ide> $this->assertEquals($val, $result[$key]); <ide> public function testGetSimpleWithHeadersAndCookies() <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> ->method('send') <del> ->with($this->callback(function ($request) use ($cookies, $headers) { <add> ->with($this->callback(function ($request) use ($headers) { <ide> $this->assertInstanceOf('Cake\Http\Client\Request', $request); <ide> $this->assertEquals(Request::METHOD_GET, $request->getMethod()); <add> $this->assertSame('2', $request->getProtocolVersion()); <ide> $this->assertEquals('http://cakephp.org/test.html', $request->getUri() . ''); <ide> $this->assertEquals('split=value', $request->getHeaderLine('Cookie')); <ide> $this->assertEquals($headers['Content-Type'], $request->getHeaderLine('content-type')); <ide> public function testGetSimpleWithHeadersAndCookies() <ide> })) <ide> ->will($this->returnValue([$response])); <ide> <del> $http = new Client(['adapter' => $mock]); <add> $http = new Client(['adapter' => $mock, 'protocolVersion' => '2']); <ide> $result = $http->get('http://cakephp.org/test.html', [], [ <ide> 'headers' => $headers, <ide> 'cookies' => $cookies,
4
Javascript
Javascript
add test coverage
358b7a4458859f768921a31dd3dfe85947d9abeb
<ide><path>scripts/__tests__/hermes-utils-test.js <del>/** <del> * Copyright (c) Meta Platforms, Inc. and affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> */ <del> <del>import * as path from 'path'; <del> <del>const { <del> configureMakeForPrebuiltHermesC, <del> copyBuildScripts, <del> copyPodSpec, <del> downloadHermesSourceTarball, <del> expandHermesSourceTarball, <del> getHermesPrebuiltArtifactsTarballName, <del> getHermesTagSHA, <del> readHermesTag, <del> setHermesTag, <del> shouldUsePrebuiltHermesC, <del>} = require('../hermes/hermes-utils'); <del> <del>const hermesTag = <del> 'hermes-2022-04-28-RNv0.69.0-15d07c2edd29a4ea0b8f15ab0588a0c1adb1200f'; <del>const tarballContents = 'dummy string'; <del>const hermescContents = 'dummy string'; <del>const hermesTagSha = '5244f819b2f3949ca94a3a1bf75d54a8ed59d94a'; <del> <del>const ROOT_DIR = path.normalize(path.join(__dirname, '..', '..')); <del>const SDKS_DIR = path.join(ROOT_DIR, 'sdks'); <del> <del>const MemoryFs = require('metro-memory-fs'); <del> <del>let execCalls; <del>let fs; <del> <del>jest.mock('child_process', () => ({ <del> execSync: jest.fn(command => { <del> if (command.startsWith('curl')) { <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <del> tarballContents, <del> ); <del> execCalls.curl = true; <del> return {code: 0}; <del> } <del> <del> if (command.startsWith('git')) { <del> execCalls.git = true; <del> return hermesTagSha + '\n'; <del> } <del> <del> if (command.startsWith('tar')) { <del> fs.mkdirSync(path.join(SDKS_DIR, 'hermes', 'utils'), { <del> recursive: true, <del> }); <del> fs.writeFileSync(path.join(SDKS_DIR, 'hermes', `package.json`), '{}'); <del> execCalls.tar = true; <del> return {code: 0}; <del> } <del> }), <del>})); <del> <del>function populateMockFilesystem() { <del> fs.mkdirSync(path.join(SDKS_DIR, 'hermes-engine', 'utils'), { <del> recursive: true, <del> }); <del> fs.writeFileSync( <del> path.join( <del> ROOT_DIR, <del> 'sdks', <del> 'hermes-engine', <del> 'utils', <del> 'build-apple-framework.sh', <del> ), <del> 'Dummy file', <del> ); <del> fs.writeFileSync( <del> path.join( <del> ROOT_DIR, <del> 'sdks', <del> 'hermes-engine', <del> 'utils', <del> 'build-ios-framework.sh', <del> ), <del> 'Dummy file', <del> ); <del> fs.writeFileSync( <del> path.join( <del> ROOT_DIR, <del> 'sdks', <del> 'hermes-engine', <del> 'utils', <del> 'build-mac-framework.sh', <del> ), <del> 'Dummy file', <del> ); <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'hermes-engine', 'hermes-engine.podspec'), <del> 'Dummy file', <del> ); <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'hermes-engine', 'hermes-utils.rb'), <del> 'Dummy file', <del> ); <del>} <del> <del>describe('hermes-utils', () => { <del> beforeEach(() => { <del> jest.resetModules(); <del> <del> jest.mock( <del> 'fs', <del> () => <del> new MemoryFs({ <del> platform: process.platform === 'win32' ? 'win32' : 'posix', <del> }), <del> ); <del> fs = require('fs'); <del> fs.reset(); <del> <del> populateMockFilesystem(); <del> <del> execCalls = Object.create(null); <del> }); <del> describe('readHermesTag', () => { <del> it('should return main if .hermesversion does not exist', () => { <del> expect(readHermesTag()).toEqual('main'); <del> }); <del> it('should fail if hermes tag is empty', () => { <del> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), ''); <del> expect(() => { <del> readHermesTag(); <del> }).toThrow('[Hermes] .hermesversion file is empty.'); <del> }); <del> it('should return tag from .hermesversion if file exists', () => { <del> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); <del> expect(readHermesTag()).toEqual(hermesTag); <del> }); <del> }); <del> describe('setHermesTag', () => { <del> it('should write tag to .hermesversion file', () => { <del> setHermesTag(hermesTag); <del> expect( <del> fs.readFileSync(path.join(SDKS_DIR, '.hermesversion'), { <del> encoding: 'utf8', <del> flag: 'r', <del> }), <del> ).toEqual(hermesTag); <del> }); <del> it('should set Hermes tag and read it back', () => { <del> setHermesTag(hermesTag); <del> expect(readHermesTag()).toEqual(hermesTag); <del> }); <del> }); <del> describe('getHermesPrebuiltArtifactsTarballName', () => { <del> it('should return Hermes tarball name', () => { <del> expect( <del> getHermesPrebuiltArtifactsTarballName('Debug', '1000.0.0'), <del> ).toEqual('hermes-runtime-darwin-debug-v1000.0.0.tar.gz'); <del> }); <del> it('should throw if build type is undefined', () => { <del> expect(() => { <del> getHermesPrebuiltArtifactsTarballName(); <del> }).toThrow('Did not specify build type.'); <del> }); <del> it('should throw if release version is undefined', () => { <del> expect(() => { <del> getHermesPrebuiltArtifactsTarballName('Release'); <del> }).toThrow('Did not specify release version.'); <del> }); <del> it('should return debug Hermes tarball name for RN 0.70.0', () => { <del> expect(getHermesPrebuiltArtifactsTarballName('Debug', '0.70.0')).toEqual( <del> 'hermes-runtime-darwin-debug-v0.70.0.tar.gz', <del> ); <del> }); <del> it('should return a wildcard Hermes tarball name for any RN version', () => { <del> expect(getHermesPrebuiltArtifactsTarballName('Debug', '*')).toEqual( <del> 'hermes-runtime-darwin-debug-v*.tar.gz', <del> ); <del> }); <del> }); <del> describe('getHermesTagSHA', () => { <del> it('should return trimmed commit SHA for Hermes tag', () => { <del> expect(getHermesTagSHA(hermesTag)).toEqual(hermesTagSha); <del> expect(execCalls.git).toBe(true); <del> }); <del> }); <del> describe('downloadHermesSourceTarball', () => { <del> it('should download Hermes source tarball to download dir', () => { <del> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); <del> downloadHermesSourceTarball(); <del> expect(execCalls.curl).toBe(true); <del> expect( <del> fs.readFileSync( <del> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ).toEqual(tarballContents); <del> }); <del> it('should not re-download Hermes tarball if tarball exists', () => { <del> fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <del> tarballContents, <del> ); <del> <del> downloadHermesSourceTarball(); <del> expect(execCalls.curl).toBeUndefined(); <del> }); <del> }); <del> describe('expandHermesSourceTarball', () => { <del> it('should expand Hermes source tarball to Hermes source dir', () => { <del> fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <del> tarballContents, <del> ); <del> expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBeFalsy(); <del> expandHermesSourceTarball(); <del> expect(execCalls.tar).toBe(true); <del> expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBe(true); <del> }); <del> it('should fail if Hermes source tarball does not exist', () => { <del> expect(() => { <del> expandHermesSourceTarball(); <del> }).toThrow('[Hermes] Could not locate Hermes tarball.'); <del> expect(execCalls.tar).toBeUndefined(); <del> }); <del> }); <del> describe('copyBuildScripts', () => { <del> it('should copy React Native Hermes build scripts to Hermes source directory', () => { <del> copyBuildScripts(); <del> <del> [ <del> 'build-apple-framework.sh', <del> 'build-ios-framework.sh', <del> 'build-mac-framework.sh', <del> ].forEach(buildScript => { <del> expect( <del> fs.readFileSync( <del> path.join(ROOT_DIR, 'sdks', 'hermes', 'utils', buildScript), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ).toEqual( <del> fs.readFileSync( <del> path.join(ROOT_DIR, 'sdks', 'hermes-engine', 'utils', buildScript), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ); <del> }); <del> }); <del> }); <del> describe('copyPodSpec', () => { <del> it('should copy React Native Hermes Podspec to Hermes source directory', () => { <del> copyPodSpec(); <del> expect( <del> fs.readFileSync( <del> path.join(SDKS_DIR, 'hermes', 'hermes-engine.podspec'), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ).toEqual( <del> fs.readFileSync( <del> path.join(SDKS_DIR, 'hermes-engine', 'hermes-engine.podspec'), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ); <del> }); <del> it('should copy hermes-utils.rb to Hermes source directory', () => { <del> copyPodSpec(); <del> expect( <del> fs.readFileSync(path.join(SDKS_DIR, 'hermes', 'hermes-utils.rb'), { <del> encoding: 'utf8', <del> flag: 'r', <del> }), <del> ).toEqual( <del> fs.readFileSync( <del> path.join(SDKS_DIR, 'hermes-engine', 'hermes-utils.rb'), <del> { <del> encoding: 'utf8', <del> flag: 'r', <del> }, <del> ), <del> ); <del> }); <del> }); <del> describe('shouldUsePrebuiltHermesC', () => { <del> it('returns false if path to osx hermesc does not exist', () => { <del> expect(shouldUsePrebuiltHermesC('macos')).toBeFalsy(); <del> }); <del> it('returns false for non-macOS', () => { <del> expect(shouldUsePrebuiltHermesC('windows')).toBeFalsy(); <del> }); <del> it('return true only if path to hermesc exists', () => { <del> fs.mkdirSync(path.join(SDKS_DIR, 'hermesc', 'osx-bin'), { <del> recursive: true, <del> }); <del> fs.writeFileSync( <del> path.join(SDKS_DIR, 'hermesc', 'osx-bin', 'hermesc'), <del> hermescContents, <del> ); <del> expect(shouldUsePrebuiltHermesC('macos')).toBe(true); <del> }); <del> }); <del> <del> describe('configureMakeForPrebuiltHermesC', () => { <del> it('creates ImportHermesC file', () => { <del> fs.mkdirSync(path.join(SDKS_DIR, 'hermesc', 'osx-bin'), { <del> recursive: true, <del> }); <del> configureMakeForPrebuiltHermesC(); <del> expect( <del> fs.existsSync( <del> path.join(SDKS_DIR, 'hermesc', 'osx-bin', 'ImportHermesc.cmake'), <del> ), <del> ).toBe(true); <del> }); <del> }); <del>}); <ide><path>scripts/hermes/__tests__/hermes-utils-test.js <add>/** <add> * Copyright (c) Meta Platforms, Inc. and 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> */ <add> <add>import * as path from 'path'; <add> <add>const os = require('os'); <add> <add>const { <add> configureMakeForPrebuiltHermesC, <add> copyBuildScripts, <add> copyPodSpec, <add> createHermesPrebuiltArtifactsTarball, <add> createTarballFromDirectory, <add> downloadHermesSourceTarball, <add> expandHermesSourceTarball, <add> getHermesTarballDownloadPath, <add> getHermesPrebuiltArtifactsTarballName, <add> getHermesTagSHA, <add> readHermesTag, <add> setHermesTag, <add> shouldUsePrebuiltHermesC, <add>} = require('../hermes-utils'); <add> <add>const hermesTag = <add> 'hermes-2022-04-28-RNv0.69.0-15d07c2edd29a4ea0b8f15ab0588a0c1adb1200f'; <add>const tarballContents = 'dummy string'; <add>const hermescContents = 'dummy string'; <add>const hermesTagSha = '5244f819b2f3949ca94a3a1bf75d54a8ed59d94a'; <add> <add>const ROOT_DIR = path.normalize(path.join(__dirname, '../../..')); <add>const SDKS_DIR = path.join(ROOT_DIR, 'sdks'); <add> <add>const MemoryFs = require('metro-memory-fs'); <add> <add>let execCalls, spawnCalls; <add>let fs; <add> <add>jest.mock('child_process', () => ({ <add> execSync: jest.fn((command, options) => { <add> // git is used in getHermesTagSHA to obtain the commit sha for the latest commit to Hermes main <add> if (command.startsWith('git')) { <add> execCalls.git = true; <add> return hermesTagSha + '\n'; <add> } <add> }), <add> spawnSync: jest.fn((command, args, options) => { <add> // curl is used in downloadHermesSourceTarball to fetch the source code from github.com/facebook/hermes for a specific Hermes commit sha <add> if (command === 'curl') { <add> const downloadPath = args[2]; <add> fs.writeFileSync(downloadPath, tarballContents); <add> spawnCalls.curl = true; <add> return {code: 0}; <add> } <add> <add> // tar is used in createTarballFromDirectory <add> if (command === 'tar') { <add> spawnCalls.tar = true; <add> <add> if (args[0] === '-zxf') { <add> // We are expanding the tarball <add> fs.mkdirSync(path.join(SDKS_DIR, 'hermes/utils'), { <add> recursive: true, <add> }); <add> fs.writeFileSync(path.join(SDKS_DIR, 'hermes/package.json'), '{}'); <add> return {code: 0}; <add> } else if (args[2] === '-czvf') { <add> // We are creating the tarball <add> const filename = args[3]; <add> fs.writeFileSync(filename, tarballContents); <add> return {code: 0}; <add> } <add> } <add> <add> // rsync is used in createHermesPrebuiltArtifactsTarball <add> if (command === 'rsync') { <add> spawnCalls.rsync = true; <add> spawnCalls.rsyncArgs = args; <add> const destination = args[args.length - 1]; <add> <add> // Create destination directory <add> fs.mkdirSync(path.join(options.cwd, destination), { <add> recursive: true, <add> }); <add> } <add> }), <add>})); <add> <add>function populateMockFilesystemWithHermesBuildScripts() { <add> fs.mkdirSync(path.join(SDKS_DIR, 'hermes-engine/utils'), { <add> recursive: true, <add> }); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/utils/build-apple-framework.sh'), <add> 'Dummy file', <add> ); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/utils/build-ios-framework.sh'), <add> 'Dummy file', <add> ); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/utils/build-mac-framework.sh'), <add> 'Dummy file', <add> ); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/hermes-engine.podspec'), <add> 'Dummy file', <add> ); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/hermes-utils.rb'), <add> 'Dummy file', <add> ); <add>} <add> <add>function populateMockFilesystemWithHermesBuildArtifacts() { <add> fs.mkdirSync(os.tmpdir(), {recursive: true}); <add> const frameworksDir = path.join( <add> SDKS_DIR, <add> 'hermes/destroot/Library/Frameworks', <add> ); <add> fs.mkdirSync(path.join(frameworksDir, 'macosx/hermes.framework'), { <add> recursive: true, <add> }); <add> fs.mkdirSync(path.join(frameworksDir, 'universal/hermes.xcframework'), { <add> recursive: true, <add> }); <add> <add> const dsymsDirs = [ <add> 'macosx', <add> 'universal/hermes.xcframework/ios-arm64/dSYMs', <add> 'universal/hermes.xcframework/ios-arm64_x86_64-simulator/dSYMs', <add> 'universal/hermes.xcframework/ios-arm64_x86_64-maccatalyst/dSYMs', <add> ]; <add> <add> for (const dsymsDir of dsymsDirs) { <add> fs.mkdirSync(path.join(frameworksDir, dsymsDir, 'hermes.framework.dSYM'), { <add> recursive: true, <add> }); <add> } <add>} <add> <add>describe('hermes-utils', () => { <add> beforeEach(() => { <add> jest.resetModules(); <add> <add> jest.mock( <add> 'fs', <add> () => <add> new MemoryFs({ <add> platform: process.platform === 'win32' ? 'win32' : 'posix', <add> }), <add> ); <add> fs = require('fs'); <add> fs.reset(); <add> <add> populateMockFilesystemWithHermesBuildScripts(); <add> <add> execCalls = Object.create(null); <add> spawnCalls = Object.create(null); <add> }); <add> <add> describe('Versioning Hermes', () => { <add> describe('readHermesTag', () => { <add> it('should return main if .hermesversion does not exist', () => { <add> expect(readHermesTag()).toEqual('main'); <add> }); <add> it('should fail if hermes tag is empty', () => { <add> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), ''); <add> expect(() => { <add> readHermesTag(); <add> }).toThrow('[Hermes] .hermesversion file is empty.'); <add> }); <add> it('should return tag from .hermesversion if file exists', () => { <add> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); <add> expect(readHermesTag()).toEqual(hermesTag); <add> }); <add> }); <add> <add> describe('setHermesTag', () => { <add> it('should write tag to .hermesversion file', () => { <add> setHermesTag(hermesTag); <add> expect( <add> fs.readFileSync(path.join(SDKS_DIR, '.hermesversion'), { <add> encoding: 'utf8', <add> flag: 'r', <add> }), <add> ).toEqual(hermesTag); <add> }); <add> it('should set Hermes tag and read it back', () => { <add> setHermesTag(hermesTag); <add> expect(readHermesTag()).toEqual(hermesTag); <add> }); <add> }); <add> <add> describe('getHermesTagSHA', () => { <add> it('should return trimmed commit SHA for Hermes tag', () => { <add> expect(getHermesTagSHA(hermesTag)).toEqual(hermesTagSha); <add> expect(execCalls.git).toBe(true); <add> }); <add> }); <add> }); <add> <add> describe('Downloading Hermes', () => { <add> describe('getHermesTarballDownloadPath', () => { <add> it('returns download path with Hermes tag sha', () => { <add> const hermesTarballDownloadPath = <add> getHermesTarballDownloadPath(hermesTag); <add> expect(hermesTarballDownloadPath).toEqual( <add> path.join( <add> SDKS_DIR, <add> 'download', <add> `hermes-${getHermesTagSHA(hermesTag)}.tgz`, <add> ), <add> ); <add> }); <add> }); <add> describe('downloadHermesSourceTarball', () => { <add> it('should download Hermes source tarball to download dir', () => { <add> fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); <add> const hermesTarballDownloadPath = <add> getHermesTarballDownloadPath(hermesTag); <add> downloadHermesSourceTarball(); <add> expect(spawnCalls.curl).toBe(true); <add> expect( <add> fs.readFileSync(hermesTarballDownloadPath, { <add> encoding: 'utf8', <add> flag: 'r', <add> }), <add> ).toEqual(tarballContents); <add> }); <add> it('should not re-download Hermes source tarball if tarball exists', () => { <add> fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <add> tarballContents, <add> ); <add> <add> downloadHermesSourceTarball(); <add> expect(spawnCalls.curl).toBeUndefined(); <add> }); <add> }); <add> <add> describe('expandHermesSourceTarball', () => { <add> it('should expand Hermes source tarball to Hermes source dir', () => { <add> fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), <add> tarballContents, <add> ); <add> expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBeFalsy(); <add> expandHermesSourceTarball(); <add> expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBe(true); <add> }); <add> it('should fail if Hermes source tarball does not exist', () => { <add> expect(() => { <add> expandHermesSourceTarball(); <add> }).toThrow('[Hermes] Could not locate Hermes tarball.'); <add> }); <add> }); <add> }); <add> <add> describe('Configuring Hermes Build', () => { <add> describe('copyBuildScripts', () => { <add> it('should copy React Native Hermes build scripts to Hermes source directory', () => { <add> copyBuildScripts(); <add> <add> [ <add> 'build-apple-framework.sh', <add> 'build-ios-framework.sh', <add> 'build-mac-framework.sh', <add> ].forEach(buildScript => { <add> expect( <add> fs.readFileSync( <add> path.join(ROOT_DIR, 'sdks/hermes/utils', buildScript), <add> { <add> encoding: 'utf8', <add> flag: 'r', <add> }, <add> ), <add> ).toEqual( <add> fs.readFileSync( <add> path.join(ROOT_DIR, 'sdks/hermes-engine/utils', buildScript), <add> { <add> encoding: 'utf8', <add> flag: 'r', <add> }, <add> ), <add> ); <add> }); <add> }); <add> }); <add> describe('copyPodSpec', () => { <add> it('should copy React Native Hermes Podspec to Hermes source directory', () => { <add> copyPodSpec(); <add> expect( <add> fs.readFileSync(path.join(SDKS_DIR, 'hermes/hermes-engine.podspec'), { <add> encoding: 'utf8', <add> flag: 'r', <add> }), <add> ).toEqual( <add> fs.readFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/hermes-engine.podspec'), <add> { <add> encoding: 'utf8', <add> flag: 'r', <add> }, <add> ), <add> ); <add> }); <add> it('should copy hermes-utils.rb to Hermes source directory', () => { <add> copyPodSpec(); <add> expect( <add> fs.readFileSync(path.join(SDKS_DIR, 'hermes/hermes-utils.rb'), { <add> encoding: 'utf8', <add> flag: 'r', <add> }), <add> ).toEqual( <add> fs.readFileSync( <add> path.join(SDKS_DIR, 'hermes-engine/hermes-utils.rb'), <add> { <add> encoding: 'utf8', <add> flag: 'r', <add> }, <add> ), <add> ); <add> }); <add> }); <add> describe('shouldUsePrebuiltHermesC', () => { <add> it('returns false if path to osx hermesc does not exist', () => { <add> expect(shouldUsePrebuiltHermesC('macos')).toBeFalsy(); <add> }); <add> it('returns false for non-macOS', () => { <add> expect(shouldUsePrebuiltHermesC('windows')).toBeFalsy(); <add> }); <add> it('return true only if path to hermesc exists', () => { <add> fs.mkdirSync(path.join(SDKS_DIR, 'hermesc/osx-bin'), { <add> recursive: true, <add> }); <add> fs.writeFileSync( <add> path.join(SDKS_DIR, 'hermesc/osx-bin/hermesc'), <add> hermescContents, <add> ); <add> expect(shouldUsePrebuiltHermesC('macos')).toBe(true); <add> }); <add> }); <add> <add> describe('configureMakeForPrebuiltHermesC', () => { <add> it('creates ImportHermesC file', () => { <add> fs.mkdirSync(path.join(SDKS_DIR, 'hermesc/osx-bin'), { <add> recursive: true, <add> }); <add> configureMakeForPrebuiltHermesC(); <add> expect( <add> fs.existsSync( <add> path.join(SDKS_DIR, 'hermesc/osx-bin/ImportHermesc.cmake'), <add> ), <add> ).toBe(true); <add> }); <add> }); <add> }); <add> <add> describe('Packaging Hermes', () => { <add> beforeEach(() => { <add> populateMockFilesystemWithHermesBuildArtifacts(); <add> }); <add> <add> describe('createTarballFromDirectory', () => { <add> it('should create the tarball', () => { <add> fs.mkdirSync(path.join(SDKS_DIR, 'downloads'), {recursive: true}); <add> const tarballFilename = path.join( <add> SDKS_DIR, <add> 'downloads/hermes-runtime-darwin.tar.gz', <add> ); <add> createTarballFromDirectory( <add> path.join(SDKS_DIR, 'hermes/destroot'), <add> tarballFilename, <add> ); <add> expect(spawnCalls.tar).toBe(true); <add> expect(fs.existsSync(tarballFilename)).toBe(true); <add> }); <add> }); <add> <add> describe('getHermesPrebuiltArtifactsTarballName', () => { <add> it('should return Hermes prebuilts tarball name', () => { <add> expect( <add> getHermesPrebuiltArtifactsTarballName('Debug', '1000.0.0'), <add> ).toEqual('hermes-runtime-darwin-debug-v1000.0.0.tar.gz'); <add> }); <add> it('should throw if build type is undefined', () => { <add> expect(() => { <add> getHermesPrebuiltArtifactsTarballName(); <add> }).toThrow('Did not specify build type.'); <add> }); <add> it('should throw if release version is undefined', () => { <add> expect(() => { <add> getHermesPrebuiltArtifactsTarballName('Release'); <add> }).toThrow('Did not specify release version.'); <add> }); <add> it('should return debug Hermes prebuilts tarball name for RN 0.70.0', () => { <add> expect( <add> getHermesPrebuiltArtifactsTarballName('Debug', '0.70.0'), <add> ).toEqual('hermes-runtime-darwin-debug-v0.70.0.tar.gz'); <add> }); <add> it('should return a wildcard Hermes prebuilts tarball name for any RN version', () => { <add> expect(getHermesPrebuiltArtifactsTarballName('Debug', '*')).toEqual( <add> 'hermes-runtime-darwin-debug-v*.tar.gz', <add> ); <add> }); <add> }); <add> <add> describe('createHermesPrebuiltArtifactsTarball', () => { <add> it('creates tarball', () => { <add> const tarballOutputDir = fs.mkdtempSync( <add> path.join(os.tmpdir(), 'hermes-prebuilts-'), <add> ); <add> fs.mkdirSync(tarballOutputDir, { <add> recursive: true, <add> }); <add> <add> const excludeDebugSymbols = false; <add> const tarballOutputPath = createHermesPrebuiltArtifactsTarball( <add> path.join(SDKS_DIR, 'hermes'), <add> 'Debug', <add> '1000.0.0', <add> tarballOutputDir, <add> excludeDebugSymbols, <add> ); <add> expect(fs.existsSync(tarballOutputPath)).toBe(true); <add> expect(spawnCalls.rsync).toBe(true); <add> // rsync -a src dest <add> expect(spawnCalls.rsyncArgs.length).toEqual(3); <add> }); <add> <add> it('creates tarball with debug symbols excluded', () => { <add> const tarballOutputDir = fs.mkdtempSync( <add> path.join(os.tmpdir(), 'hermes-prebuilts-'), <add> ); <add> fs.mkdirSync(tarballOutputDir, { <add> recursive: true, <add> }); <add> <add> const excludeDebugSymbols = true; <add> const tarballOutputPath = createHermesPrebuiltArtifactsTarball( <add> path.join(SDKS_DIR, 'hermes'), <add> 'Debug', <add> '1000.0.0', <add> tarballOutputDir, <add> excludeDebugSymbols, <add> ); <add> expect(fs.existsSync(tarballOutputPath)).toBe(true); <add> expect(spawnCalls.rsync).toBe(true); <add> <add> // When the debug symbols are excluded, we pass an additional two parameters to rsync: <add> // rsync -a --exclude=dSYMs/ --exclude=*.dSYM/ src dest <add> expect(spawnCalls.rsyncArgs.length).toEqual(5); <add> expect(spawnCalls.rsyncArgs[1]).toEqual('--exclude=dSYMs/'); <add> expect(spawnCalls.rsyncArgs[2]).toEqual('--exclude=*.dSYM/'); <add> }); <add> }); <add> }); <add>}); <ide><path>scripts/hermes/hermes-utils.js <ide> const fs = require('fs'); <ide> const os = require('os'); <ide> const path = require('path'); <del>const {execSync} = require('child_process'); <add>const {execSync, spawnSync} = require('child_process'); <ide> <ide> const SDKS_DIR = path.normalize(path.join(__dirname, '..', '..', 'sdks')); <ide> const HERMES_DIR = path.join(SDKS_DIR, 'hermes'); <ide> const MACOS_IMPORT_HERMESC_PATH = path.join( <ide> 'ImportHermesc.cmake', <ide> ); <ide> <add>/** <add> * Delegate execution to the supplied command. <add> * <add> * @param command Path to the command. <add> * @param args Array of arguments pass to the command. <add> * @param options child process options. <add> */ <add>function delegateSync(command, args, options) { <add> return spawnSync(command, args, {stdio: 'inherit', ...options}); <add>} <add> <ide> function readHermesTag() { <ide> if (fs.existsSync(HERMES_TAG_FILE_PATH)) { <ide> const data = fs <ide> function downloadHermesSourceTarball() { <ide> `[Hermes] Downloading Hermes source code for commit ${hermesTagSHA}`, <ide> ); <ide> try { <del> execSync(`curl ${hermesTarballUrl} -Lo ${hermesTarballDownloadPath}`); <add> delegateSync('curl', [hermesTarballUrl, '-Lo', hermesTarballDownloadPath]); <ide> } catch (error) { <ide> throw new Error(`[Hermes] Failed to download Hermes tarball. ${error}`); <ide> } <ide> function expandHermesSourceTarball() { <ide> } <ide> console.info(`[Hermes] Expanding Hermes tarball for commit ${hermesTagSHA}`); <ide> try { <del> execSync( <del> `tar -zxf ${hermesTarballDownloadPath} --strip-components=1 --directory ${HERMES_DIR}`, <del> ); <add> delegateSync('tar', [ <add> '-zxf', <add> hermesTarballDownloadPath, <add> '--strip-components=1', <add> '--directory', <add> HERMES_DIR, <add> ]); <ide> } catch (error) { <ide> throw new Error('[Hermes] Failed to expand Hermes tarball.'); <ide> } <ide> function getHermesPrebuiltArtifactsTarballName(buildType, releaseVersion) { <ide> return `hermes-runtime-darwin-${buildType.toLowerCase()}-v${releaseVersion}.tar.gz`; <ide> } <ide> <add>/** <add> * Creates a tarball with the contents of the supplied directory. <add> */ <add>function createTarballFromDirectory(directory, filename) { <add> const args = ['-C', directory, '-czvf', filename, '.']; <add> delegateSync('tar', args); <add>} <add> <ide> function createHermesPrebuiltArtifactsTarball( <ide> hermesDir, <ide> buildType, <ide> function createHermesPrebuiltArtifactsTarball( <ide> args.push('--exclude=dSYMs/'); <ide> args.push('--exclude=*.dSYM/'); <ide> } <del> execSync(`rsync ${args.join(' ')} ./destroot ${tarballTempDir}`, { <add> args.push('./destroot'); <add> args.push(tarballTempDir); <add> delegateSync('rsync', args, { <ide> cwd: hermesDir, <ide> }); <ide> if (fs.existsSync(path.join(hermesDir, 'LICENSE'))) { <del> execSync(`cp LICENSE ${tarballTempDir}`, {cwd: hermesDir}); <add> delegateSync('cp', ['LICENSE', tarballTempDir], {cwd: hermesDir}); <ide> } <ide> } catch (error) { <ide> throw new Error(`Failed to copy destroot to tempdir: ${error}`); <ide> } <ide> <del> const tarballFilename = getHermesPrebuiltArtifactsTarballName( <del> buildType, <del> releaseVersion, <add> const tarballFilename = path.join( <add> tarballOutputDir, <add> getHermesPrebuiltArtifactsTarballName(buildType, releaseVersion), <ide> ); <del> const tarballOutputPath = path.join(tarballOutputDir, tarballFilename); <ide> <ide> try { <del> execSync(`tar -C ${tarballTempDir} -czvf ${tarballOutputPath} .`); <add> createTarballFromDirectory(tarballTempDir, tarballFilename); <ide> } catch (error) { <ide> throw new Error(`[Hermes] Failed to create tarball: ${error}`); <ide> } <ide> <del> if (!fs.existsSync(tarballOutputPath)) { <add> if (!fs.existsSync(tarballFilename)) { <ide> throw new Error( <del> `Tarball creation failed, could not locate tarball at ${tarballOutputPath}`, <add> `Tarball creation failed, could not locate tarball at ${tarballFilename}`, <ide> ); <ide> } <ide> <del> return tarballOutputPath; <add> return tarballFilename; <ide> } <ide> <ide> function validateHermesFrameworksExist(destrootDir) { <ide> module.exports = { <ide> copyBuildScripts, <ide> copyPodSpec, <ide> createHermesPrebuiltArtifactsTarball, <add> createTarballFromDirectory, <ide> downloadHermesSourceTarball, <ide> expandHermesSourceTarball, <ide> getHermesTagSHA, <add> getHermesTarballDownloadPath, <ide> getHermesPrebuiltArtifactsTarballName, <ide> readHermesTag, <ide> setHermesTag,
3
Javascript
Javascript
add more info about nuget setup
9622b266f485f559f14a7bad8965d9886e321519
<ide><path>tasks/nuget.js <ide> module.exports = function (grunt) { <add> // To set up on mac: <add> // * brew install nuget # this fetches mono <add> // * go to nuget.org, login, click on username (top right), copy api-key <add> // from the bottom <add> // * grunt nugetkey --key=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX <add> // * grunt nuget-publish <add> // <add> // <ide> // If this fails you might need to follow: <ide> // <ide> // http://stackoverflow.com/questions/15181888/nuget-on-linux-error-getting-response-stream
1
Java
Java
update copyright date
7575616d268997b40758ccb57815d57afceb9ab5
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptUtils.java <ide> /* <del> * Copyright 2002-2019 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
Python
Python
keep the cruft for compatibility for now
2fefcefa18e3eddae19b15a3603cea80ad381b09
<ide><path>numpy/core/setup.py <ide> def name_to_defsymb(name): <ide> if check_func(f): <ide> moredefs.append(name_to_defsymb(f)) <ide> <del># for func_name, defsymbol in FUNCTIONS_TO_CHECK: <del># if check_func(func_name): <del># moredefs.append(defsymbol) <add> # Keep this for compatibility for now <add> for func_name, defsymbol in FUNCTIONS_TO_CHECK: <add> if check_func(func_name): <add> moredefs.append(defsymbol) <ide> <ide> def configuration(parent_package='',top_path=None): <ide> from numpy.distutils.misc_util import Configuration,dot_join
1
Text
Text
add manual package install directions to atom docs
6092de9af8f3f420c64cffa5b9d8e75b6c8a076c
<ide><path>docs/customizing-atom.md <ide> Themes` section on the `Packages` tab within the Settings panel. <ide> You can install non-bundled packages by going to the `Available Packages` <ide> section on the `Packages` tab within the Settings panel (`cmd-,`). <ide> <add>To manually install a package from [atom.io](http://atom-io.dev/packages) (emmet, in this example), run this in your shell: <add> <add>`$ apm install emmet` <add> <add>If you want to install a specific version of a package, you can do so like this: <add> <add>`$ apm install emmet@0.1.5` <add> <ide> ## Customizing Key Bindings <ide> <ide> Atom keymaps work similarly to stylesheets. Just as stylesheets use selectors
1
Javascript
Javascript
avoid cross-realm objects
18c59c600d6d6149011f3c0a3b6d0e85b31329f3
<ide><path>lib/dependencies/CommonJsImportsParserPlugin.js <ide> class CommonJsImportsParserPlugin { <ide> parser.parseCommentOptions(expr.range); <ide> <ide> if (commentErrors) { <del> for (const e of commentErrors) { <del> const { comment } = e; <add> for (const { cause: e, comment } of commentErrors) { <ide> parser.state.module.addWarning( <ide> new CommentCompilationWarning( <ide> `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, <ide><path>lib/dependencies/ImportParserPlugin.js <ide> class ImportParserPlugin { <ide> parser.parseCommentOptions(expr.range); <ide> <ide> if (commentErrors) { <del> for (const e of commentErrors) { <del> const { comment } = e; <add> for (const { cause: e, comment } of commentErrors) { <ide> parser.state.module.addWarning( <ide> new CommentCompilationWarning( <ide> `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, <ide> class ImportParserPlugin { <ide> if (importOptions.webpackInclude !== undefined) { <ide> if ( <ide> !importOptions.webpackInclude || <del> importOptions.webpackInclude.constructor.name !== "RegExp" <add> !(importOptions.webpackInclude instanceof RegExp) <ide> ) { <ide> parser.state.module.addWarning( <ide> new UnsupportedFeatureWarning( <ide> class ImportParserPlugin { <ide> ) <ide> ); <ide> } else { <del> include = new RegExp(importOptions.webpackInclude); <add> include = importOptions.webpackInclude; <ide> } <ide> } <ide> if (importOptions.webpackExclude !== undefined) { <ide> if ( <ide> !importOptions.webpackExclude || <del> importOptions.webpackExclude.constructor.name !== "RegExp" <add> !(importOptions.webpackExclude instanceof RegExp) <ide> ) { <ide> parser.state.module.addWarning( <ide> new UnsupportedFeatureWarning( <ide> class ImportParserPlugin { <ide> ) <ide> ); <ide> } else { <del> exclude = new RegExp(importOptions.webpackExclude); <add> exclude = importOptions.webpackExclude; <ide> } <ide> } <ide> if (importOptions.webpackExports !== undefined) { <ide><path>lib/dependencies/WorkerPlugin.js <ide> class WorkerPlugin { <ide> parser.parseCommentOptions(expr.range); <ide> <ide> if (commentErrors) { <del> for (const e of commentErrors) { <del> const { comment } = e; <add> for (const { cause: e, comment } of commentErrors) { <ide> parser.state.module.addWarning( <ide> new CommentCompilationWarning( <ide> `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, <ide> class WorkerPlugin { <ide> } else { <ide> Object.assign( <ide> entryOptions, <del> importOptions.webpackEntryOptions <add> JSON.parse( <add> JSON.stringify(importOptions.webpackEntryOptions) <add> ) <ide> ); <ide> } <ide> } <ide><path>lib/javascript/JavascriptParser.js <ide> class JavascriptParser extends Parser { <ide> if (value && webpackCommentRegExp.test(value)) { <ide> // try compile only if webpack options comment is present <ide> try { <del> const val = vm.runInNewContext(`(function(){return {${value}};})()`); <del> Object.assign(options, val); <add> let val = vm.runInNewContext(`(function(){return {${value}};})()`); <add> const key = Object.getOwnPropertyNames(val)[0]; <add> if (!key) continue; <add> val = val[key]; <add> <add> if (typeof val === "object" && val !== null) { <add> if (val.constructor.name === "RegExp") val = new RegExp(val); <add> else val = JSON.parse(JSON.stringify(val)); <add> } <add> options[key] = val; <ide> } catch (e) { <del> e.comment = comment; <del> errors.push(e); <add> errors.push({ comment, cause: e }); <ide> } <ide> } <ide> }
4
PHP
PHP
fix tests for php < 8.1
9dd4b5e052004e37a1af3079cc22f1ba3fd855f7
<ide><path>tests/Database/DatabaseEloquentMorphToTest.php <ide> public function testLookupDictionaryIsProperlyConstructedForStringableEnums() <ide> { <ide> if (PHP_VERSION < "8.1") { <ide> $this->markTestSkipped('PHP 8.1 is required'); <add> } else { <add> $relation = $this->getRelation(); <add> $relation->addEagerConstraints([ <add> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnumStringAllowed::test2] <add> ]); <add> $dictionary = $relation->getDictionary(); <add> $value = $dictionary['morph_type_2'][TestEnumStringAllowed::test2->toString()][0]->foreign_key; <add> $this->assertEquals(TestEnumStringAllowed::test2, $value); <ide> } <del> $relation = $this->getRelation(); <del> $relation->addEagerConstraints([ <del> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnumStringAllowed::test2] <del> ]); <del> $dictionary = $relation->getDictionary(); <del> $value = $dictionary['morph_type_2'][TestEnumStringAllowed::test2->toString()][0]->foreign_key; <del> $this->assertEquals(TestEnumStringAllowed::test2, $value); <add> <ide> } <ide> <ide> public function testLookupDictionaryIsNotProperlyConstructedForEnums() <ide> { <ide> if (PHP_VERSION < "8.1") { <ide> $this->markTestSkipped('PHP 8.1 is required'); <add> } else { <add> $this->expectException(InvalidArgumentException::class); <add> $relation = $this->getRelation(); <add> $relation->addEagerConstraints([ <add> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnum::test] <add> ]); <add> $relation->getDictionary(); <ide> } <del> $this->expectException(InvalidArgumentException::class); <del> $relation = $this->getRelation(); <del> $relation->addEagerConstraints([ <del> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnum::test] <del> ]); <del> $dictionary = $relation->getDictionary(); <add> <ide> } <ide> <ide> public function testLookupDictionaryIsProperlyConstructed()
1
Ruby
Ruby
update actionmailer documentation [ci skip]
e2c7545cdd69376ed7e6ccb2084dda8cbd7571c2
<ide><path>actionmailer/lib/action_mailer/collector.rb <ide> require 'active_support/core_ext/hash/reverse_merge' <ide> require 'active_support/core_ext/array/extract_options' <ide> <del>module ActionMailer #:nodoc: <add>module ActionMailer <ide> class Collector <ide> include AbstractController::Collector <ide> attr_reader :responses <ide><path>actionmailer/lib/action_mailer/delivery_methods.rb <ide> require 'tmpdir' <ide> <ide> module ActionMailer <del> # This module handles everything related to mail delivery, from registering new <del> # delivery methods to configuring the mail object to be sent. <add> # This module handles everything related to mail delivery, from registering <add> # new delivery methods to configuring the mail object to be sent. <ide> module DeliveryMethods <ide> extend ActiveSupport::Concern <ide> <ide> module ClassMethods <ide> # Provides a list of emails that have been delivered by Mail::TestMailer <ide> delegate :deliveries, :deliveries=, :to => Mail::TestMailer <ide> <del> # Adds a new delivery method through the given class using the given symbol <del> # as alias and the default options supplied: <del> # <del> # Example: <add> # Adds a new delivery method through the given class using the given <add> # symbol as alias and the default options supplied. <ide> # <ide> # add_delivery_method :sendmail, Mail::Sendmail, <del> # :location => '/usr/sbin/sendmail', <del> # :arguments => '-i -t' <del> # <add> # location: '/usr/sbin/sendmail', <add> # arguments: '-i -t' <ide> def add_delivery_method(symbol, klass, default_options={}) <ide> class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings") <ide> send(:"#{symbol}_settings=", default_options) <ide> self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze <ide> end <ide> <del> def wrap_delivery_behavior(mail, method=nil, options=nil) #:nodoc: <add> def wrap_delivery_behavior(mail, method=nil, options=nil) # :nodoc: <ide> method ||= self.delivery_method <ide> mail.delivery_handler = self <ide> <ide> def wrap_delivery_behavior(mail, method=nil, options=nil) #:nodoc: <ide> end <ide> end <ide> <del> def wrap_delivery_behavior!(*args) #:nodoc: <add> def wrap_delivery_behavior!(*args) # :nodoc: <ide> self.class.wrap_delivery_behavior(message, *args) <ide> end <ide> end <ide><path>actionmailer/lib/action_mailer/mail_helper.rb <ide> module ActionMailer <ide> module MailHelper <del> # Take the text and format it, indented two spaces for each line, and wrapped at 72 columns. <add> # Take the text and format it, indented two spaces for each line, and <add> # wrapped at 72 columns. <ide> def block_format(text) <ide> formatted = text.split(/\n\r?\n/).collect { |paragraph| <ide> format_paragraph(paragraph) <ide> def attachments <ide> <ide> # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces. <ide> # <del> # === Examples <del> # <del> # my_text = "Here is a sample text with more than 40 characters" <add> # my_text = 'Here is a sample text with more than 40 characters' <ide> # <ide> # format_paragraph(my_text, 25, 4) <ide> # # => " Here is a sample text with\n more than 40 characters" <ide><path>actionmailer/lib/action_mailer/railtie.rb <ide> require "abstract_controller/railties/routes_helpers" <ide> <ide> module ActionMailer <del> class Railtie < Rails::Railtie <add> class Railtie < Rails::Railtie # :nodoc: <ide> config.action_mailer = ActiveSupport::OrderedOptions.new <ide> config.eager_load_namespaces << ActionMailer <ide> <ide><path>actionmailer/lib/action_mailer/test_helper.rb <ide> module TestHelper <ide> # assert_emails 2 <ide> # end <ide> # <del> # If a block is passed, that block should cause the specified number of emails to be sent. <add> # If a block is passed, that block should cause the specified number of <add> # emails to be sent. <ide> # <ide> # def test_emails_again <ide> # assert_emails 1 do
5
Javascript
Javascript
prevent disabled optimization of bind()
88b28896790023ae4653eefbc6687bbf0046c00c
<ide><path>lib/dgram.js <ide> function replaceHandle(self, newHandle) { <ide> self._handle = newHandle; <ide> } <ide> <del>Socket.prototype.bind = function(port /*, address, callback*/) { <add>Socket.prototype.bind = function(port_ /*, address, callback*/) { <ide> var self = this; <add> let port = port_; <ide> <ide> self._healthCheck(); <ide>
1
PHP
PHP
fix @link tag
4d2cc316bb4b231e70649159d5ed1563cbc7e76f
<ide><path>src/Cache/Engine/RedisEngine.php <ide> public function clearGroup(string $group): bool <ide> * <ide> * @param mixed $value Value to serialize. <ide> * @return string <del> * @https://github.com/phpredis/phpredis/issues/81 <add> * @link https://github.com/phpredis/phpredis/issues/81 <ide> */ <ide> protected function serialize($value): string <ide> {
1
Javascript
Javascript
provide duration/interval to timers
6263c00828ada8ed1cfd110e59906b99352131d0
<ide><path>test/message/timeout_throw.js <ide> require('../common'); <ide> setTimeout(function() { <ide> // eslint-disable-next-line no-undef <ide> undefined_reference_error_maker; <del>}); <add>}, 1); <ide><path>test/parallel/test-handle-wrap-close-abort.js <ide> setTimeout(function() { <ide> setTimeout(function() { <ide> throw new Error('setTimeout'); <ide> }, 1); <del>}); <add>}, 1); <ide><path>test/parallel/test-stream-end-paused.js <ide> stream.pause(); <ide> setTimeout(common.mustCall(function() { <ide> stream.on('end', common.mustCall(function() {})); <ide> stream.resume(); <del>})); <add>}), 1); <ide> <ide> process.on('exit', function() { <ide> assert(calledRead); <ide><path>test/parallel/test-stream-readable-event.js <ide> const Readable = require('stream').Readable; <ide> // we're testing what we think we are <ide> assert(!r._readableState.reading); <ide> r.on('readable', common.mustCall(function() {})); <del> }); <add> }, 1); <ide> } <ide> <ide> { <ide> const Readable = require('stream').Readable; <ide> // assert we're testing what we think we are <ide> assert(r._readableState.reading); <ide> r.on('readable', common.mustCall(function() {})); <del> }); <add> }, 1); <ide> } <ide> <ide> { <ide> const Readable = require('stream').Readable; <ide> // assert we're testing what we think we are <ide> assert(!r._readableState.reading); <ide> r.on('readable', common.mustCall(function() {})); <del> }); <add> }, 1); <ide> } <ide><path>test/parallel/test-stream2-large-read-stall.js <ide> function push() { <ide> <ide> console.error(' push #%d', pushes); <ide> if (r.push(Buffer.allocUnsafe(PUSHSIZE))) <del> setTimeout(push); <add> setTimeout(push, 1); <ide> } <ide> <ide> process.on('exit', function() { <ide><path>test/parallel/test-stream2-readable-non-empty-end.js <ide> test._read = function(size) { <ide> var chunk = chunks[n++]; <ide> setTimeout(function() { <ide> test.push(chunk === undefined ? null : chunk); <del> }); <add> }, 1); <ide> }; <ide> <ide> test.on('end', thrower); <ide> test.on('readable', function() { <ide> if (res) { <ide> bytesread += res.length; <ide> console.error('br=%d len=%d', bytesread, len); <del> setTimeout(next); <add> setTimeout(next, 1); <ide> } <ide> test.read(0); <ide> });
6
Javascript
Javascript
add atom beta to launcheditor
d38644eee53e81c70978ba48ef9dcd2e78fd5b80
<ide><path>local-cli/server/util/launchEditor.js <ide> function isTerminalEditor(editor) { <ide> // of the app every time <ide> var COMMON_EDITORS = { <ide> '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', <add> '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': <add> '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', <ide> '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': <ide> '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', <ide> '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': <ide> function getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) { <ide> case 'wstorm': <ide> case 'appcode': <ide> case 'charm': <del> case 'idea': <add> case 'idea': <ide> return [fileName + ':' + lineNumber]; <ide> case 'joe': <ide> case 'emacs':
1
Python
Python
fix "ok" alignment in migrate output
d5ca1693341daccce9b0dd8504967a56b289d92f
<ide><path>django/core/management/commands/migrate.py <ide> def handle(self, *args, **options): <ide> def migration_progress_callback(self, action, migration): <ide> if self.verbosity >= 1: <ide> if action == "apply_start": <del> self.stdout.write(" Applying %s... " % migration) <add> self.stdout.write(" Applying %s..." % migration, ending="") <ide> self.stdout.flush() <ide> elif action == "apply_success": <del> self.stdout.write(" OK\n") <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK")) <ide> elif action == "unapply_start": <del> self.stdout.write(" Unapplying %s... " % migration) <add> self.stdout.write(" Unapplying %s..." % migration, ending="") <ide> self.stdout.flush() <ide> elif action == "unapply_success": <del> self.stdout.write(" OK\n") <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK")) <ide> <ide> def sync_apps(self, connection, apps): <ide> "Runs the old syncdb-style operation on a list of apps." <ide><path>django/utils/termcolors.py <ide> def make_style(opts=(), **kwargs): <ide> 'HTTP_SERVER_ERROR': {}, <ide> 'MIGRATE_HEADING': {}, <ide> 'MIGRATE_LABEL': {}, <add> 'MIGRATE_SUCCESS': {}, <add> 'MIGRATE_FAILURE': {}, <ide> }, <ide> DARK_PALETTE: { <ide> 'ERROR': { 'fg': 'red', 'opts': ('bold',) }, <ide> def make_style(opts=(), **kwargs): <ide> 'HTTP_SERVER_ERROR': { 'fg': 'magenta', 'opts': ('bold',) }, <ide> 'MIGRATE_HEADING': { 'fg': 'cyan', 'opts': ('bold',) }, <ide> 'MIGRATE_LABEL': { 'opts': ('bold',) }, <add> 'MIGRATE_SUCCESS': { 'fg': 'green', 'opts': ('bold',) }, <add> 'MIGRATE_FAILURE': { 'fg': 'red', 'opts': ('bold',) }, <ide> }, <ide> LIGHT_PALETTE: { <ide> 'ERROR': { 'fg': 'red', 'opts': ('bold',) }, <ide> def make_style(opts=(), **kwargs): <ide> 'HTTP_SERVER_ERROR': { 'fg': 'magenta', 'opts': ('bold',) }, <ide> 'MIGRATE_HEADING': { 'fg': 'cyan', 'opts': ('bold',) }, <ide> 'MIGRATE_LABEL': { 'opts': ('bold',) }, <add> 'MIGRATE_SUCCESS': { 'fg': 'green', 'opts': ('bold',) }, <add> 'MIGRATE_FAILURE': { 'fg': 'red', 'opts': ('bold',) }, <ide> } <ide> } <ide> DEFAULT_PALETTE = DARK_PALETTE
2
Javascript
Javascript
remove internal frames from runtime errors
c5f54b1fad19a35dc00322181650545d2961ccc4
<ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> self._domain.on('error', function debugDomainError(e) { <ide> debug('domain error'); <ide> const top = replMap.get(self); <del> <add> const pstrace = Error.prepareStackTrace; <add> Error.prepareStackTrace = prepareStackTrace(pstrace); <ide> internalUtil.decorateErrorStack(e); <add> Error.prepareStackTrace = pstrace; <ide> const isError = internalUtil.isError(e); <ide> if (e instanceof SyntaxError && e.stack) { <ide> // remove repl:line-number and stack trace <ide> e.stack = e.stack <del> .replace(/^repl:\d+\r?\n/, '') <del> .replace(/^\s+at\s.*\n?/gm, ''); <add> .replace(/^repl:\d+\r?\n/, '') <add> .replace(/^\s+at\s.*\n?/gm, ''); <ide> } else if (isError && self.replMode === exports.REPL_MODE_STRICT) { <ide> e.stack = e.stack.replace(/(\s+at\s+repl:)(\d+)/, <ide> (_, pre, line) => pre + (line - 1)); <ide> function REPLServer(prompt, <ide> }; <ide> } <ide> <add> function filterInternalStackFrames(error, structuredStack) { <add> // search from the bottom of the call stack to <add> // find the first frame with a null function name <add> if (typeof structuredStack !== 'object') <add> return structuredStack; <add> const idx = structuredStack.reverse().findIndex( <add> (frame) => frame.getFunctionName() === null); <add> <add> // if found, get rid of it and everything below it <add> structuredStack = structuredStack.splice(idx + 1); <add> return structuredStack; <add> } <add> <add> function prepareStackTrace(fn) { <add> return (error, stackFrames) => { <add> const frames = filterInternalStackFrames(error, stackFrames); <add> if (fn) { <add> return fn(error, frames); <add> } <add> frames.push(error); <add> return frames.reverse().join('\n at '); <add> }; <add> } <add> <ide> function _parseREPLKeyword(keyword, rest) { <ide> var cmd = this.commands[keyword]; <ide> if (cmd) { <ide> function complete(line, callback) { <ide> } else { <ide> const evalExpr = `try { ${expr} } catch (e) {}`; <ide> this.eval(evalExpr, this.context, 'repl', (e, obj) => { <del> // if (e) console.log(e); <del> <ide> if (obj != null) { <ide> if (typeof obj === 'object' || typeof obj === 'function') { <ide> try { <ide><path>test/fixtures/repl-pretty-stack.js <add>'use strict'; <add> <add>function a() { <add> b(); <add>} <add> <add>function b() { <add> c(); <add>} <add> <add>function c() { <add> d(function() { throw new Error('Whoops!'); }); <add>} <add> <add>function d(f) { <add> f(); <add>} <add> <add>a(); <ide>\ No newline at end of file <ide><path>test/parallel/test-repl-pretty-custom-stack.js <add>'use strict'; <add>const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <add>const assert = require('assert'); <add>const repl = require('repl'); <add> <add> <add>function run({ command, expected }) { <add> let accum = ''; <add> <add> const inputStream = new common.ArrayStream(); <add> const outputStream = new common.ArrayStream(); <add> <add> outputStream.write = (data) => accum += data.replace('\r', ''); <add> <add> const r = repl.start({ <add> prompt: '', <add> input: inputStream, <add> output: outputStream, <add> terminal: false, <add> useColors: false <add> }); <add> <add> r.write(`${command}\n`); <add> assert.strictEqual(accum, expected); <add> r.close(); <add>} <add> <add>const origPrepareStackTrace = Error.prepareStackTrace; <add>Error.prepareStackTrace = (err, stack) => { <add> if (err instanceof SyntaxError) <add> return err.toString(); <add> stack.push(err); <add> return stack.reverse().join('--->\n'); <add>}; <add> <add>process.on('uncaughtException', (e) => { <add> Error.prepareStackTrace = origPrepareStackTrace; <add> throw e; <add>}); <add> <add>process.on('exit', () => (Error.prepareStackTrace = origPrepareStackTrace)); <add> <add>const tests = [ <add> { <add> // test .load for a file that throws <add> command: `.load ${fixtures.path('repl-pretty-stack.js')}`, <add> expected: 'Error: Whoops!--->\nrepl:9:24--->\nd (repl:12:3)--->\nc ' + <add> '(repl:9:3)--->\nb (repl:6:3)--->\na (repl:3:3)\n' <add> }, <add> { <add> command: 'let x y;', <add> expected: 'let x y;\n ^\n\nSyntaxError: Unexpected identifier\n' <add> }, <add> { <add> command: 'throw new Error(\'Whoops!\')', <add> expected: 'Error: Whoops!\n' <add> }, <add> { <add> command: 'foo = bar;', <add> expected: 'ReferenceError: bar is not defined\n' <add> }, <add> // test anonymous IIFE <add> { <add> command: '(function() { throw new Error(\'Whoops!\'); })()', <add> expected: 'Error: Whoops!--->\nrepl:1:21\n' <add> } <add>]; <add> <add>tests.forEach(run); <ide><path>test/parallel/test-repl-pretty-stack.js <add>'use strict'; <add>const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <add>const assert = require('assert'); <add>const repl = require('repl'); <add> <add> <add>function run({ command, expected }) { <add> let accum = ''; <add> <add> const inputStream = new common.ArrayStream(); <add> const outputStream = new common.ArrayStream(); <add> <add> outputStream.write = (data) => accum += data.replace('\r', ''); <add> <add> const r = repl.start({ <add> prompt: '', <add> input: inputStream, <add> output: outputStream, <add> terminal: false, <add> useColors: false <add> }); <add> <add> r.write(`${command}\n`); <add> assert.strictEqual(accum, expected); <add> r.close(); <add>} <add> <add>const tests = [ <add> { <add> // test .load for a file that throws <add> command: `.load ${fixtures.path('repl-pretty-stack.js')}`, <add> expected: 'Error: Whoops!\n at repl:9:24\n at d (repl:12:3)\n ' + <add> 'at c (repl:9:3)\n at b (repl:6:3)\n at a (repl:3:3)\n' <add> }, <add> { <add> command: 'let x y;', <add> expected: 'let x y;\n ^\n\nSyntaxError: Unexpected identifier\n\n' <add> }, <add> { <add> command: 'throw new Error(\'Whoops!\')', <add> expected: 'Error: Whoops!\n' <add> }, <add> { <add> command: 'foo = bar;', <add> expected: 'ReferenceError: bar is not defined\n' <add> }, <add> // test anonymous IIFE <add> { <add> command: '(function() { throw new Error(\'Whoops!\'); })()', <add> expected: 'Error: Whoops!\n at repl:1:21\n' <add> } <add>]; <add> <add>tests.forEach(run); <ide><path>test/parallel/test-repl.js <ide> function clean_up() { <ide> function strict_mode_error_test() { <ide> send_expect([ <ide> { client: client_unix, send: 'ref = 1', <del> expect: /^ReferenceError:\sref\sis\snot\sdefined\n\s+at\srepl:1:5/ }, <add> expect: /^ReferenceError:\sref\sis\snot\sdefined\nnode via Unix socket> $/ }, <ide> ]); <ide> } <ide>
5
Ruby
Ruby
move cxxstdlib methods to the class
249aae177f3e6fb100c391c1f4562cc331c69d2e
<ide><path>Library/Homebrew/compat/formula.rb <ide> def std_cmake_parameters <ide> "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST -Wno-dev" <ide> end <ide> <add> def cxxstdlib <add> self.class.cxxstdlib <add> end <add> <add> def cxxstdlib_check check_type <add> self.class.cxxstdlib_check check_type <add> end <add> <ide> def self.bottle_sha1(*) <ide> end <ide> <ide><path>Library/Homebrew/cxxstdlib.rb <ide> def compatible_with?(other) <ide> end <ide> <ide> def check_dependencies(formula, deps) <del> unless formula.cxxstdlib.include? :skip <add> unless formula.class.cxxstdlib.include? :skip <ide> deps.each do |dep| <ide> # Software is unlikely to link against anything from its <ide> # buildtime deps, so it doesn't matter at all if they link <ide><path>Library/Homebrew/formula.rb <ide> def recursive_requirements(&block) <ide> Requirement.expand(self, &block) <ide> end <ide> <del> # Flag for marking whether this formula needs C++ standard library <del> # compatibility check <del> def cxxstdlib <del> @cxxstdlib ||= Set.new <del> end <del> <ide> def to_hash <ide> hsh = { <ide> "name" => name, <ide> def patch <ide> active_spec.patches.each(&:apply) <ide> end <ide> <del> # Explicitly request changing C++ standard library compatibility check <del> # settings. Use with caution! <del> def cxxstdlib_check check_type <del> cxxstdlib << check_type <del> end <del> <ide> def self.method_added method <ide> case method <ide> when :brew <ide> def keg_only reason, explanation=nil <ide> @keg_only_reason = KegOnlyReason.new(reason, explanation.to_s.chomp) <ide> end <ide> <add> # Flag for marking whether this formula needs C++ standard library <add> # compatibility check <add> def cxxstdlib <add> @cxxstdlib ||= Set.new <add> end <add> <add> # Explicitly request changing C++ standard library compatibility check <add> # settings. Use with caution! <add> def cxxstdlib_check check_type <add> cxxstdlib << check_type <add> end <add> <ide> # For Apple compilers, this should be in the format: <ide> # fails_with compiler do <ide> # cause "An explanation for why the build doesn't work."
3
Javascript
Javascript
move createwritereq to separate function
aec2f733f97460ddde677b53bcc048b55878c7b3
<ide><path>lib/net.js <ide> Socket.prototype.write = function(chunk, encoding, cb) { <ide> <ide> <ide> Socket.prototype._write = function(dataEncoding, cb) { <del> assert(Array.isArray(dataEncoding)); <add> // assert(Array.isArray(dataEncoding)); <ide> var data = dataEncoding[0]; <ide> var encoding = dataEncoding[1] || 'utf8'; <ide> <del> if (this !== process.stderr && this !== process.stdout) <del> debug('Socket._write'); <del> <ide> // If we are still connecting, then buffer this for later. <ide> // The Writable logic will buffer up any more writes while <ide> // waiting for this one to be done. <ide> if (this._connecting) { <del> debug('_write: waiting for connection'); <ide> this._pendingWrite = dataEncoding; <ide> this.once('connect', function() { <del> debug('_write: connected now, try again'); <ide> this._write(dataEncoding, cb); <ide> }); <ide> return; <ide> Socket.prototype._write = function(dataEncoding, cb) { <ide> timers.active(this); <ide> <ide> if (!this._handle) { <del> debug('already destroyed'); <ide> this._destroy(new Error('This socket is closed.'), cb); <ide> return false; <ide> } <ide> <del> var writeReq; <del> <del> if (Buffer.isBuffer(data)) { <del> writeReq = this._handle.writeBuffer(data); <del> <del> } else { <del> switch (encoding) { <del> case 'utf8': <del> case 'utf-8': <del> writeReq = this._handle.writeUtf8String(data); <del> break; <del> <del> case 'ascii': <del> writeReq = this._handle.writeAsciiString(data); <del> break; <del> <del> case 'ucs2': <del> case 'ucs-2': <del> case 'utf16le': <del> case 'utf-16le': <del> writeReq = this._handle.writeUcs2String(data); <del> break; <del> <del> default: <del> writeReq = this._handle.writeBuffer(new Buffer(data, encoding)); <del> break; <del> } <del> } <add> var enc = Buffer.isBuffer(data) ? 'buffer' : encoding; <add> var writeReq = createWriteReq(this._handle, data, enc); <ide> <ide> if (!writeReq || typeof writeReq !== 'object') <ide> return this._destroy(errnoException(errno, 'write'), cb); <ide> Socket.prototype._write = function(dataEncoding, cb) { <ide> writeReq.cb = cb; <ide> }; <ide> <add>function createWriteReq(handle, data, encoding) { <add> switch (encoding) { <add> case 'buffer': <add> return handle.writeBuffer(data); <add> <add> case 'utf8': <add> case 'utf-8': <add> return handle.writeUtf8String(data); <add> <add> case 'ascii': <add> return handle.writeAsciiString(data); <add> <add> case 'ucs2': <add> case 'ucs-2': <add> case 'utf16le': <add> case 'utf-16le': <add> return handle.writeUcs2String(data); <add> <add> default: <add> return handle.writeBuffer(new Buffer(data, encoding)); <add> } <add>} <add> <ide> <ide> Socket.prototype.__defineGetter__('bytesWritten', function() { <ide> var bytes = this._bytesDispatched,
1
Python
Python
fix some typos in solution 1 of euler 686
3bff196981312e41ba9dac91e1bd971b7120726c
<ide><path>project_euler/problem_686/sol1.py <ide> def log_difference(number: int) -> float: <ide> Computing 2^90 is time consuming. <ide> Hence we find log(2^90) = 90*log(2) = 27.092699609758302 <ide> But we require only the decimal part to determine whether the power starts with 123. <del> SO we just return the decimal part of the log product. <add> So we just return the decimal part of the log product. <ide> Therefore we return 0.092699609758302 <ide> <ide> >>> log_difference(90) <ide> def solution(number: int = 678910) -> int: <ide> <ide> So if number = 10, then solution returns 2515 as we observe from above series. <ide> <del> Wwe will define a lowerbound and upperbound. <add> We will define a lowerbound and upperbound. <ide> lowerbound = log(1.23), upperbound = log(1.24) <ide> because we need to find the powers that yield 123 as starting digits. <ide> <ide> log(1.23) = 0.08990511143939792, log(1,24) = 0.09342168516223506. <ide> We use 1.23 and not 12.3 or 123, because log(1.23) yields only decimal value <ide> which is less than 1. <del> log(12.3) will be same decimal vale but 1 added to it <add> log(12.3) will be same decimal value but 1 added to it <ide> which is log(12.3) = 1.093421685162235. <ide> We observe that decimal value remains same no matter 1.23 or 12.3 <ide> Since we use the function log_difference(), <ide> def solution(number: int = 678910) -> int: <ide> Hence to optimize the algorithm we will increment by 196 or 93 depending upon the <ide> log_difference() value. <ide> <del> Lets take for example 90. <add> Let's take for example 90. <ide> Since 90 is the first power leading to staring digits as 123, <ide> we will increment iterator by 196. <ide> Because the difference between any two powers leading to 123 <ide> def solution(number: int = 678910) -> int: <ide> The iterator will now become 379, <ide> which is the next power leading to 123 as starting digits. <ide> <del> Lets take 1060. We increment by 196, we get 1256. <add> Let's take 1060. We increment by 196, we get 1256. <ide> log_difference(1256) = 0.09367455396034, <ide> Which is greater than upperbound hence we increment by 93. Now iterator is 1349. <ide> log_difference(1349) = 0.08946415071057 which is less than lowerbound. <ide> The next power is 1545 and we need to add 196 to get 1545. <ide> <ide> Conditions are as follows: <ide> <del> 1) If we find a power, whose log_difference() is in the range of <add> 1) If we find a power whose log_difference() is in the range of <ide> lower and upperbound, we will increment by 196. <ide> which implies that the power is a number which will lead to 123 as starting digits. <ide> 2) If we find a power, whose log_difference() is greater than or equal upperbound,
1
Text
Text
add 3.2.0-beta.3 to changelog
7f310a6185aabf5a4b828ca64f78b0a22e3a8b74
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.2.0-beta.3 (April 23, 2018) <add>- [#16539](https://github.com/emberjs/ember.js/pull/16539) [BUGFIX] Ember is already registered by the libraries registry already. <add>- [#16559](https://github.com/emberjs/ember.js/pull/16559) [BUGFIX] Fix property normalization, Update glimmer-vm to 0.34.0 <add>- [#16563](https://github.com/emberjs/ember.js/pull/16563) [BUGFIX] Ensure `ariaRole` can be initially false. <add>- [#16550](https://github.com/emberjs/ember.js/pull/16550) [BUGFIX] Decrement counter of pending requests in the next tick <add>- [#16551](https://github.com/emberjs/ember.js/pull/16551) [BUGFIX] Fix `proto` return value for native classes <add>- [#16558](https://github.com/emberjs/ember.js/pull/16558) [BUGFIX] Ensure ComponentDefinitions do not leak heap space. <add>- [#16560](https://github.com/emberjs/ember.js/pull/16560) [BUGFIX] avoid strict assertion when object proxy calls thru for function <add>- [#16564](https://github.com/emberjs/ember.js/pull/16564) [BUGFIX] Ensure Ember.isArray does not trigger proxy assertion. <add>- [#16572](https://github.com/emberjs/ember.js/pull/16572) [BUGFIX] Fix curly component class reference setup <add> <ide> ### v3.2.0-beta.2 (April 16, 2018) <ide> <ide> - [#16493](https://github.com/emberjs/ember.js/pull/16493) [BUGFIX] Ensure proxies have access to `getOwner(this)`.
1
Javascript
Javascript
remove dead sourcemap code
0d1d7ba2b7e142e9a3b41dcdaa3b1ca52177f5a5
<ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMap.js <del> <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> * <del> * @providesModule SourceMap <del> * @generated <del> * @extern <del> * <del> * This module was generated from `node_modules/source-map` by running <del> * <del> * $ npm install dryice <del> * $ node Makefile.dryice.js <del> * $ cat dist/source-map.js <del> * <del> * and wrapping resulting file into `wrapper` function. <del> * <del> */ <del>/*eslint-disable */ <del> <del>var scope = {}; <del>wrapper.call(scope); <del> <del>module.exports = scope.sourceMap; <del> <del>function wrapper() { <del> <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del> <del>/** <del> * Define a module along with a payload. <del> * @param {string} moduleName Name for the payload <del> * @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec <del> * @param {function} payload Function with (require, exports, module) params <del> */ <del>function define(moduleName, deps, payload) { <del> if (typeof moduleName != "string") { <del> throw new TypeError('Expected string, got: ' + moduleName); <del> } <del> <del> if (arguments.length == 2) { <del> payload = deps; <del> } <del> <del> if (moduleName in define.modules) { <del> throw new Error("Module already defined: " + moduleName); <del> } <del> define.modules[moduleName] = payload; <del>}; <del> <del>/** <del> * The global store of un-instantiated modules <del> */ <del>define.modules = {}; <del> <del> <del>/** <del> * We invoke require() in the context of a Domain so we can have multiple <del> * sets of modules running separate from each other. <del> * This contrasts with JSMs which are singletons, Domains allows us to <del> * optionally load a CommonJS module twice with separate data each time. <del> * Perhaps you want 2 command lines with a different set of commands in each, <del> * for example. <del> */ <del>function Domain() { <del> this.modules = {}; <del> this._currentModule = null; <del>} <del> <del>(function () { <del> <del> /** <del> * Lookup module names and resolve them by calling the definition function if <del> * needed. <del> * There are 2 ways to call this, either with an array of dependencies and a <del> * callback to call when the dependencies are found (which can happen <del> * asynchronously in an in-page context) or with a single string an no callback <del> * where the dependency is resolved synchronously and returned. <del> * The API is designed to be compatible with the CommonJS AMD spec and <del> * RequireJS. <del> * @param {string[]|string} deps A name, or names for the payload <del> * @param {function|undefined} callback Function to call when the dependencies <del> * are resolved <del> * @return {undefined|object} The module required or undefined for <del> * array/callback method <del> */ <del> Domain.prototype.require = function(deps, callback) { <del> if (Array.isArray(deps)) { <del> var params = deps.map(function(dep) { <del> return this.lookup(dep); <del> }, this); <del> if (callback) { <del> callback.apply(null, params); <del> } <del> return undefined; <del> } <del> else { <del> return this.lookup(deps); <del> } <del> }; <del> <del> function normalize(path) { <del> var bits = path.split('/'); <del> var i = 1; <del> while (i < bits.length) { <del> if (bits[i] === '..') { <del> bits.splice(i-1, 1); <del> } else if (bits[i] === '.') { <del> bits.splice(i, 1); <del> } else { <del> i++; <del> } <del> } <del> return bits.join('/'); <del> } <del> <del> function join(a, b) { <del> a = a.trim(); <del> b = b.trim(); <del> if (/^\//.test(b)) { <del> return b; <del> } else { <del> return a.replace(/\/*$/, '/') + b; <del> } <del> } <del> <del> function dirname(path) { <del> var bits = path.split('/'); <del> bits.pop(); <del> return bits.join('/'); <del> } <del> <del> /** <del> * Lookup module names and resolve them by calling the definition function if <del> * needed. <del> * @param {string} moduleName A name for the payload to lookup <del> * @return {object} The module specified by aModuleName or null if not found. <del> */ <del> Domain.prototype.lookup = function(moduleName) { <del> if (/^\./.test(moduleName)) { <del> moduleName = normalize(join(dirname(this._currentModule), moduleName)); <del> } <del> <del> if (moduleName in this.modules) { <del> var module = this.modules[moduleName]; <del> return module; <del> } <del> <del> if (!(moduleName in define.modules)) { <del> throw new Error("Module not defined: " + moduleName); <del> } <del> <del> var module = define.modules[moduleName]; <del> <del> if (typeof module == "function") { <del> var exports = {}; <del> var previousModule = this._currentModule; <del> this._currentModule = moduleName; <del> module(this.require.bind(this), exports, { id: moduleName, uri: "" }); <del> this._currentModule = previousModule; <del> module = exports; <del> } <del> <del> // cache the resulting module object for next time <del> this.modules[moduleName] = module; <del> <del> return module; <del> }; <del> <del>}()); <del> <del>define.Domain = Domain; <del>define.globalDomain = new Domain(); <del>var require = define.globalDomain.require.bind(define.globalDomain); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/source-map-generator', ['require', 'exports', 'module' , 'source-map/base64-vlq', 'source-map/util', 'source-map/array-set'], function(require, exports, module) { <del> <del> var base64VLQ = require('./base64-vlq'); <del> var util = require('./util'); <del> var ArraySet = require('./array-set').ArraySet; <del> <del> /** <del> * An instance of the SourceMapGenerator represents a source map which is <del> * being built incrementally. To create a new one, you must pass an object <del> * with the following properties: <del> * <del> * - file: The filename of the generated source. <del> * - sourceRoot: An optional root for all URLs in this source map. <del> */ <del> function SourceMapGenerator(aArgs) { <del> this._file = util.getArg(aArgs, 'file'); <del> this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); <del> this._sources = new ArraySet(); <del> this._names = new ArraySet(); <del> this._mappings = []; <del> this._sourcesContents = null; <del> } <del> <del> SourceMapGenerator.prototype._version = 3; <del> <del> /** <del> * Creates a new SourceMapGenerator based on a SourceMapConsumer <del> * <del> * @param aSourceMapConsumer The SourceMap. <del> */ <del> SourceMapGenerator.fromSourceMap = <del> function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { <del> var sourceRoot = aSourceMapConsumer.sourceRoot; <del> var generator = new SourceMapGenerator({ <del> file: aSourceMapConsumer.file, <del> sourceRoot: sourceRoot <del> }); <del> aSourceMapConsumer.eachMapping(function (mapping) { <del> var newMapping = { <del> generated: { <del> line: mapping.generatedLine, <del> column: mapping.generatedColumn <del> } <del> }; <del> <del> if (mapping.source) { <del> newMapping.source = mapping.source; <del> if (sourceRoot) { <del> newMapping.source = util.relative(sourceRoot, newMapping.source); <del> } <del> <del> newMapping.original = { <del> line: mapping.originalLine, <del> column: mapping.originalColumn <del> }; <del> <del> if (mapping.name) { <del> newMapping.name = mapping.name; <del> } <del> } <del> <del> generator.addMapping(newMapping); <del> }); <del> aSourceMapConsumer.sources.forEach(function (sourceFile) { <del> var content = aSourceMapConsumer.sourceContentFor(sourceFile); <del> if (content) { <del> generator.setSourceContent(sourceFile, content); <del> } <del> }); <del> return generator; <del> }; <del> <del> /** <del> * Add a single mapping from original source line and column to the generated <del> * source's line and column for this source map being created. The mapping <del> * object should have the following properties: <del> * <del> * - generated: An object with the generated line and column positions. <del> * - original: An object with the original line and column positions. <del> * - source: The original source file (relative to the sourceRoot). <del> * - name: An optional original token name for this mapping. <del> */ <del> SourceMapGenerator.prototype.addMapping = <del> function SourceMapGenerator_addMapping(aArgs) { <del> var generated = util.getArg(aArgs, 'generated'); <del> var original = util.getArg(aArgs, 'original', null); <del> var source = util.getArg(aArgs, 'source', null); <del> var name = util.getArg(aArgs, 'name', null); <del> <del> this._validateMapping(generated, original, source, name); <del> <del> if (source && !this._sources.has(source)) { <del> this._sources.add(source); <del> } <del> <del> if (name && !this._names.has(name)) { <del> this._names.add(name); <del> } <del> <del> this._mappings.push({ <del> generatedLine: generated.line, <del> generatedColumn: generated.column, <del> originalLine: original != null && original.line, <del> originalColumn: original != null && original.column, <del> source: source, <del> name: name <del> }); <del> }; <del> <del> /** <del> * Set the source content for a source file. <del> */ <del> SourceMapGenerator.prototype.setSourceContent = <del> function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { <del> var source = aSourceFile; <del> if (this._sourceRoot) { <del> source = util.relative(this._sourceRoot, source); <del> } <del> <del> if (aSourceContent !== null) { <del> // Add the source content to the _sourcesContents map. <del> // Create a new _sourcesContents map if the property is null. <del> if (!this._sourcesContents) { <del> this._sourcesContents = {}; <del> } <del> this._sourcesContents[util.toSetString(source)] = aSourceContent; <del> } else { <del> // Remove the source file from the _sourcesContents map. <del> // If the _sourcesContents map is empty, set the property to null. <del> delete this._sourcesContents[util.toSetString(source)]; <del> if (Object.keys(this._sourcesContents).length === 0) { <del> this._sourcesContents = null; <del> } <del> } <del> }; <del> <del> /** <del> * Applies the mappings of a sub-source-map for a specific source file to the <del> * source map being generated. Each mapping to the supplied source file is <del> * rewritten using the supplied source map. Note: The resolution for the <del> * resulting mappings is the minimum of this map and the supplied map. <del> * <del> * @param aSourceMapConsumer The source map to be applied. <del> * @param aSourceFile Optional. The filename of the source file. <del> * If omitted, SourceMapConsumer's file property will be used. <del> */ <del> SourceMapGenerator.prototype.applySourceMap = <del> function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { <del> // If aSourceFile is omitted, we will use the file property of the SourceMap <del> if (!aSourceFile) { <del> aSourceFile = aSourceMapConsumer.file; <del> } <del> var sourceRoot = this._sourceRoot; <del> // Make "aSourceFile" relative if an absolute Url is passed. <del> if (sourceRoot) { <del> aSourceFile = util.relative(sourceRoot, aSourceFile); <del> } <del> // Applying the SourceMap can add and remove items from the sources and <del> // the names array. <del> var newSources = new ArraySet(); <del> var newNames = new ArraySet(); <del> <del> // Find mappings for the "aSourceFile" <del> this._mappings.forEach(function (mapping) { <del> if (mapping.source === aSourceFile && mapping.originalLine) { <del> // Check if it can be mapped by the source map, then update the mapping. <del> var original = aSourceMapConsumer.originalPositionFor({ <del> line: mapping.originalLine, <del> column: mapping.originalColumn <del> }); <del> if (original.source !== null) { <del> // Copy mapping <del> if (sourceRoot) { <del> mapping.source = util.relative(sourceRoot, original.source); <del> } else { <del> mapping.source = original.source; <del> } <del> mapping.originalLine = original.line; <del> mapping.originalColumn = original.column; <del> if (original.name !== null && mapping.name !== null) { <del> // Only use the identifier name if it's an identifier <del> // in both SourceMaps <del> mapping.name = original.name; <del> } <del> } <del> } <del> <del> var source = mapping.source; <del> if (source && !newSources.has(source)) { <del> newSources.add(source); <del> } <del> <del> var name = mapping.name; <del> if (name && !newNames.has(name)) { <del> newNames.add(name); <del> } <del> <del> }, this); <del> this._sources = newSources; <del> this._names = newNames; <del> <del> // Copy sourcesContents of applied map. <del> aSourceMapConsumer.sources.forEach(function (sourceFile) { <del> var content = aSourceMapConsumer.sourceContentFor(sourceFile); <del> if (content) { <del> if (sourceRoot) { <del> sourceFile = util.relative(sourceRoot, sourceFile); <del> } <del> this.setSourceContent(sourceFile, content); <del> } <del> }, this); <del> }; <del> <del> /** <del> * A mapping can have one of the three levels of data: <del> * <del> * 1. Just the generated position. <del> * 2. The Generated position, original position, and original source. <del> * 3. Generated and original position, original source, as well as a name <del> * token. <del> * <del> * To maintain consistency, we validate that any new mapping being added falls <del> * in to one of these categories. <del> */ <del> SourceMapGenerator.prototype._validateMapping = <del> function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, <del> aName) { <del> if (aGenerated && 'line' in aGenerated && 'column' in aGenerated <del> && aGenerated.line > 0 && aGenerated.column >= 0 <del> && !aOriginal && !aSource && !aName) { <del> // Case 1. <del> return; <del> } <del> else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated <del> && aOriginal && 'line' in aOriginal && 'column' in aOriginal <del> && aGenerated.line > 0 && aGenerated.column >= 0 <del> && aOriginal.line > 0 && aOriginal.column >= 0 <del> && aSource) { <del> // Cases 2 and 3. <del> return; <del> } <del> else { <del> throw new Error('Invalid mapping: ' + JSON.stringify({ <del> generated: aGenerated, <del> source: aSource, <del> orginal: aOriginal, <del> name: aName <del> })); <del> } <del> }; <del> <del> /** <del> * Serialize the accumulated mappings in to the stream of base 64 VLQs <del> * specified by the source map format. <del> */ <del> SourceMapGenerator.prototype._serializeMappings = <del> function SourceMapGenerator_serializeMappings() { <del> var previousGeneratedColumn = 0; <del> var previousGeneratedLine = 1; <del> var previousOriginalColumn = 0; <del> var previousOriginalLine = 0; <del> var previousName = 0; <del> var previousSource = 0; <del> var result = ''; <del> var mapping; <del> <del> // The mappings must be guaranteed to be in sorted order before we start <del> // serializing them or else the generated line numbers (which are defined <del> // via the ';' separators) will be all messed up. Note: it might be more <del> // performant to maintain the sorting as we insert them, rather than as we <del> // serialize them, but the big O is the same either way. <del> this._mappings.sort(util.compareByGeneratedPositions); <del> <del> for (var i = 0, len = this._mappings.length; i < len; i++) { <del> mapping = this._mappings[i]; <del> <del> if (mapping.generatedLine !== previousGeneratedLine) { <del> previousGeneratedColumn = 0; <del> while (mapping.generatedLine !== previousGeneratedLine) { <del> result += ';'; <del> previousGeneratedLine++; <del> } <del> } <del> else { <del> if (i > 0) { <del> if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { <del> continue; <del> } <del> result += ','; <del> } <del> } <del> <del> result += base64VLQ.encode(mapping.generatedColumn <del> - previousGeneratedColumn); <del> previousGeneratedColumn = mapping.generatedColumn; <del> <del> if (mapping.source) { <del> result += base64VLQ.encode(this._sources.indexOf(mapping.source) <del> - previousSource); <del> previousSource = this._sources.indexOf(mapping.source); <del> <del> // lines are stored 0-based in SourceMap spec version 3 <del> result += base64VLQ.encode(mapping.originalLine - 1 <del> - previousOriginalLine); <del> previousOriginalLine = mapping.originalLine - 1; <del> <del> result += base64VLQ.encode(mapping.originalColumn <del> - previousOriginalColumn); <del> previousOriginalColumn = mapping.originalColumn; <del> <del> if (mapping.name) { <del> result += base64VLQ.encode(this._names.indexOf(mapping.name) <del> - previousName); <del> previousName = this._names.indexOf(mapping.name); <del> } <del> } <del> } <del> <del> return result; <del> }; <del> <del> SourceMapGenerator.prototype._generateSourcesContent = <del> function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { <del> return aSources.map(function (source) { <del> if (!this._sourcesContents) { <del> return null; <del> } <del> if (aSourceRoot) { <del> source = util.relative(aSourceRoot, source); <del> } <del> var key = util.toSetString(source); <del> return Object.prototype.hasOwnProperty.call(this._sourcesContents, <del> key) <del> ? this._sourcesContents[key] <del> : null; <del> }, this); <del> }; <del> <del> /** <del> * Externalize the source map. <del> */ <del> SourceMapGenerator.prototype.toJSON = <del> function SourceMapGenerator_toJSON() { <del> var map = { <del> version: this._version, <del> file: this._file, <del> sources: this._sources.toArray(), <del> names: this._names.toArray(), <del> mappings: this._serializeMappings() <del> }; <del> if (this._sourceRoot) { <del> map.sourceRoot = this._sourceRoot; <del> } <del> if (this._sourcesContents) { <del> map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); <del> } <del> <del> return map; <del> }; <del> <del> /** <del> * Render the source map being generated to a string. <del> */ <del> SourceMapGenerator.prototype.toString = <del> function SourceMapGenerator_toString() { <del> return JSON.stringify(this); <del> }; <del> <del> exports.SourceMapGenerator = SourceMapGenerator; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> * <del> * Based on the Base 64 VLQ implementation in Closure Compiler: <del> * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java <del> * <del> * Copyright 2011 The Closure Compiler Authors. All rights reserved. <del> * Redistribution and use in source and binary forms, with or without <del> * modification, are permitted provided that the following conditions are <del> * met: <del> * <del> * * Redistributions of source code must retain the above copyright <del> * notice, this list of conditions and the following disclaimer. <del> * * Redistributions in binary form must reproduce the above <del> * copyright notice, this list of conditions and the following <del> * disclaimer in the documentation and/or other materials provided <del> * with the distribution. <del> * * Neither the name of Google Inc. nor the names of its <del> * contributors may be used to endorse or promote products derived <del> * from this software without specific prior written permission. <del> * <del> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <del> * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT <del> * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <del> * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT <del> * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, <del> * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT <del> * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, <del> * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY <del> * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT <del> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE <del> * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <del> */ <del>define('source-map/base64-vlq', ['require', 'exports', 'module' , 'source-map/base64'], function(require, exports, module) { <del> <del> var base64 = require('./base64'); <del> <del> // A single base 64 digit can contain 6 bits of data. For the base 64 variable <del> // length quantities we use in the source map spec, the first bit is the sign, <del> // the next four bits are the actual value, and the 6th bit is the <del> // continuation bit. The continuation bit tells us whether there are more <del> // digits in this value following this digit. <del> // <del> // Continuation <del> // | Sign <del> // | | <del> // V V <del> // 101011 <del> <del> var VLQ_BASE_SHIFT = 5; <del> <del> // binary: 100000 <del> var VLQ_BASE = 1 << VLQ_BASE_SHIFT; <del> <del> // binary: 011111 <del> var VLQ_BASE_MASK = VLQ_BASE - 1; <del> <del> // binary: 100000 <del> var VLQ_CONTINUATION_BIT = VLQ_BASE; <del> <del> /** <del> * Converts from a two-complement value to a value where the sign bit is <del> * is placed in the least significant bit. For example, as decimals: <del> * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) <del> * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) <del> */ <del> function toVLQSigned(aValue) { <del> return aValue < 0 <del> ? ((-aValue) << 1) + 1 <del> : (aValue << 1) + 0; <del> } <del> <del> /** <del> * Converts to a two-complement value from a value where the sign bit is <del> * is placed in the least significant bit. For example, as decimals: <del> * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 <del> * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 <del> */ <del> function fromVLQSigned(aValue) { <del> var isNegative = (aValue & 1) === 1; <del> var shifted = aValue >> 1; <del> return isNegative <del> ? -shifted <del> : shifted; <del> } <del> <del> /** <del> * Returns the base 64 VLQ encoded value. <del> */ <del> exports.encode = function base64VLQ_encode(aValue) { <del> var encoded = ""; <del> var digit; <del> <del> var vlq = toVLQSigned(aValue); <del> <del> do { <del> digit = vlq & VLQ_BASE_MASK; <del> vlq >>>= VLQ_BASE_SHIFT; <del> if (vlq > 0) { <del> // There are still more digits in this value, so we must make sure the <del> // continuation bit is marked. <del> digit |= VLQ_CONTINUATION_BIT; <del> } <del> encoded += base64.encode(digit); <del> } while (vlq > 0); <del> <del> return encoded; <del> }; <del> <del> /** <del> * Decodes the next base 64 VLQ value from the given string and returns the <del> * value and the rest of the string. <del> */ <del> exports.decode = function base64VLQ_decode(aStr) { <del> var i = 0; <del> var strLen = aStr.length; <del> var result = 0; <del> var shift = 0; <del> var continuation, digit; <del> <del> do { <del> if (i >= strLen) { <del> throw new Error("Expected more digits in base 64 VLQ value."); <del> } <del> digit = base64.decode(aStr.charAt(i++)); <del> continuation = !!(digit & VLQ_CONTINUATION_BIT); <del> digit &= VLQ_BASE_MASK; <del> result = result + (digit << shift); <del> shift += VLQ_BASE_SHIFT; <del> } while (continuation); <del> <del> return { <del> value: fromVLQSigned(result), <del> rest: aStr.slice(i) <del> }; <del> }; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/base64', ['require', 'exports', 'module' , ], function(require, exports, module) { <del> <del> var charToIntMap = {}; <del> var intToCharMap = {}; <del> <del> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' <del> .split('') <del> .forEach(function (ch, index) { <del> charToIntMap[ch] = index; <del> intToCharMap[index] = ch; <del> }); <del> <del> /** <del> * Encode an integer in the range of 0 to 63 to a single base 64 digit. <del> */ <del> exports.encode = function base64_encode(aNumber) { <del> if (aNumber in intToCharMap) { <del> return intToCharMap[aNumber]; <del> } <del> throw new TypeError("Must be between 0 and 63: " + aNumber); <del> }; <del> <del> /** <del> * Decode a single base 64 digit to an integer. <del> */ <del> exports.decode = function base64_decode(aChar) { <del> if (aChar in charToIntMap) { <del> return charToIntMap[aChar]; <del> } <del> throw new TypeError("Not a valid base 64 digit: " + aChar); <del> }; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/util', ['require', 'exports', 'module' , ], function(require, exports, module) { <del> <del> /** <del> * This is a helper function for getting values from parameter/options <del> * objects. <del> * <del> * @param args The object we are extracting values from <del> * @param name The name of the property we are getting. <del> * @param defaultValue An optional value to return if the property is missing <del> * from the object. If this is not specified and the property is missing, an <del> * error will be thrown. <del> */ <del> function getArg(aArgs, aName, aDefaultValue) { <del> if (aName in aArgs) { <del> return aArgs[aName]; <del> } else if (arguments.length === 3) { <del> return aDefaultValue; <del> } else { <del> throw new Error('"' + aName + '" is a required argument.'); <del> } <del> } <del> exports.getArg = getArg; <del> <del> var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; <del> var dataUrlRegexp = /^data:.+\,.+/; <del> <del> function urlParse(aUrl) { <del> var match = aUrl.match(urlRegexp); <del> if (!match) { <del> return null; <del> } <del> return { <del> scheme: match[1], <del> auth: match[3], <del> host: match[4], <del> port: match[6], <del> path: match[7] <del> }; <del> } <del> exports.urlParse = urlParse; <del> <del> function urlGenerate(aParsedUrl) { <del> var url = aParsedUrl.scheme + "://"; <del> if (aParsedUrl.auth) { <del> url += aParsedUrl.auth + "@" <del> } <del> if (aParsedUrl.host) { <del> url += aParsedUrl.host; <del> } <del> if (aParsedUrl.port) { <del> url += ":" + aParsedUrl.port <del> } <del> if (aParsedUrl.path) { <del> url += aParsedUrl.path; <del> } <del> return url; <del> } <del> exports.urlGenerate = urlGenerate; <del> <del> function join(aRoot, aPath) { <del> var url; <del> <del> if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { <del> return aPath; <del> } <del> <del> if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { <del> url.path = aPath; <del> return urlGenerate(url); <del> } <del> <del> return aRoot.replace(/\/$/, '') + '/' + aPath; <del> } <del> exports.join = join; <del> <del> /** <del> * Because behavior goes wacky when you set `__proto__` on objects, we <del> * have to prefix all the strings in our set with an arbitrary character. <del> * <del> * See https://github.com/mozilla/source-map/pull/31 and <del> * https://github.com/mozilla/source-map/issues/30 <del> * <del> * @param String aStr <del> */ <del> function toSetString(aStr) { <del> return '$' + aStr; <del> } <del> exports.toSetString = toSetString; <del> <del> function fromSetString(aStr) { <del> return aStr.substr(1); <del> } <del> exports.fromSetString = fromSetString; <del> <del> function relative(aRoot, aPath) { <del> aRoot = aRoot.replace(/\/$/, ''); <del> <del> var url = urlParse(aRoot); <del> if (aPath.charAt(0) == "/" && url && url.path == "/") { <del> return aPath.slice(1); <del> } <del> <del> return aPath.indexOf(aRoot + '/') === 0 <del> ? aPath.substr(aRoot.length + 1) <del> : aPath; <del> } <del> exports.relative = relative; <del> <del> function strcmp(aStr1, aStr2) { <del> var s1 = aStr1 || ""; <del> var s2 = aStr2 || ""; <del> return (s1 > s2) - (s1 < s2); <del> } <del> <del> /** <del> * Comparator between two mappings where the original positions are compared. <del> * <del> * Optionally pass in `true` as `onlyCompareGenerated` to consider two <del> * mappings with the same original source/line/column, but different generated <del> * line and column the same. Useful when searching for a mapping with a <del> * stubbed out mapping. <del> */ <del> function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { <del> var cmp; <del> <del> cmp = strcmp(mappingA.source, mappingB.source); <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.originalLine - mappingB.originalLine; <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.originalColumn - mappingB.originalColumn; <del> if (cmp || onlyCompareOriginal) { <del> return cmp; <del> } <del> <del> cmp = strcmp(mappingA.name, mappingB.name); <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.generatedLine - mappingB.generatedLine; <del> if (cmp) { <del> return cmp; <del> } <del> <del> return mappingA.generatedColumn - mappingB.generatedColumn; <del> }; <del> exports.compareByOriginalPositions = compareByOriginalPositions; <del> <del> /** <del> * Comparator between two mappings where the generated positions are <del> * compared. <del> * <del> * Optionally pass in `true` as `onlyCompareGenerated` to consider two <del> * mappings with the same generated line and column, but different <del> * source/name/original line and column the same. Useful when searching for a <del> * mapping with a stubbed out mapping. <del> */ <del> function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { <del> var cmp; <del> <del> cmp = mappingA.generatedLine - mappingB.generatedLine; <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.generatedColumn - mappingB.generatedColumn; <del> if (cmp || onlyCompareGenerated) { <del> return cmp; <del> } <del> <del> cmp = strcmp(mappingA.source, mappingB.source); <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.originalLine - mappingB.originalLine; <del> if (cmp) { <del> return cmp; <del> } <del> <del> cmp = mappingA.originalColumn - mappingB.originalColumn; <del> if (cmp) { <del> return cmp; <del> } <del> <del> return strcmp(mappingA.name, mappingB.name); <del> }; <del> exports.compareByGeneratedPositions = compareByGeneratedPositions; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/array-set', ['require', 'exports', 'module' , 'source-map/util'], function(require, exports, module) { <del> <del> var util = require('./util'); <del> <del> /** <del> * A data structure which is a combination of an array and a set. Adding a new <del> * member is O(1), testing for membership is O(1), and finding the index of an <del> * element is O(1). Removing elements from the set is not supported. Only <del> * strings are supported for membership. <del> */ <del> function ArraySet() { <del> this._array = []; <del> this._set = {}; <del> } <del> <del> /** <del> * Static method for creating ArraySet instances from an existing array. <del> */ <del> ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { <del> var set = new ArraySet(); <del> for (var i = 0, len = aArray.length; i < len; i++) { <del> set.add(aArray[i], aAllowDuplicates); <del> } <del> return set; <del> }; <del> <del> /** <del> * Add the given string to this set. <del> * <del> * @param String aStr <del> */ <del> ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { <del> var isDuplicate = this.has(aStr); <del> var idx = this._array.length; <del> if (!isDuplicate || aAllowDuplicates) { <del> this._array.push(aStr); <del> } <del> if (!isDuplicate) { <del> this._set[util.toSetString(aStr)] = idx; <del> } <del> }; <del> <del> /** <del> * Is the given string a member of this set? <del> * <del> * @param String aStr <del> */ <del> ArraySet.prototype.has = function ArraySet_has(aStr) { <del> return Object.prototype.hasOwnProperty.call(this._set, <del> util.toSetString(aStr)); <del> }; <del> <del> /** <del> * What is the index of the given string in the array? <del> * <del> * @param String aStr <del> */ <del> ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { <del> if (this.has(aStr)) { <del> return this._set[util.toSetString(aStr)]; <del> } <del> throw new Error('"' + aStr + '" is not in the set.'); <del> }; <del> <del> /** <del> * What is the element at the given index? <del> * <del> * @param Number aIdx <del> */ <del> ArraySet.prototype.at = function ArraySet_at(aIdx) { <del> if (aIdx >= 0 && aIdx < this._array.length) { <del> return this._array[aIdx]; <del> } <del> throw new Error('No element indexed by ' + aIdx); <del> }; <del> <del> /** <del> * Returns the array representation of this set (which has the proper indices <del> * indicated by indexOf). Note that this is a copy of the internal array used <del> * for storing the members so that no one can mess with internal state. <del> */ <del> ArraySet.prototype.toArray = function ArraySet_toArray() { <del> return this._array.slice(); <del> }; <del> <del> exports.ArraySet = ArraySet; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/source-map-consumer', ['require', 'exports', 'module' , 'source-map/util', 'source-map/binary-search', 'source-map/array-set', 'source-map/base64-vlq'], function(require, exports, module) { <del> <del> var util = require('./util'); <del> var binarySearch = require('./binary-search'); <del> var ArraySet = require('./array-set').ArraySet; <del> var base64VLQ = require('./base64-vlq'); <del> <del> /** <del> * A SourceMapConsumer instance represents a parsed source map which we can <del> * query for information about the original file positions by giving it a file <del> * position in the generated source. <del> * <del> * The only parameter is the raw source map (either as a JSON string, or <del> * already parsed to an object). According to the spec, source maps have the <del> * following attributes: <del> * <del> * - version: Which version of the source map spec this map is following. <del> * - sources: An array of URLs to the original source files. <del> * - names: An array of identifiers which can be referenced by individual mappings. <del> * - sourceRoot: Optional. The URL root from which all sources are relative. <del> * - sourcesContent: Optional. An array of contents of the original source files. <del> * - mappings: A string of base64 VLQs which contain the actual mappings. <del> * - file: The generated file this source map is associated with. <del> * <del> * Here is an example source map, taken from the source map spec[0]: <del> * <del> * { <del> * version : 3, <del> * file: "out.js", <del> * sourceRoot : "", <del> * sources: ["foo.js", "bar.js"], <del> * names: ["src", "maps", "are", "fun"], <del> * mappings: "AA,AB;;ABCDE;" <del> * } <del> * <del> * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# <del> */ <del> function SourceMapConsumer(aSourceMap) { <del> var sourceMap = aSourceMap; <del> if (typeof aSourceMap === 'string') { <del> sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); <del> } <del> <del> var version = util.getArg(sourceMap, 'version'); <del> var sources = util.getArg(sourceMap, 'sources'); <del> // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which <del> // requires the array) to play nice here. <del> var names = util.getArg(sourceMap, 'names', []); <del> var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); <del> var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); <del> var mappings = util.getArg(sourceMap, 'mappings'); <del> var file = util.getArg(sourceMap, 'file', null); <del> <del> // Once again, Sass deviates from the spec and supplies the version as a <del> // string rather than a number, so we use loose equality checking here. <del> if (version != this._version) { <del> throw new Error('Unsupported version: ' + version); <del> } <del> <del> // Pass `true` below to allow duplicate names and sources. While source maps <del> // are intended to be compressed and deduplicated, the TypeScript compiler <del> // sometimes generates source maps with duplicates in them. See Github issue <del> // #72 and bugzil.la/889492. <del> this._names = ArraySet.fromArray(names, true); <del> this._sources = ArraySet.fromArray(sources, true); <del> <del> this.sourceRoot = sourceRoot; <del> this.sourcesContent = sourcesContent; <del> this._mappings = mappings; <del> this.file = file; <del> } <del> <del> /** <del> * Create a SourceMapConsumer from a SourceMapGenerator. <del> * <del> * @param SourceMapGenerator aSourceMap <del> * The source map that will be consumed. <del> * @returns SourceMapConsumer <del> */ <del> SourceMapConsumer.fromSourceMap = <del> function SourceMapConsumer_fromSourceMap(aSourceMap) { <del> var smc = Object.create(SourceMapConsumer.prototype); <del> <del> smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); <del> smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); <del> smc.sourceRoot = aSourceMap._sourceRoot; <del> smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), <del> smc.sourceRoot); <del> smc.file = aSourceMap._file; <del> <del> smc.__generatedMappings = aSourceMap._mappings.slice() <del> .sort(util.compareByGeneratedPositions); <del> smc.__originalMappings = aSourceMap._mappings.slice() <del> .sort(util.compareByOriginalPositions); <del> <del> return smc; <del> }; <del> <del> /** <del> * The version of the source mapping spec that we are consuming. <del> */ <del> SourceMapConsumer.prototype._version = 3; <del> <del> /** <del> * The list of original sources. <del> */ <del> Object.defineProperty(SourceMapConsumer.prototype, 'sources', { <del> get: function () { <del> return this._sources.toArray().map(function (s) { <del> return this.sourceRoot ? util.join(this.sourceRoot, s) : s; <del> }, this); <del> } <del> }); <del> <del> // `__generatedMappings` and `__originalMappings` are arrays that hold the <del> // parsed mapping coordinates from the source map's "mappings" attribute. They <del> // are lazily instantiated, accessed via the `_generatedMappings` and <del> // `_originalMappings` getters respectively, and we only parse the mappings <del> // and create these arrays once queried for a source location. We jump through <del> // these hoops because there can be many thousands of mappings, and parsing <del> // them is expensive, so we only want to do it if we must. <del> // <del> // Each object in the arrays is of the form: <del> // <del> // { <del> // generatedLine: The line number in the generated code, <del> // generatedColumn: The column number in the generated code, <del> // source: The path to the original source file that generated this <del> // chunk of code, <del> // originalLine: The line number in the original source that <del> // corresponds to this chunk of generated code, <del> // originalColumn: The column number in the original source that <del> // corresponds to this chunk of generated code, <del> // name: The name of the original symbol which generated this chunk of <del> // code. <del> // } <del> // <del> // All properties except for `generatedLine` and `generatedColumn` can be <del> // `null`. <del> // <del> // `_generatedMappings` is ordered by the generated positions. <del> // <del> // `_originalMappings` is ordered by the original positions. <del> <del> SourceMapConsumer.prototype.__generatedMappings = null; <del> Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { <del> get: function () { <del> if (!this.__generatedMappings) { <del> this.__generatedMappings = []; <del> this.__originalMappings = []; <del> this._parseMappings(this._mappings, this.sourceRoot); <del> } <del> <del> return this.__generatedMappings; <del> } <del> }); <del> <del> SourceMapConsumer.prototype.__originalMappings = null; <del> Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { <del> get: function () { <del> if (!this.__originalMappings) { <del> this.__generatedMappings = []; <del> this.__originalMappings = []; <del> this._parseMappings(this._mappings, this.sourceRoot); <del> } <del> <del> return this.__originalMappings; <del> } <del> }); <del> <del> /** <del> * Parse the mappings in a string in to a data structure which we can easily <del> * query (the ordered arrays in the `this.__generatedMappings` and <del> * `this.__originalMappings` properties). <del> */ <del> SourceMapConsumer.prototype._parseMappings = <del> function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { <del> var generatedLine = 1; <del> var previousGeneratedColumn = 0; <del> var previousOriginalLine = 0; <del> var previousOriginalColumn = 0; <del> var previousSource = 0; <del> var previousName = 0; <del> var mappingSeparator = /^[,;]/; <del> var str = aStr; <del> var mapping; <del> var temp; <del> <del> while (str.length > 0) { <del> if (str.charAt(0) === ';') { <del> generatedLine++; <del> str = str.slice(1); <del> previousGeneratedColumn = 0; <del> } <del> else if (str.charAt(0) === ',') { <del> str = str.slice(1); <del> } <del> else { <del> mapping = {}; <del> mapping.generatedLine = generatedLine; <del> <del> // Generated column. <del> temp = base64VLQ.decode(str); <del> mapping.generatedColumn = previousGeneratedColumn + temp.value; <del> previousGeneratedColumn = mapping.generatedColumn; <del> str = temp.rest; <del> <del> if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { <del> // Original source. <del> temp = base64VLQ.decode(str); <del> mapping.source = this._sources.at(previousSource + temp.value); <del> previousSource += temp.value; <del> str = temp.rest; <del> if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { <del> throw new Error('Found a source, but no line and column'); <del> } <del> <del> // Original line. <del> temp = base64VLQ.decode(str); <del> mapping.originalLine = previousOriginalLine + temp.value; <del> previousOriginalLine = mapping.originalLine; <del> // Lines are stored 0-based <del> mapping.originalLine += 1; <del> str = temp.rest; <del> if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { <del> throw new Error('Found a source and line, but no column'); <del> } <del> <del> // Original column. <del> temp = base64VLQ.decode(str); <del> mapping.originalColumn = previousOriginalColumn + temp.value; <del> previousOriginalColumn = mapping.originalColumn; <del> str = temp.rest; <del> <del> if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { <del> // Original name. <del> temp = base64VLQ.decode(str); <del> mapping.name = this._names.at(previousName + temp.value); <del> previousName += temp.value; <del> str = temp.rest; <del> } <del> } <del> <del> this.__generatedMappings.push(mapping); <del> if (typeof mapping.originalLine === 'number') { <del> this.__originalMappings.push(mapping); <del> } <del> } <del> } <del> <del> this.__originalMappings.sort(util.compareByOriginalPositions); <del> }; <del> <del> /** <del> * Find the mapping that best matches the hypothetical "needle" mapping that <del> * we are searching for in the given "haystack" of mappings. <del> */ <del> SourceMapConsumer.prototype._findMapping = <del> function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, <del> aColumnName, aComparator) { <del> // To return the position we are searching for, we must first find the <del> // mapping for the given position and then return the opposite position it <del> // points to. Because the mappings are sorted, we can use binary search to <del> // find the best mapping. <del> <del> if (aNeedle[aLineName] <= 0) { <del> throw new TypeError('Line must be greater than or equal to 1, got ' <del> + aNeedle[aLineName]); <del> } <del> if (aNeedle[aColumnName] < 0) { <del> throw new TypeError('Column must be greater than or equal to 0, got ' <del> + aNeedle[aColumnName]); <del> } <del> <del> return binarySearch.search(aNeedle, aMappings, aComparator); <del> }; <del> <del> /** <del> * Returns the original source, line, and column information for the generated <del> * source's line and column positions provided. The only argument is an object <del> * with the following properties: <del> * <del> * - line: The line number in the generated source. <del> * - column: The column number in the generated source. <del> * <del> * and an object is returned with the following properties: <del> * <del> * - source: The original source file, or null. <del> * - line: The line number in the original source, or null. <del> * - column: The column number in the original source, or null. <del> * - name: The original identifier, or null. <del> */ <del> SourceMapConsumer.prototype.originalPositionFor = <del> function SourceMapConsumer_originalPositionFor(aArgs) { <del> var needle = { <del> generatedLine: util.getArg(aArgs, 'line'), <del> generatedColumn: util.getArg(aArgs, 'column') <del> }; <del> <del> var mapping = this._findMapping(needle, <del> this._generatedMappings, <del> "generatedLine", <del> "generatedColumn", <del> util.compareByGeneratedPositions); <del> <del> if (mapping) { <del> var source = util.getArg(mapping, 'source', null); <del> if (source && this.sourceRoot) { <del> source = util.join(this.sourceRoot, source); <del> } <del> return { <del> source: source, <del> line: util.getArg(mapping, 'originalLine', null), <del> column: util.getArg(mapping, 'originalColumn', null), <del> name: util.getArg(mapping, 'name', null) <del> }; <del> } <del> <del> return { <del> source: null, <del> line: null, <del> column: null, <del> name: null <del> }; <del> }; <del> <del> /** <del> * Returns the original source content. The only argument is the url of the <del> * original source file. Returns null if no original source content is <del> * available. <del> */ <del> SourceMapConsumer.prototype.sourceContentFor = <del> function SourceMapConsumer_sourceContentFor(aSource) { <del> if (!this.sourcesContent) { <del> return null; <del> } <del> <del> if (this.sourceRoot) { <del> aSource = util.relative(this.sourceRoot, aSource); <del> } <del> <del> if (this._sources.has(aSource)) { <del> return this.sourcesContent[this._sources.indexOf(aSource)]; <del> } <del> <del> var url; <del> if (this.sourceRoot <del> && (url = util.urlParse(this.sourceRoot))) { <del> // XXX: file:// URIs and absolute paths lead to unexpected behavior for <del> // many users. We can help them out when they expect file:// URIs to <del> // behave like it would if they were running a local HTTP server. See <del> // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. <del> var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); <del> if (url.scheme == "file" <del> && this._sources.has(fileUriAbsPath)) { <del> return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] <del> } <del> <del> if ((!url.path || url.path == "/") <del> && this._sources.has("/" + aSource)) { <del> return this.sourcesContent[this._sources.indexOf("/" + aSource)]; <del> } <del> } <del> <del> throw new Error('"' + aSource + '" is not in the SourceMap.'); <del> }; <del> <del> /** <del> * Returns the generated line and column information for the original source, <del> * line, and column positions provided. The only argument is an object with <del> * the following properties: <del> * <del> * - source: The filename of the original source. <del> * - line: The line number in the original source. <del> * - column: The column number in the original source. <del> * <del> * and an object is returned with the following properties: <del> * <del> * - line: The line number in the generated source, or null. <del> * - column: The column number in the generated source, or null. <del> */ <del> SourceMapConsumer.prototype.generatedPositionFor = <del> function SourceMapConsumer_generatedPositionFor(aArgs) { <del> var needle = { <del> source: util.getArg(aArgs, 'source'), <del> originalLine: util.getArg(aArgs, 'line'), <del> originalColumn: util.getArg(aArgs, 'column') <del> }; <del> <del> if (this.sourceRoot) { <del> needle.source = util.relative(this.sourceRoot, needle.source); <del> } <del> <del> var mapping = this._findMapping(needle, <del> this._originalMappings, <del> "originalLine", <del> "originalColumn", <del> util.compareByOriginalPositions); <del> <del> if (mapping) { <del> return { <del> line: util.getArg(mapping, 'generatedLine', null), <del> column: util.getArg(mapping, 'generatedColumn', null) <del> }; <del> } <del> <del> return { <del> line: null, <del> column: null <del> }; <del> }; <del> <del> SourceMapConsumer.GENERATED_ORDER = 1; <del> SourceMapConsumer.ORIGINAL_ORDER = 2; <del> <del> /** <del> * Iterate over each mapping between an original source/line/column and a <del> * generated line/column in this source map. <del> * <del> * @param Function aCallback <del> * The function that is called with each mapping. <del> * @param Object aContext <del> * Optional. If specified, this object will be the value of `this` every <del> * time that `aCallback` is called. <del> * @param aOrder <del> * Either `SourceMapConsumer.GENERATED_ORDER` or <del> * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to <del> * iterate over the mappings sorted by the generated file's line/column <del> * order or the original's source/line/column order, respectively. Defaults to <del> * `SourceMapConsumer.GENERATED_ORDER`. <del> */ <del> SourceMapConsumer.prototype.eachMapping = <del> function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { <del> var context = aContext || null; <del> var order = aOrder || SourceMapConsumer.GENERATED_ORDER; <del> <del> var mappings; <del> switch (order) { <del> case SourceMapConsumer.GENERATED_ORDER: <del> mappings = this._generatedMappings; <del> break; <del> case SourceMapConsumer.ORIGINAL_ORDER: <del> mappings = this._originalMappings; <del> break; <del> default: <del> throw new Error("Unknown order of iteration."); <del> } <del> <del> var sourceRoot = this.sourceRoot; <del> mappings.map(function (mapping) { <del> var source = mapping.source; <del> if (source && sourceRoot) { <del> source = util.join(sourceRoot, source); <del> } <del> return { <del> source: source, <del> generatedLine: mapping.generatedLine, <del> generatedColumn: mapping.generatedColumn, <del> originalLine: mapping.originalLine, <del> originalColumn: mapping.originalColumn, <del> name: mapping.name <del> }; <del> }).forEach(aCallback, context); <del> }; <del> <del> exports.SourceMapConsumer = SourceMapConsumer; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/binary-search', ['require', 'exports', 'module' , ], function(require, exports, module) { <del> <del> /** <del> * Recursive implementation of binary search. <del> * <del> * @param aLow Indices here and lower do not contain the needle. <del> * @param aHigh Indices here and higher do not contain the needle. <del> * @param aNeedle The element being searched for. <del> * @param aHaystack The non-empty array being searched. <del> * @param aCompare Function which takes two elements and returns -1, 0, or 1. <del> */ <del> function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { <del> // This function terminates when one of the following is true: <del> // <del> // 1. We find the exact element we are looking for. <del> // <del> // 2. We did not find the exact element, but we can return the next <del> // closest element that is less than that element. <del> // <del> // 3. We did not find the exact element, and there is no next-closest <del> // element which is less than the one we are searching for, so we <del> // return null. <del> var mid = Math.floor((aHigh - aLow) / 2) + aLow; <del> var cmp = aCompare(aNeedle, aHaystack[mid], true); <del> if (cmp === 0) { <del> // Found the element we are looking for. <del> return aHaystack[mid]; <del> } <del> else if (cmp > 0) { <del> // aHaystack[mid] is greater than our needle. <del> if (aHigh - mid > 1) { <del> // The element is in the upper half. <del> return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); <del> } <del> // We did not find an exact match, return the next closest one <del> // (termination case 2). <del> return aHaystack[mid]; <del> } <del> else { <del> // aHaystack[mid] is less than our needle. <del> if (mid - aLow > 1) { <del> // The element is in the lower half. <del> return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); <del> } <del> // The exact needle element was not found in this haystack. Determine if <del> // we are in termination case (2) or (3) and return the appropriate thing. <del> return aLow < 0 <del> ? null <del> : aHaystack[aLow]; <del> } <del> } <del> <del> /** <del> * This is an implementation of binary search which will always try and return <del> * the next lowest value checked if there is no exact hit. This is because <del> * mappings between original and generated line/col pairs are single points, <del> * and there is an implicit region between each of them, so a miss just means <del> * that you aren't on the very start of a region. <del> * <del> * @param aNeedle The element you are looking for. <del> * @param aHaystack The array that is being searched. <del> * @param aCompare A function which takes the needle and an element in the <del> * array and returns -1, 0, or 1 depending on whether the needle is less <del> * than, equal to, or greater than the element, respectively. <del> */ <del> exports.search = function search(aNeedle, aHaystack, aCompare) { <del> return aHaystack.length > 0 <del> ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) <del> : null; <del> }; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/* <del> * Copyright 2011 Mozilla Foundation and contributors <del> * Licensed under the New BSD license. See LICENSE or: <del> * http://opensource.org/licenses/BSD-3-Clause <del> */ <del>define('source-map/source-node', ['require', 'exports', 'module' , 'source-map/source-map-generator', 'source-map/util'], function(require, exports, module) { <del> <del> var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; <del> var util = require('./util'); <del> <del> /** <del> * SourceNodes provide a way to abstract over interpolating/concatenating <del> * snippets of generated JavaScript source code while maintaining the line and <del> * column information associated with the original source code. <del> * <del> * @param aLine The original line number. <del> * @param aColumn The original column number. <del> * @param aSource The original source's filename. <del> * @param aChunks Optional. An array of strings which are snippets of <del> * generated JS, or other SourceNodes. <del> * @param aName The original identifier. <del> */ <del> function SourceNode(aLine, aColumn, aSource, aChunks, aName) { <del> this.children = []; <del> this.sourceContents = {}; <del> this.line = aLine === undefined ? null : aLine; <del> this.column = aColumn === undefined ? null : aColumn; <del> this.source = aSource === undefined ? null : aSource; <del> this.name = aName === undefined ? null : aName; <del> if (aChunks != null) this.add(aChunks); <del> } <del> <del> /** <del> * Creates a SourceNode from generated code and a SourceMapConsumer. <del> * <del> * @param aGeneratedCode The generated code <del> * @param aSourceMapConsumer The SourceMap for the generated code <del> */ <del> SourceNode.fromStringWithSourceMap = <del> function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { <del> // The SourceNode we want to fill with the generated code <del> // and the SourceMap <del> var node = new SourceNode(); <del> <del> // The generated code <del> // Processed fragments are removed from this array. <del> var remainingLines = aGeneratedCode.split('\n'); <del> <del> // We need to remember the position of "remainingLines" <del> var lastGeneratedLine = 1, lastGeneratedColumn = 0; <del> <del> // The generate SourceNodes we need a code range. <del> // To extract it current and last mapping is used. <del> // Here we store the last mapping. <del> var lastMapping = null; <del> <del> aSourceMapConsumer.eachMapping(function (mapping) { <del> if (lastMapping === null) { <del> // We add the generated code until the first mapping <del> // to the SourceNode without any mapping. <del> // Each line is added as separate string. <del> while (lastGeneratedLine < mapping.generatedLine) { <del> node.add(remainingLines.shift() + "\n"); <del> lastGeneratedLine++; <del> } <del> if (lastGeneratedColumn < mapping.generatedColumn) { <del> var nextLine = remainingLines[0]; <del> node.add(nextLine.substr(0, mapping.generatedColumn)); <del> remainingLines[0] = nextLine.substr(mapping.generatedColumn); <del> lastGeneratedColumn = mapping.generatedColumn; <del> } <del> } else { <del> // We add the code from "lastMapping" to "mapping": <del> // First check if there is a new line in between. <del> if (lastGeneratedLine < mapping.generatedLine) { <del> var code = ""; <del> // Associate full lines with "lastMapping" <del> do { <del> code += remainingLines.shift() + "\n"; <del> lastGeneratedLine++; <del> lastGeneratedColumn = 0; <del> } while (lastGeneratedLine < mapping.generatedLine); <del> // When we reached the correct line, we add code until we <del> // reach the correct column too. <del> if (lastGeneratedColumn < mapping.generatedColumn) { <del> var nextLine = remainingLines[0]; <del> code += nextLine.substr(0, mapping.generatedColumn); <del> remainingLines[0] = nextLine.substr(mapping.generatedColumn); <del> lastGeneratedColumn = mapping.generatedColumn; <del> } <del> // Create the SourceNode. <del> addMappingWithCode(lastMapping, code); <del> } else { <del> // There is no new line in between. <del> // Associate the code between "lastGeneratedColumn" and <del> // "mapping.generatedColumn" with "lastMapping" <del> var nextLine = remainingLines[0]; <del> var code = nextLine.substr(0, mapping.generatedColumn - <del> lastGeneratedColumn); <del> remainingLines[0] = nextLine.substr(mapping.generatedColumn - <del> lastGeneratedColumn); <del> lastGeneratedColumn = mapping.generatedColumn; <del> addMappingWithCode(lastMapping, code); <del> } <del> } <del> lastMapping = mapping; <del> }, this); <del> // We have processed all mappings. <del> // Associate the remaining code in the current line with "lastMapping" <del> // and add the remaining lines without any mapping <del> addMappingWithCode(lastMapping, remainingLines.join("\n")); <del> <del> // Copy sourcesContent into SourceNode <del> aSourceMapConsumer.sources.forEach(function (sourceFile) { <del> var content = aSourceMapConsumer.sourceContentFor(sourceFile); <del> if (content) { <del> node.setSourceContent(sourceFile, content); <del> } <del> }); <del> <del> return node; <del> <del> function addMappingWithCode(mapping, code) { <del> if (mapping === null || mapping.source === undefined) { <del> node.add(code); <del> } else { <del> node.add(new SourceNode(mapping.originalLine, <del> mapping.originalColumn, <del> mapping.source, <del> code, <del> mapping.name)); <del> } <del> } <del> }; <del> <del> /** <del> * Add a chunk of generated JS to this source node. <del> * <del> * @param aChunk A string snippet of generated JS code, another instance of <del> * SourceNode, or an array where each member is one of those things. <del> */ <del> SourceNode.prototype.add = function SourceNode_add(aChunk) { <del> if (Array.isArray(aChunk)) { <del> aChunk.forEach(function (chunk) { <del> this.add(chunk); <del> }, this); <del> } <del> else if (aChunk instanceof SourceNode || typeof aChunk === "string") { <del> if (aChunk) { <del> this.children.push(aChunk); <del> } <del> } <del> else { <del> throw new TypeError( <del> "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk <del> ); <del> } <del> return this; <del> }; <del> <del> /** <del> * Add a chunk of generated JS to the beginning of this source node. <del> * <del> * @param aChunk A string snippet of generated JS code, another instance of <del> * SourceNode, or an array where each member is one of those things. <del> */ <del> SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { <del> if (Array.isArray(aChunk)) { <del> for (var i = aChunk.length-1; i >= 0; i--) { <del> this.prepend(aChunk[i]); <del> } <del> } <del> else if (aChunk instanceof SourceNode || typeof aChunk === "string") { <del> this.children.unshift(aChunk); <del> } <del> else { <del> throw new TypeError( <del> "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk <del> ); <del> } <del> return this; <del> }; <del> <del> /** <del> * Walk over the tree of JS snippets in this node and its children. The <del> * walking function is called once for each snippet of JS and is passed that <del> * snippet and the its original associated source's line/column location. <del> * <del> * @param aFn The traversal function. <del> */ <del> SourceNode.prototype.walk = function SourceNode_walk(aFn) { <del> var chunk; <del> for (var i = 0, len = this.children.length; i < len; i++) { <del> chunk = this.children[i]; <del> if (chunk instanceof SourceNode) { <del> chunk.walk(aFn); <del> } <del> else { <del> if (chunk !== '') { <del> aFn(chunk, { source: this.source, <del> line: this.line, <del> column: this.column, <del> name: this.name }); <del> } <del> } <del> } <del> }; <del> <del> /** <del> * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between <del> * each of `this.children`. <del> * <del> * @param aSep The separator. <del> */ <del> SourceNode.prototype.join = function SourceNode_join(aSep) { <del> var newChildren; <del> var i; <del> var len = this.children.length; <del> if (len > 0) { <del> newChildren = []; <del> for (i = 0; i < len-1; i++) { <del> newChildren.push(this.children[i]); <del> newChildren.push(aSep); <del> } <del> newChildren.push(this.children[i]); <del> this.children = newChildren; <del> } <del> return this; <del> }; <del> <del> /** <del> * Call String.prototype.replace on the very right-most source snippet. Useful <del> * for trimming whitespace from the end of a source node, etc. <del> * <del> * @param aPattern The pattern to replace. <del> * @param aReplacement The thing to replace the pattern with. <del> */ <del> SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { <del> var lastChild = this.children[this.children.length - 1]; <del> if (lastChild instanceof SourceNode) { <del> lastChild.replaceRight(aPattern, aReplacement); <del> } <del> else if (typeof lastChild === 'string') { <del> this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); <del> } <del> else { <del> this.children.push(''.replace(aPattern, aReplacement)); <del> } <del> return this; <del> }; <del> <del> /** <del> * Set the source content for a source file. This will be added to the SourceMapGenerator <del> * in the sourcesContent field. <del> * <del> * @param aSourceFile The filename of the source file <del> * @param aSourceContent The content of the source file <del> */ <del> SourceNode.prototype.setSourceContent = <del> function SourceNode_setSourceContent(aSourceFile, aSourceContent) { <del> this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; <del> }; <del> <del> /** <del> * Walk over the tree of SourceNodes. The walking function is called for each <del> * source file content and is passed the filename and source content. <del> * <del> * @param aFn The traversal function. <del> */ <del> SourceNode.prototype.walkSourceContents = <del> function SourceNode_walkSourceContents(aFn) { <del> for (var i = 0, len = this.children.length; i < len; i++) { <del> if (this.children[i] instanceof SourceNode) { <del> this.children[i].walkSourceContents(aFn); <del> } <del> } <del> <del> var sources = Object.keys(this.sourceContents); <del> for (var i = 0, len = sources.length; i < len; i++) { <del> aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); <del> } <del> }; <del> <del> /** <del> * Return the string representation of this source node. Walks over the tree <del> * and concatenates all the various snippets together to one string. <del> */ <del> SourceNode.prototype.toString = function SourceNode_toString() { <del> var str = ""; <del> this.walk(function (chunk) { <del> str += chunk; <del> }); <del> return str; <del> }; <del> <del> /** <del> * Returns the string representation of this source node along with a source <del> * map. <del> */ <del> SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { <del> var generated = { <del> code: "", <del> line: 1, <del> column: 0 <del> }; <del> var map = new SourceMapGenerator(aArgs); <del> var sourceMappingActive = false; <del> var lastOriginalSource = null; <del> var lastOriginalLine = null; <del> var lastOriginalColumn = null; <del> var lastOriginalName = null; <del> this.walk(function (chunk, original) { <del> generated.code += chunk; <del> if (original.source !== null <del> && original.line !== null <del> && original.column !== null) { <del> if(lastOriginalSource !== original.source <del> || lastOriginalLine !== original.line <del> || lastOriginalColumn !== original.column <del> || lastOriginalName !== original.name) { <del> map.addMapping({ <del> source: original.source, <del> original: { <del> line: original.line, <del> column: original.column <del> }, <del> generated: { <del> line: generated.line, <del> column: generated.column <del> }, <del> name: original.name <del> }); <del> } <del> lastOriginalSource = original.source; <del> lastOriginalLine = original.line; <del> lastOriginalColumn = original.column; <del> lastOriginalName = original.name; <del> sourceMappingActive = true; <del> } else if (sourceMappingActive) { <del> map.addMapping({ <del> generated: { <del> line: generated.line, <del> column: generated.column <del> } <del> }); <del> lastOriginalSource = null; <del> sourceMappingActive = false; <del> } <del> chunk.split('').forEach(function (ch) { <del> if (ch === '\n') { <del> generated.line++; <del> generated.column = 0; <del> } else { <del> generated.column++; <del> } <del> }); <del> }); <del> this.walkSourceContents(function (sourceFile, sourceContent) { <del> map.setSourceContent(sourceFile, sourceContent); <del> }); <del> <del> return { code: generated.code, map: map }; <del> }; <del> <del> exports.SourceNode = SourceNode; <del> <del>}); <del>/* -*- Mode: js; js-indent-level: 2; -*- */ <del>/////////////////////////////////////////////////////////////////////////////// <del> <del>this.sourceMap = { <del> SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer, <del> SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator, <del> SourceNode: require('source-map/source-node').SourceNode <del>}; <del> <del>} <ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMapsCache.js <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> * <del> * @providesModule SourceMapsCache <del> */ <del>'use strict'; <del> <del>const getObjectValues = require('getObjectValues'); <del>const SourceMapsUtils = require('SourceMapsUtils'); <del> <del>const sourceMapsCache = {}; <del> <del>const SourceMapsCache = { <del> mainSourceMapID: 'main', <del> <del> fetch({text, url, fullSourceMappingURL}) { <del> const sourceMappingURL = fullSourceMappingURL <del> ? fullSourceMappingURL <del> : SourceMapsUtils.extractSourceMapURL({text, url}); <del> <del> sourceMapsCache[sourceMappingURL] = SourceMapsUtils.fetchSourceMap( <del> sourceMappingURL <del> ); <del> }, <del> <del> getSourceMaps() { <del> fetchMainSourceMap(); <del> return Promise.all(getObjectValues(sourceMapsCache)); <del> }, <del>}; <del> <del>function fetchMainSourceMap() { <del> if (!sourceMapsCache[SourceMapsCache.mainSourceMapID]) { <del> sourceMapsCache[SourceMapsCache.mainSourceMapID] = <del> SourceMapsUtils.fetchMainSourceMap(); <del> } <del>} <del> <del>module.exports = SourceMapsCache; <ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMapsUtils.js <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> * <del> * @providesModule SourceMapsUtils <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>const Promise = require('Promise'); <del>const NativeModules = require('NativeModules'); <del>const SourceMapConsumer = require('SourceMap').SourceMapConsumer; <del>const SourceMapURL = require('./source-map-url'); <del> <del>const RCTSourceCode = NativeModules.SourceCode; <del>const RCTNetworking = NativeModules.Networking; <del> <del>const SourceMapsUtils = { <del> fetchMainSourceMap(): Promise { <del> return SourceMapsUtils._getMainSourceMapURL().then(url => <del> SourceMapsUtils.fetchSourceMap(url) <del> ); <del> }, <del> <del> fetchSourceMap(sourceMappingURL: string): Promise { <del> return fetch(sourceMappingURL) <del> .then(response => response.text()) <del> .then(map => new SourceMapConsumer(map)); <del> }, <del> <del> extractSourceMapURL(data: ({url?:string, text?:string, fullSourceMappingURL?:string})): ?string { <del> const url = data.url; <del> const text = data.text; <del> const fullSourceMappingURL = data.fullSourceMappingURL; <del> if (fullSourceMappingURL) { <del> return fullSourceMappingURL; <del> } <del> const mapURL = SourceMapURL.getFrom(text); <del> if (!mapURL) { <del> return null; <del> } <del> if (!url) { <del> return null; <del> } <del> const baseURLs = url.match(/(.+:\/\/.*?)\//); <del> if (!baseURLs || baseURLs.length < 2) { <del> return null; <del> } <del> return baseURLs[1] + mapURL; <del> }, <del> <del> _getMainSourceMapURL(): Promise { <del> if (global.RAW_SOURCE_MAP) { <del> return Promise.resolve(global.RAW_SOURCE_MAP); <del> } <del> <del> if (!RCTSourceCode) { <del> return Promise.reject(new Error('RCTSourceCode module is not available')); <del> } <del> <del> if (!RCTNetworking) { <del> // Used internally by fetch <del> return Promise.reject(new Error('RCTNetworking module is not available')); <del> } <del> <del> const scriptText = RCTSourceCode.getScriptText(); <del> if (scriptText) { <del> return scriptText <del> .then(SourceMapsUtils.extractSourceMapURL) <del> .then((url) => { <del> if (url === null) { <del> return Promise.reject(new Error('No source map URL found. May be running from bundled file.')); <del> } <del> return Promise.resolve(url); <del> }); <del> } else { <del> // Running in mock-config mode <del> return Promise.reject(new Error('Couldn\'t fetch script text')); <del> } <del> }, <del>}; <del> <del>module.exports = SourceMapsUtils; <ide><path>Libraries/Utilities/HMRClient.js <ide> Error: ${e.message}` <ide> RCTExceptionsManager && RCTExceptionsManager.dismissRedbox && RCTExceptionsManager.dismissRedbox(); <ide> } <ide> <del> let serverHost; <del> <del> if (Platform.OS === 'android') { <del> serverHost = require('NativeModules').AndroidConstants.ServerHost; <del> } else { <del> serverHost = port ? `${host}:${port}` : host; <del> } <del> <ide> modules.forEach(({id, code}, i) => { <ide> code = code + '\n\n' + sourceMappingURLs[i]; <ide> <del> require('SourceMapsCache').fetch({ <del> text: code, <del> url: `http://${serverHost}${sourceURLs[i]}`, <del> sourceMappingURL: sourceMappingURLs[i], <del> }); <del> <ide> // on JSC we need to inject from native for sourcemaps to work <ide> // (Safari doesn't support `sourceMappingURL` nor any variant when <ide> // evaluating code) but on Chrome we can simply use eval
4
Go
Go
fix bug in link-local unmarshalling
69c2f8d6dbf2ba1608188ec1b4fb6685a8c12aba
<ide><path>libnetwork/endpoint_info.go <ide> func (epi *endpointInterface) UnmarshalJSON(b []byte) error { <ide> } <ide> } <ide> if v, ok := epMap["llAddrs"]; ok { <del> list := v.([]string) <add> list := v.([]interface{}) <ide> epi.llAddrs = make([]*net.IPNet, 0, len(list)) <ide> for _, llS := range list { <del> ll, err := types.ParseCIDR(llS) <add> ll, err := types.ParseCIDR(llS.(string)) <ide> if err != nil { <del> return types.InternalErrorf("failed to decode endpoint interface link-local address (%s) after json unmarshal: %v", llS, err) <add> return types.InternalErrorf("failed to decode endpoint interface link-local address (%v) after json unmarshal: %v", llS, err) <ide> } <ide> epi.llAddrs = append(epi.llAddrs, ll) <ide> } <ide><path>libnetwork/libnetwork_internal_test.go <ide> func TestEndpointMarshalling(t *testing.T) { <ide> } <ide> nw6.IP = ip <ide> <add> var lla []*net.IPNet <add> for _, nw := range []string{"169.254.0.1/16", "169.254.1.1/16", "169.254.2.2/16"} { <add> ll, _ := types.ParseCIDR(nw) <add> lla = append(lla, ll) <add> } <add> <ide> e := &endpoint{ <ide> name: "Bau", <ide> id: "efghijklmno", <ide> func TestEndpointMarshalling(t *testing.T) { <ide> dstPrefix: "eth", <ide> v4PoolID: "poolpool", <ide> v6PoolID: "poolv6", <add> llAddrs: lla, <ide> }, <ide> } <ide> <ide> func compareEndpointInterface(a, b *endpointInterface) bool { <ide> return false <ide> } <ide> return a.srcName == b.srcName && a.dstPrefix == b.dstPrefix && a.v4PoolID == b.v4PoolID && a.v6PoolID == b.v6PoolID && <del> types.CompareIPNet(a.addr, b.addr) && types.CompareIPNet(a.addrv6, b.addrv6) <add> types.CompareIPNet(a.addr, b.addr) && types.CompareIPNet(a.addrv6, b.addrv6) && compareNwLists(a.llAddrs, b.llAddrs) <ide> } <ide> <ide> func compareIpamConfList(listA, listB []*IpamConf) bool { <ide> func compareAddresses(a, b map[string]*net.IPNet) bool { <ide> return true <ide> } <ide> <add>func compareNwLists(a, b []*net.IPNet) bool { <add> if len(a) != len(b) { <add> return false <add> } <add> for k := range a { <add> if !types.CompareIPNet(a[k], b[k]) { <add> return false <add> } <add> } <add> return true <add>} <add> <ide> func TestAuxAddresses(t *testing.T) { <ide> c, err := New() <ide> if err != nil {
2
Text
Text
preserve the right order for model.compile
d7d1ee54a5fa98ef5612224b6167529ff506e1c1
<ide><path>docs/sources/models.md <ide> model = Sequential() <ide> model.add(Dense(2, init='uniform', input_dim=64)) <ide> model.add(Activation('softmax')) <ide> <del>model.compile(loss='mse', optimizer='sgd') <add>model.compile(optimizer='sgd', loss='mse') <ide> <ide> ''' <ide> Demonstration of verbose modes 1 and 2 <ide> graph.add_node(Dense(4), name='dense3', input='dense1') <ide> graph.add_output(name='output1', input='dense2') <ide> graph.add_output(name='output2', input='dense3') <ide> <del>graph.compile('rmsprop', {'output1':'mse', 'output2':'mse'}) <add>graph.compile(optimizer='rmsprop', loss={'output1':'mse', 'output2':'mse'}) <ide> history = graph.fit({'input':X_train, 'output1':y_train, 'output2':y2_train}, nb_epoch=10) <ide> <ide> ``` <ide> graph.add_node(Dense(16), name='dense1', input='input1') <ide> graph.add_node(Dense(4), name='dense2', input='input2') <ide> graph.add_node(Dense(4), name='dense3', input='dense1') <ide> graph.add_output(name='output', inputs=['dense2', 'dense3'], merge_mode='sum') <del>graph.compile('rmsprop', {'output':'mse'}) <add>graph.compile(optimizer='rmsprop', loss={'output':'mse'}) <ide> <ide> history = graph.fit({'input1':X_train, 'input2':X2_train, 'output':y_train}, nb_epoch=10) <ide> predictions = graph.predict({'input1':X_test, 'input2':X2_test}) # {'output':...}
1
Ruby
Ruby
add bottle_prefix method
af4247429b7b1352592bca28238d8bb61194454a
<ide><path>Library/Homebrew/formula.rb <ide> def var; HOMEBREW_PREFIX+'var' end <ide> def bash_completion; prefix+'etc/bash_completion.d' end <ide> def zsh_completion; share+'zsh/site-functions' end <ide> <add> # for storing etc, var files for later copying from bottles <add> def bottle_prefix; prefix+'.bottle' end <add> <ide> # override this to provide a plist <ide> def plist; nil; end <ide> alias :startup_plist :plist
1
Text
Text
add issue templates
e122c80c9ddb17e4dad2b6225da2ed9e95e986c7
<ide><path>.github/ISSUE_TEMPLATE/---bug-report.md <add>--- <add>name: "\U0001F41E Bug Report" <add>about: Report a reproducible bug <add>title: '' <add>labels: bug <add>assignees: '' <add> <add>--- <add> <add><!-- Click "Preview" for a more readable version -- <add> <add>Please read and follow the instructions before submitting an issue: <add> <add>- Read all our documentation, especially the [README](https://github.com/axios/axios/blob/master/README.md). It may contain information that helps you solve your issue. <add>- Ensure your issue isn't already [reported](https://github.com/axios/axios/issues?utf8=%E2%9C%93&q=is%3Aissue). <add>- If you aren't sure that the issue is caused by Axios or you just need help, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/axios) or [our chat](https://gitter.im/mzabriskie/axios). <add>- If you're reporting a bug, ensure it isn't already fixed in the latest Axios version. <add> <add>⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️ <add>--> <add> <add>**Describe the bug** <add>A clear and concise description of what the bug is. **If your problem is not a bug, please file under Support or Usage Question** <add> <add>**To Reproduce** <add>Code snippet to reproduce, ideally that will work by pasting into something like https://npm.runkit.com/axios, a hosted solution, or a repository that illustrates the issue. **If your problem is not reproducible, please file under Support or Usage Question** <add> <add>```js <add>// Example code here <add>``` <add> <add>**Expected behavior** <add>A clear and concise description of what you expected to happen. <add> <add>**Environment:** <add> - Axios Version [e.g. 0.18.0] <add> - OS: [e.g. iOS 12.1.0, OSX 10.13.4] <add> - Browser [e.g. Chrome, Safari] <add> - Browser Version [e.g. 22] <add> - Additional Library Versions [e.g. React 16.7, React Native 0.58.0] <add> <add>**Additional context/Screenshots** <add>Add any other context about the problem here. If applicable, add screenshots to help explain. <ide><path>.github/ISSUE_TEMPLATE/---documentation.md <add>--- <add>name: "\U0001F4DA Documentation" <add>about: Report an error or area that needs clarification <add>title: '' <add>labels: documentation <add>assignees: '' <add> <add>--- <add> <add><!-- Click "Preview" for a more readable version -- <add> <add>If you found an area that needs clarification, feel free to open a PR or list the section/content that could be improved below <add> <add>⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️ <add>--> <add> <add>**Section/Content To Improve** <add>Quote or link to section <add> <add>**Suggested Improvement** <add>Identify what is confusing or incorrect and what could make it better <add> <add>**Relevant File(s)**: [e.g. README.md] <ide><path>.github/ISSUE_TEMPLATE/---support-or-usage-question.md <add>--- <add>name: "\U0001F914 Support or Usage Question" <add>about: Get help using Axios <add>title: '' <add>labels: question <add>assignees: '' <add> <add>--- <add> <add><!-- Click "Preview" for a more readable version -- <add> <add>Please read and follow the instructions before submitting an issue: <add> <add>- Read all our documentation, especially the [README](https://github.com/axios/axios/blob/master/README.md). It may contain information that helps you solve your issue. <add>- Ensure your issue isn't already [reported](https://github.com/axios/axios/issues?utf8=%E2%9C%93&q=is%3Aissue). <add>- If you aren't sure that the issue is caused by Axios or you just need help, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/axios) or [our chat](https://gitter.im/mzabriskie/axios). <add>- If you're reporting a bug, ensure it isn't already fixed in the latest Axios version. <add> <add>⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️ <add>--> <add> <add>**Describe the issue** <add>A clear and concise description of what the issue is. <add> <add>**Example Code** <add>Code snippet to illustrate your question <add> <add>```js <add>// Example code here <add>``` <add> <add>**Expected behavior, if applicable** <add>A clear and concise description of what you expected to happen. <add> <add>**Environment:** <add> - Axios Version [e.g. 0.18.0] <add> - OS: [e.g. iOS 12.1.0, OSX 10.13.4] <add> - Browser [e.g. Chrome, Safari] <add> - Browser Version [e.g. 22] <add> - Additional Library Versions [e.g. React 16.7, React Native 0.58.0] <add> <add>**Additional context/Screenshots** <add>Add any other context about the problem here. If applicable, add screenshots to help explain. <ide><path>.github/ISSUE_TEMPLATE/--feature-request.md <add>--- <add>name: "✨ Feature Request" <add>about: Suggest an idea or feature <add>title: '' <add>labels: feature <add>assignees: '' <add> <add>--- <add> <add>**Is your feature request related to a problem? Please describe.** <add>A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] <add> <add>**Describe the solution you'd like** <add>A clear and concise description of what you want to happen. <add> <add>**Describe alternatives you've considered** <add>A clear and concise description of any alternative solutions or features you've considered. <add> <add>**Additional context** <add>Add any other context or screenshots about the feature request here.
4
Text
Text
change the name and some elementary bits
194bfa2bc060a24c64b0377a62508c089cc735c8
<ide><path>README.md <del># SproutCore <add># Amber.js <ide> <del>SproutCore is a JavaScript framework that does all of the heavy lifting that you'd normally have to do by hand. There are tasks that are common to every web app; SproutCore does those things for you, so you can focus on building killer features and UI. <add>Amber.js (formerly SproutCore 2.0) is a JavaScript framework that does all of the heavy lifting that you'd normally have to do by hand. There are tasks that are common to every web app; Amber.js does those things for you, so you can focus on building killer features and UI. <ide> <del>These are the three features that make SproutCore a joy to use: <add>These are the three features that make Amber.js a joy to use: <ide> <ide> 1. Bindings <ide> 2. Computed properties <ide> 3. Auto-updating templates <ide> <add>Amber.js has strong roots in SproutCore; you can read more about its evolution in [the Amber.js launch announcement](http://yehudakatz.com/2011/12/08/announcing-amber-js/). <add> <ide> ## Bindings <ide> <del>Use bindings to keep properties between two different objects in sync. You just declare a binding once, and SproutCore will make sure changes get propagated in either direction. <add>Use bindings to keep properties between two different objects in sync. You just declare a binding once, and Amber.js will make sure changes get propagated in either direction. <ide> <ide> Here's how you create a binding between two objects: <ide> <ide> Hopefully you can see how all three of these powerful tools work together: start <ide> <ide> # Getting Started <ide> <del>For new users, we recommend downloading the [SproutCore Starter Kit](https://github.com/sproutcore/starter-kit/downloads), which includes everything you need to get started. <add>For new users, we recommend downloading the [Amber.js Starter Kit](https://github.com/amberjs/starter-kit/downloads), which includes everything you need to get started. <ide> <del>We also recommend that you check out the [annotated Todos example](http://annotated-todos.strobeapp.com/), which shows you the best practices for architecting an MVC-based web application. <add>We also recommend that you check out the [annotated Todos example](http://annotated-todos.strobeapp.com/), which shows you the best practices for architecting an MVC-based web application. You can also [browse or fork the code on Github](https://github.com/amberjs/todos). <ide> <ide> The [SproutCore Guides are available](http://guides.sproutcore20.com/) for SproutCore 2.0. If you find an error, please [fork the guides on GitHub](https://github.com/sproutcore/sproutguides/tree/v2.0) and submit a pull request. (Note that 2.0 guides are on the `v2.0` branch.) <ide> <ide> To learn more about what we're up to, follow [@sproutcore on Twitter](http://twitter.com/sproutcore), [subscribe to the blog](http://blog.sproutcore.com), or [read the original SproutCore 2.0 announcement](http://blog.sproutcore.com/announcing-sproutcore-2-0/). <ide> <del># Building SproutCore 2.0 <add># Building Amber.js <ide> <del>1. Run `rake` to build SproutCore. Two builds will be placed in the `dist/` directory. <del> * `sproutcore.js` and `sproutcore.min.js` - unminified and minified <del> builds of SproutCore 2.0 <add>1. Run `rake` to build Amber.js. Two builds will be placed in the `dist/` directory. <add> * `amber.js` and `amber.min.js` - unminified and minified <add> builds of Amber.js <ide> <ide> If you are building under Linux, you will need a JavaScript runtime for <ide> minification. You can either install nodejs or `gem install <ide> therubyracer`. <ide> <ide> 5. Then visit: `http://localhost:4020/assets/spade-qunit/index.html?package=PACKAGE_NAME`. Replace `PACKAGE_NAME` with the name of the package you want to run. For example: <ide> <del> * [SproutCore Runtime](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-runtime) <del> * [SproutCore Views](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-views) <del> * [SproutCore Handlebars](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-handlebars) <add> * [Amber.js Runtime](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-runtime) <add> * [Amber.js Views](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-views) <add> * [Amber.js Handlebars](http://localhost:4020/assets/spade-qunit/index.html?package=sproutcore-handlebars) <ide> <ide> To run multiple packages, you can separate them with commas. For <ide> example, to run all of the unit tests together:
1
Javascript
Javascript
add test case
f71468b8e1e683942bb75c8415a149ff8947407b
<ide><path>test/configCases/graph/issue-11770/a.js <add>import { val } from "./shared"; <add> <add>it("should have the correct value", () => { <add> expect(val).toBe(84); <add>}); <ide><path>test/configCases/graph/issue-11770/b.js <add>import { other } from "./shared"; <add> <add>it("should have the correct value", () => { <add> expect(other).toBe("other"); <add>}); <ide><path>test/configCases/graph/issue-11770/dep.js <add>export default 42; <ide><path>test/configCases/graph/issue-11770/shared.js <add>import value from "./dep"; <add> <add>const derived = value; <add> <add>export const val = /*#__PURE__*/ (() => value + derived)(); <add> <add>export const other = "other"; <ide><path>test/configCases/graph/issue-11770/test.config.js <add>module.exports = { <add> findBundle: function (i, options) { <add> return ["shared.js", "a.js", "b.js"]; <add> } <add>}; <ide><path>test/configCases/graph/issue-11770/webpack.config.js <add>module.exports = { <add> entry: { <add> a: "./a", <add> b: "./b" <add> }, <add> target: "web", <add> output: { <add> filename: "[name].js" <add> }, <add> optimization: { <add> usedExports: true, <add> splitChunks: { <add> cacheGroups: { <add> forceMerge: { <add> test: /shared/, <add> enforce: true, <add> name: "shared", <add> chunks: "all" <add> } <add> } <add> } <add> } <add>};
6
Javascript
Javascript
fix default nexttick triggerasyncid
0fd4c73e5cda23dfb5b8e54dc11e07e547e9d576
<ide><path>lib/async_hooks.js <ide> function emitInitS(asyncId, type, triggerAsyncId, resource) { <ide> <ide> // This can run after the early return check b/c running this function <ide> // manually means that the embedder must have used initTriggerId(). <del> if (!Number.isSafeInteger(triggerAsyncId)) { <del> if (triggerAsyncId !== undefined) <del> resource = triggerAsyncId; <add> if (triggerAsyncId === null) { <ide> triggerAsyncId = initTriggerId(); <ide> } <ide> <ide><path>lib/internal/process/next_tick.js <ide> function setupNextTick() { <ide> // The needed emit*() functions. <ide> const { emitInit, emitBefore, emitAfter, emitDestroy } = async_hooks; <ide> // Grab the constants necessary for working with internal arrays. <del> const { kInit, kBefore, kAfter, kDestroy, kAsyncUidCntr, kInitTriggerId } = <add> const { kInit, kBefore, kAfter, kDestroy, kAsyncUidCntr } = <ide> async_wrap.constants; <ide> const { async_id_symbol, trigger_id_symbol } = async_wrap; <ide> var nextTickQueue = new NextTickQueue(); <ide> function setupNextTick() { <ide> if (process._exiting) <ide> return; <ide> <add> if (triggerAsyncId === null) { <add> triggerAsyncId = async_hooks.initTriggerId(); <add> } <add> <ide> var args; <ide> switch (arguments.length) { <ide> case 2: break; <ide> function setupNextTick() { <ide> ++tickInfo[kLength]; <ide> if (async_hook_fields[kInit] > 0) <ide> emitInit(asyncId, 'TickObject', triggerAsyncId, obj); <del> <del> // The call to initTriggerId() was skipped, so clear kInitTriggerId. <del> async_uid_fields[kInitTriggerId] = 0; <ide> } <ide> } <ide><path>test/async-hooks/init-hooks.js <ide> class ActivityCollector { <ide> this._logid = logid; <ide> this._logtype = logtype; <ide> <del> // register event handlers if provided <add> // Register event handlers if provided <ide> this.oninit = typeof oninit === 'function' ? oninit : noop; <ide> this.onbefore = typeof onbefore === 'function' ? onbefore : noop; <ide> this.onafter = typeof onafter === 'function' ? onafter : noop; <ide> this.ondestroy = typeof ondestroy === 'function' ? ondestroy : noop; <ide> <del> // create the hook with which we'll collect activity data <add> // Create the hook with which we'll collect activity data <ide> this._asyncHook = async_hooks.createHook({ <ide> init: this._init.bind(this), <ide> before: this._before.bind(this), <ide> class ActivityCollector { <ide> '\nExpected "destroy" to be called after "after"'); <ide> } <ide> } <add> if (!a.handleIsObject) { <add> v('No resource object\n' + activityString(a) + <add> '\nExpected "init" to be called with a resource object'); <add> } <ide> } <ide> if (violations.length) { <del> console.error(violations.join('\n')); <del> assert.fail(violations.length, 0, `Failed sanity checks: ${violations}`); <add> console.error(violations.join('\n\n') + '\n'); <add> assert.fail(violations.length, 0, <add> `${violations.length} failed sanity checks`); <ide> } <ide> } <ide> <ide> class ActivityCollector { <ide> _getActivity(uid, hook) { <ide> const h = this._activities.get(uid); <ide> if (!h) { <del> // if we allowed handles without init we ignore any further life time <add> // If we allowed handles without init we ignore any further life time <ide> // events this makes sense for a few tests in which we enable some hooks <ide> // later <ide> if (this._allowNoInit) { <del> const stub = { uid, type: 'Unknown' }; <add> const stub = { uid, type: 'Unknown', handleIsObject: true }; <ide> this._activities.set(uid, stub); <ide> return stub; <ide> } else { <ide> class ActivityCollector { <ide> } <ide> <ide> _init(uid, type, triggerAsyncId, handle) { <del> const activity = { uid, type, triggerAsyncId }; <add> const activity = { <add> uid, <add> type, <add> triggerAsyncId, <add> // In some cases (e.g. Timeout) the handle is a function, thus the usual <add> // `typeof handle === 'object' && handle !== null` check can't be used. <add> handleIsObject: handle instanceof Object <add> }; <ide> this._stamp(activity, 'init'); <ide> this._activities.set(uid, activity); <ide> this._maybeLog(uid, type, 'init'); <ide><path>test/async-hooks/test-emit-init.js <ide> initHooks({ <ide> }) <ide> }).enable(); <ide> <del>async_hooks.emitInit(expectedId, expectedType, expectedResource); <add>async_hooks.emitInit(expectedId, expectedType, null, expectedResource); <ide><path>test/async-hooks/test-internal-nexttick-default-trigger.js <add>'use strict'; <add>// Flags: --expose-internals <add>const common = require('../common'); <add> <add>// This tests ensures that the triggerId of both the internal and external <add>// nexTick function sets the triggerAsyncId correctly. <add> <add>const assert = require('assert'); <add>const async_hooks = require('async_hooks'); <add>const initHooks = require('./init-hooks'); <add>const { checkInvocations } = require('./hook-checks'); <add>const internal = require('internal/process/next_tick'); <add> <add>const hooks = initHooks(); <add>hooks.enable(); <add> <add>const rootAsyncId = async_hooks.executionAsyncId(); <add> <add>// public <add>process.nextTick(common.mustCall(function() { <add> assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); <add>})); <add> <add>// internal default <add>internal.nextTick(null, common.mustCall(function() { <add> assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); <add>})); <add> <add>// internal <add>internal.nextTick(rootAsyncId + 1, common.mustCall(function() { <add> assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId + 1); <add>})); <add> <add>process.on('exit', function() { <add> hooks.sanityCheck(); <add> <add> const as = hooks.activitiesOfTypes('TickObject'); <add> checkInvocations(as[0], { <add> init: 1, before: 1, after: 1, destroy: 1 <add> }, 'when process exits'); <add> checkInvocations(as[1], { <add> init: 1, before: 1, after: 1, destroy: 1 <add> }, 'when process exits'); <add> checkInvocations(as[2], { <add> init: 1, before: 1, after: 1, destroy: 1 <add> }, 'when process exits'); <add>});
5
Javascript
Javascript
fix dimensions tests in testswarm
13f3cd1611d7905c6fadcf2f8a533096b347a6ad
<ide><path>test/unit/dimensions.js <ide> QUnit.test( "outerWidth/Height for table cells and textarea with border-box in I <ide> $firstTh = jQuery( "<th style='width: 200px;padding: 5px' />" ), <ide> $secondTh = jQuery( "<th style='width: 190px;padding: 5px' />" ), <ide> $thirdTh = jQuery( "<th style='width: 180px;padding: 5px' />" ), <del> $td = jQuery( "<td style='height: 20px;padding: 5px;border: 1px solid'>text</td>" ), <add> // Support Firefox 63, Edge 16-17, Android 8, iOS 7-11 <add> // These browsers completely ignore the border-box and height settings <add> // The computed height is instead just line-height + border <add> // Either way, what we're doing in css.js is correct <add> $td = jQuery( "<td style='height: 20px;padding: 5px;border: 1px solid;line-height:18px'>text</td>" ), <ide> $tbody = jQuery( "<tbody />" ).appendTo( $table ), <ide> $textarea = jQuery( "<textarea style='height: 0;padding: 2px;border: 1px solid;box-sizing: border-box' />" ).appendTo( "#qunit-fixture" ); <ide> jQuery( "<tr />" ).appendTo( $thead ).append( $firstTh );
1
Text
Text
fix copy & paste error in api docs
0fddc0447cbc0fee237a76e5b4128d893156490b
<ide><path>website/docs/api/language.md <ide> Evaluate a pipeline's components. <ide> <ide> <Infobox variant="warning" title="Changed in v3.0"> <ide> <del>The `Language.update` method now takes a batch of [`Example`](/api/example) <add>The `Language.evaluate` method now takes a batch of [`Example`](/api/example) <ide> objects instead of tuples of `Doc` and `GoldParse` objects. <ide> <ide> </Infobox>
1
Python
Python
add a regression test for gh-11216
324e3045c3e5a4c262e9d231663b7228593c8675
<ide><path>numpy/lib/tests/test_arraypad.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <add>import pytest <add> <ide> import numpy as np <del>from numpy.testing import (assert_array_equal, assert_raises, assert_allclose,) <add>from numpy.testing import (assert_array_equal, assert_raises, assert_allclose, <add> assert_equal) <ide> from numpy.lib import pad <ide> <ide> <ide> def test_check_mean_2(self): <ide> ) <ide> assert_array_equal(a, b) <ide> <add> @pytest.mark.parametrize("mode", [ <add> pytest.param("mean", marks=pytest.mark.xfail(reason="gh-11216")), <add> "median", <add> "minimum", <add> "maximum" <add> ]) <add> def test_same_prepend_append(self, mode): <add> """ Test that appended and prepended values are equal """ <add> # This test is constructed to trigger floating point rounding errors in <add> # a way that caused gh-11216 for mode=='mean' <add> a = np.array([-1, 2, -1]) + np.array([0, 1e-12, 0], dtype=np.float64) <add> a = np.pad(a, (1, 1), mode) <add> assert_equal(a[0], a[-1]) <add> <ide> <ide> class TestConstant(object): <ide> def test_check_constant(self):
1
Go
Go
allow receiving of signals from 'docker kill'
4822fb1e2423d88cdf0ad5d039b8fd3274b05401
<ide><path>profiles/apparmor/apparmor.go <ide> var ( <ide> type profileData struct { <ide> // Name is profile name. <ide> Name string <add> // DaemonProfile is the profile name of our daemon. <add> DaemonProfile string <ide> // Imports defines the apparmor functions to import, before defining the profile. <ide> Imports []string <ide> // InnerImports defines the apparmor functions to import in the profile. <ide> func InstallDefault(name string) error { <ide> Name: name, <ide> } <ide> <add> // Figure out the daemon profile. <add> currentProfile, err := ioutil.ReadFile("/proc/self/attr/current") <add> if err != nil { <add> // If we couldn't get the daemon profile, assume we are running <add> // unconfined which is generally the default. <add> currentProfile = nil <add> } <add> daemonProfile := string(currentProfile) <add> // Normally profiles are suffixed by " (enforcing)" or similar. AppArmor <add> // profiles cannot contain spaces so this doesn't restrict daemon profile <add> // names. <add> if parts := strings.SplitN(daemonProfile, " ", 2); len(parts) >= 1 { <add> daemonProfile = parts[0] <add> } <add> if daemonProfile == "" { <add> daemonProfile = "unconfined" <add> } <add> p.DaemonProfile = daemonProfile <add> <ide> // Install to a temporary directory. <ide> f, err := ioutil.TempFile("", name) <ide> if err != nil { <ide><path>profiles/apparmor/template.go <ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) { <ide> capability, <ide> file, <ide> umount, <add>{{if ge .Version 208096}} <add>{{/* Allow 'docker kill' to actually send signals to container processes. */}} <add> signal (receive) peer={{.DaemonProfile}}, <add>{{/* Allow container processes to send signals amongst themselves. */}} <add> signal (send,receive) peer={{.Name}}, <add>{{end}} <ide> <ide> deny @{PROC}/* w, # deny write for all files directly in /proc (not in a subdir) <ide> # deny write to files not in /proc/<number>/** or /proc/sys/**
2
Javascript
Javascript
simplify lazy constant loading
c11f3f8b0fa4378e0080f29a52bbe4c77070bea9
<ide><path>src/node.js <ide> process.assert = function (x, msg) { <ide> <ide> var writeError = process.binding('stdio').writeError; <ide> <add> <add>// lazy loaded. <add>var constants; <add>function lazyConstants () { <add> if (!constants) constants = process.binding("constants"); <add> return constants; <add>} <add> <add> <ide> // nextTick() <ide> <ide> var nextTickQueue = []; <ide> var module = (function () { <ide> try { <ide> process.mainModule.load(process.argv[1]); <ide> } catch (e) { <del> if (!constants) constants = process.binding("constants"); <del> if (e.errno == constants.ENOENT) { <add> if (e.errno == lazyConstants().ENOENT) { <ide> console.error("Cannot load '%s'", process.argv[1]); <ide> process.exit(1); <ide> } else { <ide> var module = (function () { <ide> // process.addListener. <ide> var events = module.requireNative('events'); <ide> <del>var constants; // lazy loaded. <del> <ide> // Signal Handlers <ide> (function() { <ide> var signalWatchers = {}; <ide> var addListener = process.addListener; <ide> var removeListener = process.removeListener; <ide> <ide> function isSignal (event) { <del> if (!constants) constants = process.binding("constants"); <del> return event.slice(0, 3) === 'SIG' && constants[event]; <add> return event.slice(0, 3) === 'SIG' && lazyConstants()[event]; <ide> } <ide> <ide> // Wrap addListener for the special signal types <ide> process.on = process.addListener = function (type, listener) { <ide> var ret = addListener.apply(this, arguments); <ide> if (isSignal(type)) { <ide> if (!signalWatchers.hasOwnProperty(type)) { <del> if (!constants) constants = process.binding("constants"); <ide> var b = process.binding('signal_watcher'); <del> var w = new b.SignalWatcher(constants[type]); <add> var w = new b.SignalWatcher(lazyConstants()[type]); <ide> w.callback = function () { process.emit(type); }; <ide> signalWatchers[type] = w; <ide> w.start(); <ide> process.exit = function (code) { <ide> }; <ide> <ide> process.kill = function (pid, sig) { <del> if (!constants) constants = process.binding("constants"); <ide> sig = sig || 'SIGTERM'; <del> if (!constants[sig]) throw new Error("Unknown signal: " + sig); <del> process._kill(pid, constants[sig]); <add> if (!lazyConstants()[sig]) throw new Error("Unknown signal: " + sig); <add> process._kill(pid, lazyConstants()[sig]); <ide> }; <ide> <ide>
1
Python
Python
rename spacy.analysis to spacy.pipe_analysis
4465cad6c5bc188f628dc92183e2e855e26bcfc4
<ide><path>spacy/language.py <ide> from .vocab import Vocab <ide> from .lemmatizer import Lemmatizer <ide> from .lookups import Lookups <del>from .analysis import analyze_pipes, analyze_all_pipes, validate_attrs <del>from .analysis import count_pipeline_interdependencies <add>from .pipe_analysis import analyze_pipes, analyze_all_pipes, validate_attrs <add>from .pipe_analysis import count_pipeline_interdependencies <ide> from .gold import Example <ide> from .scorer import Scorer <ide> from .util import link_vectors_to_models, create_default_optimizer, registry <ide> def create_pipe(self, name, config=dict()): <ide> <ide> # check whether we have a proper model config, or load a default one <ide> if "model" in factory_cfg and not isinstance(factory_cfg["model"], dict): <del> warnings.warn(Warnings.W099.format(type=type(factory_cfg["model"]), pipe=name)) <add> warnings.warn( <add> Warnings.W099.format(type=type(factory_cfg["model"]), pipe=name) <add> ) <ide> <ide> # refer to the model configuration in the cfg settings for this component <ide> if "model" in factory_cfg: <ide> self.config[name] = {"model": factory_cfg["model"]} <ide> <ide> # create all objects in the config <del> factory_cfg = registry.make_from_config({"config": factory_cfg}, validate=True)["config"] <add> factory_cfg = registry.make_from_config({"config": factory_cfg}, validate=True)[ <add> "config" <add> ] <ide> model = factory_cfg.get("model", None) <ide> if model is not None: <ide> del factory_cfg["model"] <ide> def select_pipes(self, disable=None, enable=None): <ide> def make_doc(self, text): <ide> return self.tokenizer(text) <ide> <del> def update(self, examples, dummy=None, *, drop=0.0, sgd=None, losses=None, component_cfg=None): <add> def update( <add> self, <add> examples, <add> dummy=None, <add> *, <add> drop=0.0, <add> sgd=None, <add> losses=None, <add> component_cfg=None, <add> ): <ide> """Update the models in the pipeline. <ide> <ide> examples (iterable): A batch of `Example` or `Doc` objects. <add><path>spacy/pipe_analysis.py <del><path>spacy/analysis.py <ide> def count_pipeline_interdependencies(pipeline): <ide> counts = [] <ide> for i, assigns in enumerate(pipe_assigns): <ide> count = 0 <del> for requires in pipe_requires[i+1:]: <add> for requires in pipe_requires[i + 1 :]: <ide> if assigns.intersection(requires): <ide> count += 1 <ide> counts.append(count) <ide> return counts <del> <del> <ide><path>spacy/tests/pipeline/test_analysis.py <ide> import spacy.language <ide> from spacy.language import Language, component <del>from spacy.analysis import print_summary, validate_attrs <del>from spacy.analysis import get_assigns_for_attr, get_requires_for_attr <del>from spacy.analysis import count_pipeline_interdependencies <add>from spacy.pipe_analysis import print_summary, validate_attrs <add>from spacy.pipe_analysis import get_assigns_for_attr, get_requires_for_attr <add>from spacy.pipe_analysis import count_pipeline_interdependencies <ide> from mock import Mock, ANY <ide> import pytest <ide> <ide> class Fancifier: <ide> name = "fancifier" <ide> assigns = ("doc._.fancy",) <ide> requires = tuple() <del> <add> <ide> class FancyNeeder: <ide> name = "needer" <ide> assigns = tuple()
3
Javascript
Javascript
fix notification from showing up in wrong window
5d67183b4d251d929752b2b39377c94fd7f9c07f
<ide><path>extensions/firefox/components/PdfStreamConverter.js <ide> function getLocalizedString(strings, id) { <ide> } <ide> <ide> // All the priviledged actions. <del>function ChromeActions() { <add>function ChromeActions(domWindow) { <add> this.domWindow = domWindow; <ide> } <ide> <ide> ChromeActions.prototype = { <ide> ChromeActions.prototype = { <ide> return getBoolPref(EXT_PREFIX + '.pdfBugEnabled', false); <ide> }, <ide> fallback: function(url) { <del> var strings = getLocalizedStrings('chrome.properties'); <ide> var self = this; <add> var domWindow = this.domWindow; <add> var strings = getLocalizedStrings('chrome.properties'); <ide> var message = getLocalizedString(strings, 'unsupported_feature'); <add> <ide> var win = Services.wm.getMostRecentWindow('navigator:browser'); <del> var notificationBox = win.gBrowser.getNotificationBox(); <add> var browser = win.gBrowser.getBrowserForDocument(domWindow.top.document); <add> var notificationBox = win.gBrowser.getNotificationBox(browser); <add> <ide> var buttons = [{ <ide> label: getLocalizedString(strings, 'open_with_different_viewer'), <ide> accessKey: null, <ide> PdfStreamConverter.prototype = { <ide> var domWindow = getDOMWindow(channel); <ide> // Double check the url is still the correct one. <ide> if (domWindow.document.documentURIObject.equals(aRequest.URI)) { <del> let requestListener = new RequestListener(new ChromeActions); <add> let requestListener = new RequestListener( <add> new ChromeActions(domWindow)); <ide> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) { <ide> requestListener.receive(event); <ide> }, false, true);
1
PHP
PHP
add additional tests
dace3d5091be902ccc8c56ae6f12cf3270a2b4cb
<ide><path>laravel/tests/cases/blade.test.php <ide> public function testControlStructuresAreCreatedCorrectly() <ide> { <ide> $blade1 = "@if (true)\nfoo\n@endif"; <ide> $blade2 = "@if (count(".'$something'.") > 0)\nfoo\n@endif"; <del> $blade3 = "@if (true)\nfoo\n@elseif (false)\nbar\n@endif"; <del> $blade4 = "@if (true)\nfoo\n@else\nbar\n@endif"; <del> $blade5 = "@unless (count(".'$something'.") > 0)\nfoobar\n@endunless"; <del> $blade6 = "@for (Foo::all() as ".'$foo'.")\nfoo\n@endfor"; <del> $blade7 = "@foreach (Foo::all() as ".'$foo'.")\nfoo\n@endforeach"; <del> $blade8 = "@forelse (Foo::all() as ".'$foo'.")\nfoo\n@empty\nbar\n@endforelse"; <del> $blade9 = "@while (true)\nfoo\n@endwhile"; <add> $blade3 = "@if (true)\nfoo\n@elseif (false)\nbar\n@else\nfoobar\n@endif"; <add> $blade4 = "@if (true)\nfoo\n@elseif (false)\nbar\n@endif"; <add> $blade5 = "@if (true)\nfoo\n@else\nbar\n@endif"; <add> $blade6 = "@unless (count(".'$something'.") > 0)\nfoobar\n@endunless"; <add> $blade7 = "@for (Foo::all() as ".'$foo'.")\nfoo\n@endfor"; <add> $blade8 = "@foreach (Foo::all() as ".'$foo'.")\nfoo\n@endforeach"; <add> $blade9 = "@forelse (Foo::all() as ".'$foo'.")\nfoo\n@empty\nbar\n@endforelse"; <add> $blade10 = "@while (true)\nfoo\n@endwhile"; <add> $blade11 = "@while (Foo::bar())\nfoo\n@endwhile"; <add> <ide> <ide> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php endif; ?>", Blade::compile_string($blade1)); <ide> $this->assertEquals("<?php if (count(".'$something'.") > 0): ?>\nfoo\n<?php endif; ?>", Blade::compile_string($blade2)); <del> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php elseif (false): ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade3)); <del> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php else: ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade4)); <del> $this->assertEquals("<?php if ( ! ( (count(".'$something'.") > 0))): ?>\nfoobar\n<?php endif; ?>", Blade::compile_string($blade5)); <del> $this->assertEquals("<?php for (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endfor; ?>", Blade::compile_string($blade6)); <del> $this->assertEquals("<?php foreach (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endforeach; ?>", Blade::compile_string($blade7)); <del> $this->assertEquals("<?php if (count(Foo::all()) > 0): ?><?php foreach (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endforeach; ?><?php else: ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade8)); <del> $this->assertEquals("<?php while (true): ?>\nfoo\n<?php endwhile; ?>", Blade::compile_string($blade9)); <del> <add> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php elseif (false): ?>\nbar\n<?php else: ?>\nfoobar\n<?php endif; ?>", Blade::compile_string($blade3)); <add> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php elseif (false): ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade4)); <add> $this->assertEquals("<?php if (true): ?>\nfoo\n<?php else: ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade5)); <add> $this->assertEquals("<?php if ( ! ( (count(".'$something'.") > 0))): ?>\nfoobar\n<?php endif; ?>", Blade::compile_string($blade6)); <add> $this->assertEquals("<?php for (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endfor; ?>", Blade::compile_string($blade7)); <add> $this->assertEquals("<?php foreach (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endforeach; ?>", Blade::compile_string($blade8)); <add> $this->assertEquals("<?php if (count(Foo::all()) > 0): ?><?php foreach (Foo::all() as ".'$foo'."): ?>\nfoo\n<?php endforeach; ?><?php else: ?>\nbar\n<?php endif; ?>", Blade::compile_string($blade9)); <add> $this->assertEquals("<?php while (true): ?>\nfoo\n<?php endwhile; ?>", Blade::compile_string($blade10)); <add> $this->assertEquals("<?php while (Foo::bar()): ?>\nfoo\n<?php endwhile; ?>", Blade::compile_string($blade11)); <ide> } <ide> <ide> /** <ide> public function testSectionsAreCompiledCorrectly() <ide> */ <ide> public function testIncludesAreCompiledCorrectly() <ide> { <del> $blade = "@include('user.profile')"; <add> $blade1 = "@include('user.profile')"; <add> $blade2 = "@include(Config::get('application.default_view', 'user.profile'))"; <ide> <del> $this->assertEquals("<?php echo view('user.profile')->with(get_defined_vars())->render(); ?>", Blade::compile_string($blade)); <add> $this->assertEquals("<?php echo view('user.profile')->with(get_defined_vars())->render(); ?>", Blade::compile_string($blade1)); <add> $this->assertEquals("<?php echo view(Config::get('application.default_view', 'user.profile'))->with(get_defined_vars())->render(); ?>", Blade::compile_string($blade2)); <ide> } <ide> <ide> /** <ide> public function testIncludesAreCompiledCorrectly() <ide> */ <ide> public function testRendersAreCompiledCorrectly() <ide> { <del> $blade = "@render('user.profile')"; <add> $blade1 = "@render('user.profile')"; <add> $blade2 = "@render(Config::get('application.default_view', 'user.profile'))"; <add> <add> $this->assertEquals("<?php echo render('user.profile'); ?>", Blade::compile_string($blade1)); <add> $this->assertEquals("<?php echo render(Config::get('application.default_view', 'user.profile')); ?>", Blade::compile_string($blade2)); <ide> <del> $this->assertEquals("<?php echo render('user.profile'); ?>", Blade::compile_string($blade)); <ide> } <ide> <ide> } <ide>\ No newline at end of file
1
Mixed
Ruby
render default template if block doesn't render
48f140cf7459c963a54637c897448b959dbbfd26
<ide><path>actionpack/CHANGELOG.md <add>* When a `respond_to` collector with a block doesn't have a response, then <add> a `:no_content` response should be rendered. This brings the default <add> rendering behavior introduced by https://github.com/rails/rails/issues/19036 <add> to controller methods employing `respond_to` <add> <add> *Justin Coyne* <add> <ide> * Update default rendering policies when the controller action did <ide> not explicitly indicate a response. <ide> <ide><path>actionpack/lib/action_controller/metal/mime_responds.rb <ide> def respond_to(*mimes) <ide> _process_format(format) <ide> _set_rendered_content_type format <ide> response = collector.response <del> response ? response.call : render({}) <add> response.call if response <ide> else <ide> raise ActionController::UnknownFormat <ide> end <ide><path>actionpack/test/controller/mime/respond_to_test.rb <ide> def using_defaults <ide> end <ide> end <ide> <add> def missing_templates <add> respond_to do |type| <add> # This test requires a block that is empty <add> type.json { } <add> type.xml <add> end <add> end <add> <ide> def using_defaults_with_type_list <ide> respond_to(:html, :xml) <ide> end <ide> def test_invalid_format <ide> end <ide> end <ide> <add> def test_missing_templates <add> get :missing_templates, format: :json <add> assert_response :no_content <add> get :missing_templates, format: :xml <add> assert_response :no_content <add> end <add> <ide> def test_invalid_variant <ide> assert_raises(ActionController::UnknownFormat) do <ide> get :variant_with_implicit_template_rendering, params: { v: :invalid }
3
Javascript
Javascript
prevent nan props from triggering warnings
198aabaafbe6dfe50be6b1624d1626b0cc91d974
<ide><path>src/classic/element/ReactElementValidator.js <ide> function checkAndWarnForMutatedProps(element) { <ide> <ide> for (var propName in props) { <ide> if (props.hasOwnProperty(propName)) { <del> if (!originalProps.hasOwnProperty(propName) || <del> originalProps[propName] !== props[propName]) { <add> var valueChanged = originalProps[propName] !== props[propName]; <add> // Necessary because NaN !== NaN <add> if (typeof originalProps[propName] === 'number' && <add> typeof props[propName] === 'number' && <add> isNaN(originalProps[propName]) && isNaN(props[propName])) { <add> valueChanged = false; <add> } <add> if (!originalProps.hasOwnProperty(propName) || valueChanged) { <ide> warnForPropsMutation(propName, element); <ide> <ide> // Copy over the new value so that the two props objects match again
1
Python
Python
build `panopticmaskrcnnmodel` in factory
b851571dc985c8308d23add962b4e0288ba3ee9e
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/factory.py <ide> from official.vision.beta.modeling.heads import segmentation_heads <ide> from official.vision.beta.projects.panoptic_maskrcnn.configs import panoptic_maskrcnn as panoptic_maskrcnn_cfg <ide> from official.vision.beta.projects.panoptic_maskrcnn.modeling import panoptic_maskrcnn_model <add>from official.vision.beta.projects.panoptic_maskrcnn.modeling.layers import panoptic_segmentation_generator <ide> <ide> <ide> def build_panoptic_maskrcnn( <ide> def build_panoptic_maskrcnn( <ide> <ide> segmentation_head_config = segmentation_config.head <ide> detection_head_config = model_config.detection_head <add> postprocessing_config = \ <add> model_config.panoptic_segmentation_generator <ide> <ide> segmentation_head = segmentation_heads.SegmentationHead( <ide> num_classes=segmentation_config.num_classes, <ide> def build_panoptic_maskrcnn( <ide> norm_epsilon=norm_activation_config.norm_epsilon, <ide> kernel_regularizer=l2_regularizer) <ide> <add> panoptic_segmentation_generator_obj = \ <add> panoptic_segmentation_generator.PanopticSegmentationGenerator( <add> output_size=postprocessing_config.output_size, <add> stuff_classes_offset=postprocessing_config.stuff_classes_offset, <add> mask_binarize_threshold=postprocessing_config.mask_binarize_threshold, <add> score_threshold=postprocessing_config.score_threshold, <add> things_class_label=postprocessing_config.things_class_label, <add> void_class_label=postprocessing_config.void_class_label, <add> void_instance_id=postprocessing_config.void_instance_id) <add> <ide> # Combines maskrcnn, and segmentation models to build panoptic segmentation <ide> # model. <ide> model = panoptic_maskrcnn_model.PanopticMaskRCNNModel( <ide> def build_panoptic_maskrcnn( <ide> roi_sampler=maskrcnn_model.roi_sampler, <ide> roi_aligner=maskrcnn_model.roi_aligner, <ide> detection_generator=maskrcnn_model.detection_generator, <add> panoptic_segmentation_generator=panoptic_segmentation_generator_obj, <ide> mask_head=maskrcnn_model.mask_head, <ide> mask_sampler=maskrcnn_model.mask_sampler, <ide> mask_roi_aligner=maskrcnn_model.mask_roi_aligner,
1
Javascript
Javascript
improve tests for util.inherits
df738ac56c31ac8a04d6afbd3d7be59cfa5c2e9a
<ide><path>test/parallel/test-util-inherits.js <add>'use strict'; <add> <add>require('../common'); <add>const assert = require('assert'); <add>const inherits = require('util').inherits; <add> <add>// super constructor <add>function A() { <add> this._a = 'a'; <add>} <add>A.prototype.a = function() { return this._a; }; <add> <add>// one level of inheritance <add>function B(value) { <add> A.call(this); <add> this._b = value; <add>} <add>inherits(B, A); <add>B.prototype.b = function() { return this._b; }; <add> <add>assert.strictEqual(B.super_, A); <add> <add>const b = new B('b'); <add>assert.strictEqual(b.a(), 'a'); <add>assert.strictEqual(b.b(), 'b'); <add>assert.strictEqual(b.constructor, B); <add> <add> // two levels of inheritance <add>function C() { <add> B.call(this, 'b'); <add> this._c = 'c'; <add>} <add>inherits(C, B); <add>C.prototype.c = function() { return this._c; }; <add>C.prototype.getValue = function() { return this.a() + this.b() + this.c(); }; <add> <add>assert.strictEqual(C.super_, B); <add> <add>const c = new C(); <add>assert.strictEqual(c.getValue(), 'abc'); <add>assert.strictEqual(c.constructor, C); <add> <add>// should throw with invalid arguments <add>assert.throws(function() { inherits(A, {}); }, TypeError); <add>assert.throws(function() { inherits(A, null); }, TypeError); <add>assert.throws(function() { inherits(null, A); }, TypeError); <ide><path>test/parallel/test-util.js <ide> assert.deepEqual(util._extend({a:1}, true), {a:1}); <ide> assert.deepEqual(util._extend({a:1}, false), {a:1}); <ide> assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); <ide> assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); <del> <del>// inherits <del>var ctor = function() {}; <del>assert.throws(function() { util.inherits(ctor, {}); }, TypeError); <del>assert.throws(function() { util.inherits(ctor, null); }, TypeError); <del>assert.throws(function() { util.inherits(null, ctor); }, TypeError); <del>assert.doesNotThrow(function() { util.inherits(ctor, ctor); }, TypeError);
2
Javascript
Javascript
remove unused parameters
859ccd78b56dda4a3952e35a0a414db44fe126cf
<ide><path>benchmark/_benchmark_progress.js <ide> class BenchmarkProgress { <ide> this.updateProgress(); <ide> } <ide> <del> completeConfig(data) { <add> completeConfig() { <ide> this.completedConfig++; <ide> this.updateProgress(); <ide> } <ide> <del> completeRun(job) { <add> completeRun() { <ide> this.completedRuns++; <ide> this.updateProgress(); <ide> } <ide> class BenchmarkProgress { <ide> `${caption} `; <ide> } <ide> <del> updateProgress(finished) { <add> updateProgress() { <ide> if (!process.stderr.isTTY || process.stdout.isTTY) { <ide> return; <ide> }
1
PHP
PHP
add a test
2f2cbbd8cce29ac6170e24bee94919dc20198612
<ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> <ide> class FakeConnection <ide> { <add> protected $_config = []; <add> <add> /** <add> * Constructor. <add> * <add> * @param array $config configuration for connecting to database <add> */ <add> public function __construct($config) <add> { <add> $this->_config = $config; <add> } <add> <add> /** <add> * Returns the set config <add> * <add> * @return array <add> */ <add> public function config() <add> { <add> return $this->_config; <add> } <add> <add> /** <add> * Returns the set name <add> * <add> * @return string <add> */ <add> public function configName() <add> { <add> if (empty($this->_config['name'])) { <add> return ''; <add> } <add> <add> return $this->_config['name']; <add> } <ide> } <ide> <ide> /** <ide> public function testConfigWithCallable() <ide> ConnectionManager::config('test_variant', $callable); <ide> $this->assertSame($connection, ConnectionManager::get('test_variant')); <ide> } <add> <add> /** <add> * Tests that setting a config will also correctly set the name for the connection <add> * <add> * @return void <add> */ <add> public function testSetConfigName() <add> { <add> //Set with explicit name <add> ConnectionManager::config('test_variant', [ <add> 'className' => __NAMESPACE__ . '\FakeConnection', <add> 'database' => ':memory:' <add> ]); <add> $result = ConnectionManager::get('test_variant'); <add> $this->assertSame('test_variant', $result->configName()); <add> <add> ConnectionManager::drop('test_variant'); <add> ConnectionManager::config([ <add> 'test_variant' => [ <add> 'className' => __NAMESPACE__ . '\FakeConnection', <add> 'database' => ':memory:' <add> ] <add> ]); <add> $result = ConnectionManager::get('test_variant'); <add> $this->assertSame('test_variant', $result->configName()); <add> } <ide> }
1
Text
Text
add 5.6 changelog
747771405090139378b648742ccc73649c100099
<ide><path>CHANGELOG-5.6.md <add># Release Notes for 5.6.x <add> <add>## [Unreleased] <add> <add>### Artisan Console <add>- Removed deprecated `optimize` command ([#20851](https://github.com/laravel/framework/pull/20851))
1
Python
Python
add tests to ovh storage driver
2be789d3cecd13d3378bfd3a5662ae5d630a7a6d
<ide><path>libcloud/test/storage/test_ovh.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add> <add>import sys <add>import unittest <add> <add>from libcloud.storage.drivers.s3 import S3SignatureV4Connection <add>from libcloud.storage.drivers.ovh import ( <add> OvhStorageDriver, <add> OVH_FR_SBG_HOST, <add>) <add>from libcloud.test.storage.test_s3 import S3MockHttp, S3Tests <add> <add>from libcloud.test.secrets import STORAGE_S3_PARAMS <add> <add> <add>class OvhStorageDriverTestCase(S3Tests, unittest.TestCase): <add> driver_type = OvhStorageDriver <add> driver_args = STORAGE_S3_PARAMS <add> default_host = OVH_FR_SBG_HOST <add> <add> @classmethod <add> def create_driver(self): <add> return self.driver_type(*self.driver_args, host=self.default_host) <add> <add> def setUp(self): <add> super(OvhStorageDriverTestCase, self).setUp() <add> <add> OvhStorageDriver.connectionCls.conn_class = S3MockHttp <add> S3MockHttp.type = None <add> <add> self.driver = self.create_driver() <add> <add> def test_connection_class_type(self): <add> self.assertEqual(self.driver.connectionCls, S3SignatureV4Connection) <add> <add> def test_connection_class_default_host(self): <add> self.assertEqual(self.driver.connectionCls.host, self.default_host) <add> self.assertEqual(self.driver.connectionCls.port, 443) <add> self.assertEqual(self.driver.connectionCls.secure, True) <add> <add> <add>if __name__ == "__main__": <add> sys.exit(unittest.main())
1
Go
Go
fix bad import graph from opts/opts.go
b68221c37ee597950364788204546f9c9d0e46a1
<ide><path>daemon/config/config.go <ide> func Validate(config *Config) error { <ide> } <ide> } <ide> <del> if _, err := opts.ParseGenericResources(config.NodeGenericResources); err != nil { <add> if _, err := ParseGenericResources(config.NodeGenericResources); err != nil { <ide> return err <ide> } <ide> <ide><path>daemon/config/opts.go <add>package config <add> <add>import ( <add> "github.com/docker/docker/api/types/swarm" <add> "github.com/docker/docker/daemon/cluster/convert" <add> "github.com/docker/swarmkit/api/genericresource" <add>) <add> <add>// ParseGenericResources parses and validates the specified string as a list of GenericResource <add>func ParseGenericResources(value string) ([]swarm.GenericResource, error) { <add> if value == "" { <add> return nil, nil <add> } <add> <add> resources, err := genericresource.Parse(value) <add> if err != nil { <add> return nil, err <add> } <add> <add> obj := convert.GenericResourcesFromGRPC(resources) <add> return obj, nil <add>} <ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/daemon/events" <ide> "github.com/docker/docker/daemon/exec" <ide> "github.com/docker/docker/daemon/logger" <del> "github.com/docker/docker/opts" <ide> "github.com/sirupsen/logrus" <ide> // register graph drivers <ide> _ "github.com/docker/docker/daemon/graphdriver/register" <ide> func (daemon *Daemon) setupInitLayer(initPath string) error { <ide> } <ide> <ide> func (daemon *Daemon) setGenericResources(conf *config.Config) error { <del> genericResources, err := opts.ParseGenericResources(conf.NodeGenericResources) <add> genericResources, err := config.ParseGenericResources(conf.NodeGenericResources) <ide> if err != nil { <ide> return err <ide> } <ide><path>opts/opts.go <ide> import ( <ide> "regexp" <ide> "strings" <ide> <del> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/daemon/cluster/convert" <ide> units "github.com/docker/go-units" <del> "github.com/docker/swarmkit/api/genericresource" <ide> ) <ide> <ide> var ( <ide> func (m *MemBytes) UnmarshalJSON(s []byte) error { <ide> *m = MemBytes(val) <ide> return err <ide> } <del> <del>// ParseGenericResources parses and validates the specified string as a list of GenericResource <del>func ParseGenericResources(value string) ([]swarm.GenericResource, error) { <del> if value == "" { <del> return nil, nil <del> } <del> <del> resources, err := genericresource.Parse(value) <del> if err != nil { <del> return nil, err <del> } <del> <del> obj := convert.GenericResourcesFromGRPC(resources) <del> <del> return obj, nil <del>}
4
Javascript
Javascript
add more truetype rewriting magic ('post' table)
75f09304653625d8e973398d33fd92b2741d1d3d
<ide><path>fonts.js <ide> var kMaxWaitForFontFace = 1000; <ide> * many fonts are loaded. <ide> */ <ide> var fontCount = 0; <add>var fontName = ""; <ide> <ide> /** <ide> * Hold a map of decoded fonts and of the standard fourteen Type1 fonts and <ide> var Fonts = { <ide> }, <ide> <ide> set active(aName) { <add> fontName = aName; <ide> this._active = this[aName]; <ide> }, <ide> <ide> var TrueType = function(aName, aFile, aProperties) { <ide> // If any tables are still in the array this means some required tables are <ide> // missing, which means that we need to rebuild the font in order to pass <ide> // the sanitizer. <del> if (requiredTables.length == 1 && requiredTables[0] == "OS/2") { <add> if (requiredTables.length && requiredTables[0] == "OS/2") { <ide> var OS2 = [ <ide> 0x00, 0x03, // version <ide> 0x02, 0x24, // xAvgCharWidth <ide> var TrueType = function(aName, aFile, aProperties) { <ide> <ide> // Replace the old CMAP table <ide> var rewrittedCMAP = this._createCMAPTable(glyphs); <del> var cmapDelta = rewrittedCMAP.length - originalCMAP.data.length; <add> var offsetDelta = rewrittedCMAP.length - originalCMAP.data.length; <ide> originalCMAP.data = rewrittedCMAP; <ide> <add> // Rewrite the 'post' table if needed <add> var postTable = null; <add> for (var i = 0; i < tables.length; i++) { <add> var table = tables[i]; <add> if (table.tag == "post") { <add> postTable = table; <add> break; <add> } <add> } <add> <add> if (!postTable) { <add> var post = [ <add> 0x00, 0x03, 0x00, 0x00, // Version number <add> 0x00, 0x00, 0x01, 0x00, // italicAngle <add> 0x00, 0x00, // underlinePosition <add> 0x00, 0x00, // underlineThickness <add> 0x00, 0x00, 0x00, 0x00, // isFixedPitch <add> 0x00, 0x00, 0x00, 0x00, // minMemType42 <add> 0x00, 0x00, 0x00, 0x00, // maxMemType42 <add> 0x00, 0x00, 0x00, 0x00, // minMemType1 <add> 0x00, 0x00, 0x00, 0x00 // maxMemType1 <add> ]; <add> <add> offsetDelta += post.length; <add> tables.unshift({ <add> tag: "post", <add> data: post <add> }); <add> } <add> <ide> // Create a new file to hold the new version of our truetype with a new <ide> // header and new offsets <ide> var stream = aFile.stream || aFile; <del> var ttf = new Uint8Array(stream.length + 16 + OS2.length + cmapDelta); <add> var ttf = new Uint8Array(stream.length + 1024); <ide> <ide> // The new numbers of tables will be the last one plus the num of missing <ide> // tables <ide><path>pdf.js <ide> var CanvasExtraState = (function() { <ide> <ide> const Encodings = { <ide> get ExpertEncoding() { <del> return shadow(this, "ExpertEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "ExpertEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","exclamsmall","Hungarumlautsmall",,"dollaroldstyle","dollarsuperior", <ide> "ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior", <ide> "twodotenleader","onedotenleader","comma","hyphen","period","fraction", <ide> const Encodings = { <ide> ]); <ide> }, <ide> get MacExpertEncoding() { <del> return shadow(this, "MacExpertEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "MacExpertEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle", <ide> "dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior", <ide> "parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period", <ide> const Encodings = { <ide> ]); <ide> }, <ide> get MacRomanEncoding() { <del> return shadow(this, "MacRomanEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "MacRomanEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen", <ide> "period","slash","zero","one","two","three","four","five","six","seven","eight", <ide> const Encodings = { <ide> ]); <ide> }, <ide> get StandardEncoding() { <del> return shadow(this, "StandardEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "StandardEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period", <ide> "slash","zero","one","two","three","four","five","six","seven","eight","nine", <ide> const Encodings = { <ide> ]); <ide> }, <ide> get WinAnsiEncoding() { <del> return shadow(this, "WinAnsiEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "WinAnsiEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen", <ide> "period","slash","zero","one","two","three","four","five","six","seven","eight", <ide> const Encodings = { <ide> ]); <ide> }, <ide> get zapfDingbatsEncoding() { <del> return shadow(this, "zapfDingbatsEncoding", [ <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, null, <del> null, null, null, null, null, null, null, null, null, null, <add> return shadow(this, "zapfDingbatsEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> "space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13", <ide> "a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25", <ide> "a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34", <ide> var CanvasGraphics = (function() { <ide> error("FontFile not found for font: " + fontName); <ide> fontFile = xref.fetchIfRef(fontFile); <ide> <del> // Generate the custom cmap of the font if needed <ide> var encodingMap = {}; <ide> var charset = []; <ide> if (fontDict.has("Encoding")) { <ide> var encoding = xref.fetchIfRef(fontDict.get("Encoding")); <ide> if (IsDict(encoding)) { <del> // Build an map between codes and glyphs <add> // Build a map between codes and glyphs <ide> var differences = encoding.get("Differences"); <ide> var index = 0; <ide> for (var j = 0; j < differences.length; j++) { <ide> var CanvasGraphics = (function() { <ide> } else if (fontDict.has("ToUnicode")) { <ide> var cmapObj = xref.fetchIfRef(fontDict.get("ToUnicode")); <ide> if (IsName(cmapObj)) { <del> error("ToUnicode basic cmap translation not implemented"); <del> encodingMap = {}; <add> error("ToUnicode file cmap translation not implemented"); <ide> } else if (IsStream(cmapObj)) { <add> var encoding = Encodings["WinAnsiEncoding"]; <add> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar")); <add> for (var i = firstChar; i < encoding.length; i++) <add> encodingMap[i] = new Name(encoding[i]); <add> <ide> var tokens = []; <ide> var token = ""; <ide> <ide> var CanvasGraphics = (function() { <ide> var code = parseInt("0x" + tokens[j+2]); <ide> <ide> for (var k = startRange; k <= endRange; k++) { <del> encodingMap[k] = code; <del> charset.push(code++); <add> encodingMap[k] = GlyphsUnicode[encoding[code]]; <add> charset.push(encoding[code++]); <ide> } <ide> } <ide> break;
2
Javascript
Javascript
add issignup logic
bf196d37ffb3cdae496646c55729c7a893fccdb9
<ide><path>common/models/user.js <ide> module.exports = function(User) { <ide> <ide> User.decodeEmail = email => Buffer(email, 'base64').toString(); <ide> <del> User.prototype.requestAuthEmail = function requestAuthEmail() { <add> User.prototype.requestAuthEmail = function requestAuthEmail(isSignUp) { <ide> return Observable.defer(() => { <ide> const messageOrNull = getWaitMessage(this.emailAuthLinkTTL); <ide> if (messageOrNull) { <ide> module.exports = function(User) { <ide> return this.createAccessToken$({ ttl: 15 * 60 * 1000 }); <ide> }) <ide> .flatMap(token => { <del> // email verified will be false if the user instance <del> // has just been created <del> const renderAuthEmail = this.emailVerified === false ? <del> renderSignInEmail : <del> renderSignUpEmail; <add> let renderAuthEmail = renderSignInEmail; <add> let subject = 'Login Requested - freeCodeCamp'; <add> if (isSignUp) { <add> renderAuthEmail = renderSignUpEmail; <add> subject = 'Account Created - freeCodeCamp'; <add> } <ide> const { id: loginToken, created: emailAuthLinkTTL } = token; <ide> const loginEmail = this.getEncodedEmail(); <ide> const host = getServerFullURL(); <ide> const mailOptions = { <ide> type: 'email', <ide> to: this.email, <ide> from: getEmailSender(), <del> subject: 'Login Requested - freeCodeCamp', <add> subject, <ide> text: renderAuthEmail({ <ide> host, <ide> loginEmail, <ide> module.exports = function(User) { <ide> this.update$({ emailAuthLinkTTL }) <ide> ); <ide> }) <del> .map(() => dedent` <del> If you entered a valid email, a magic link is on its way. <del> Please follow that link to sign in. <del> `); <add> .map(() => isSignUp ? <add> dedent` <add> We've created a new account for you. <add> If you entered a valid email, a magic link is on its way. <add> Please follow that link to sign in. <add> ` : <add> dedent` <add> If you entered a valid email, a magic link is on its way. <add> Please follow that link to sign in. <add> ` <add> ); <ide> }; <ide> <ide> User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) { <ide><path>server/boot/authentication.js <ide> module.exports = function enableAuthentication(app) { <ide> } <ide> <ide> return User.findOne$({ where: { email } }) <del> .flatMap(user => ( <del> // if no user found create new user and save to db <del> user ? Observable.of(user) : User.create$({ email }) <del> )) <del> .flatMap(user => user.requestAuthEmail()) <add> .flatMap(_user => Observable.if( <add> // if no user found create new user and save to db <add> _.constant(_user), <add> Observable.of(_user), <add> User.create$({ email }) <add> ) <add> .flatMap(user => user.requestAuthEmail(!_user)) <add> ) <ide> .do(msg => res.status(200).send({ message: msg })) <ide> .subscribe(_.noop, next); <ide> }
2
PHP
PHP
adjust condition to what hasherfactory uses
b98e87219c86ed4c4ae220aaa9123cf2ca00664d
<ide><path>src/Auth/FallbackPasswordHasher.php <ide> class FallbackPasswordHasher extends AbstractPasswordHasher { <ide> public function __construct(array $config = array()) { <ide> parent::__construct($config); <ide> foreach ($this->_config['hashers'] as $key => $hasher) { <del> if (!is_int($key)) { <add> if (!is_string($hasher)) { <ide> $hasher += [ <ide> 'className' => $key, <ide> ];
1
Text
Text
add new documentation
bc3bf75c6c6324476357198d9a7ddaa02bb6ecc4
<ide><path>share/doc/homebrew/New-Maintainer-Checklist.md <add># New Maintainer Checklist <add>**This is a guide used by existing maintainers to invite new maintainers. You might find it interesting but there's nothing here users should have to know.** <add> <add>So, there's someone who has been making consistently high-quality contributions to Homebrew for a long time and shown themselves able to make slightly more advanced contributions than just e.g. formula updates? Let's invite them to be a maintainer! <add> <add>First, send them the invitation email: <add> <add>``` <add>The Homebrew team and I really appreciate your help on issues, pull requests and <add>your contributions around making our testing better. <add> <add>We would like to invite you to have commit access. There are no obligations, <add>but we'd appreciate your continuing help in keeping on top of contributions. <add> <add>A few requests: <add> <add>- please make pull requests on any changes to core (i.e. non-formula) code or <add> any non-trivial (e.g. not a test or audit improvement or version bump) <add> changes to formulae code and don't merge them unless you get at least one +1 <add>- use `brew pull` and let it auto-close issues wherever possible (it may take <add> ~5m). When this isn't possible always use `git pull --rebase`, `git rebase` <add> and `git cherry-pick` rather than `git merge` and never use GitHub's "Merge <add> pull request" button. If in doubt, check with GitX that you've not <add> accidentally added merge commits <add>- still create your branches on your fork rather than in the main repository <add>- if still in doubt please ask for help and we'll help you out - these are <add> probably worth a read: <add> - https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Brew-Test-Bot-For-Core-Contributors.md <add> - https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Maintainer-Guidelines.md <add> - possibly everything else in the documentation <add> <add>How does that sound? <add> <add>Thanks for all your work so far! <add>``` <add> <add>If they accept, follow a few steps to get them set up: <add> <add>- [x] Invite them to the [**@Homebrew/core** team](https://github.com/orgs/Homebrew/teams/core) to give them write access to all repositories (but not administrator access yet) <add>- [x] Ask them to sign up for a [Bintray](https://bintray.com) account and invite them to [Bintray's Homebrew organisation](https://bintray.com/homebrew/organization/edit/members) as a member (but not administrator access yet) so they can publish new bottles <add>- [x] Add them to the [Jenkins' GitHub Authorization Settings admin user names](http://bot.brew.sh/configureSecurity/) so they can adjust settings and restart jobs <add>- [x] Add them to the [Jenkins' GitHub Pull Request Builder admin list](http://bot.brew.sh/configure) to enable `@BrewTestBot test this please` for them <add>- [x] Invite them to the [`homebrew-dev` private maintainers mailing list](https://groups.google.com/forum/#!managemembers/homebrew-dev/invite) <add>- [x] Add them to [Homebrew's README](https://github.com/Homebrew/homebrew/edit/master/README.md) <add>- [x] Encourage them to enable [GitHub's Two Factor Authentication](https://help.github.com/articles/about-two-factor-authentication/) <add> <add>After a few weeks/months with no problems consider making them administrators on the [**@Homebrew/owners**](https://github.com/orgs/Homebrew/teams/owners) and [Bintray](https://bintray.com/homebrew/organization/edit/members) teams. <add> <add>Now sit back, relax and let the new maintainers handle more of our contributions.
1
Javascript
Javascript
add failing test for gh
d21e016c51e0d1b6ce23ee36a67eac2a14e2bede
<ide><path>packages/ember-glimmer/tests/integration/components/curly-components-test.js <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> <ide> assertElement('foo'); <ide> } <add> <add> ['@test child triggers revalidate during parent destruction (GH#13846)']() { <add> let select; <add> <add> this.registerComponent('x-select', { <add> ComponentClass: Component.extend({ <add> tagName: 'select', <add> <add> init() { <add> this._super(); <add> this.options = emberA([]); <add> this.value = null; <add> <add> select = this; <add> }, <add> <add> updateValue() { <add> var newValue = this.get('options.lastObject.value'); <add> <add> this.set('value', newValue); <add> }, <add> <add> registerOption(option) { <add> this.get('options').addObject(option); <add> }, <add> <add> unregisterOption(option) { <add> this.get('options').removeObject(option); <add> <add> this.updateValue(); <add> } <add> }), <add> <add> template: '{{yield this}}' <add> }); <add> <add> this.registerComponent('x-option', { <add> ComponentClass: Component.extend({ <add> tagName: 'option', <add> attributeBindings: ['selected'], <add> <add> didInsertElement() { <add> this._super(...arguments); <add> <add> this.get('select').registerOption(this); <add> }, <add> <add> selected: computed('select.value', function() { <add> return this.get('value') === this.get('select.value'); <add> }), <add> <add> willDestroyElement() { <add> this._super(...arguments); <add> this.get('select').unregisterOption(this); <add> } <add> }) <add> }); <add> <add> this.render(strip` <add> {{#x-select value=value as |select|}} <add> {{#x-option value="1" select=select}}1{{/x-option}} <add> {{#x-option value="2" select=select}}2{{/x-option}} <add> {{/x-select}} <add> `); <add> <add> <add> this.teardown(); <add> <add> this.assert.ok(true, 'no errors during teardown'); <add> } <ide> });
1
Javascript
Javascript
add check in test-signal-handler
a6d53c67795bf957b8b57d96814520f98069e80e
<ide><path>test/parallel/test-signal-handler.js <ide> var i = 0; <ide> setInterval(function() { <ide> console.log('running process...' + ++i); <ide> <del> if (i == 5) { <add> if (i === 5) { <ide> process.kill(process.pid, 'SIGUSR1'); <ide> } <ide> }, 1); <ide> <ide> // Test on condition where a watcher for SIGNAL <ide> // has been previously registered, and `process.listeners(SIGNAL).length === 1` <del>process.on('SIGHUP', function() {}); <add>process.on('SIGHUP', function() { common.fail('should not run'); }); <ide> process.removeAllListeners('SIGHUP'); <ide> process.on('SIGHUP', common.mustCall(function() {})); <ide> process.kill(process.pid, 'SIGHUP');
1
Java
Java
avoid unused arguments for internal delegates
b449928691553ba791adf20850e9179730b4b3a2
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/DeclareParentsAdvisor.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.springframework.aop.ClassFilter; <ide> import org.springframework.aop.IntroductionAdvisor; <add>import org.springframework.aop.IntroductionInterceptor; <ide> import org.springframework.aop.support.ClassFilters; <ide> import org.springframework.aop.support.DelegatePerTargetObjectIntroductionInterceptor; <ide> import org.springframework.aop.support.DelegatingIntroductionInterceptor; <ide> */ <ide> public class DeclareParentsAdvisor implements IntroductionAdvisor { <ide> <add> private final Advice advice; <add> <ide> private final Class<?> introducedInterface; <ide> <ide> private final ClassFilter typePatternClassFilter; <ide> <del> private final Advice advice; <del> <ide> <ide> /** <ide> * Create a new advisor for this DeclareParents field. <ide> public class DeclareParentsAdvisor implements IntroductionAdvisor { <ide> * @param defaultImpl the default implementation class <ide> */ <ide> public DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, Class<?> defaultImpl) { <del> this(interfaceType, typePattern, defaultImpl, <del> new DelegatePerTargetObjectIntroductionInterceptor(defaultImpl, interfaceType)); <add> this(interfaceType, typePattern, <add> new DelegatePerTargetObjectIntroductionInterceptor(defaultImpl, interfaceType)); <ide> } <ide> <ide> /** <ide> public DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, Class<? <ide> * @param delegateRef the delegate implementation object <ide> */ <ide> public DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, Object delegateRef) { <del> this(interfaceType, typePattern, delegateRef.getClass(), <del> new DelegatingIntroductionInterceptor(delegateRef)); <add> this(interfaceType, typePattern, new DelegatingIntroductionInterceptor(delegateRef)); <ide> } <ide> <ide> /** <ide> * Private constructor to share common code between impl-based delegate and reference-based delegate <ide> * (cannot use method such as init() to share common code, due the use of final fields) <ide> * @param interfaceType static field defining the introduction <ide> * @param typePattern type pattern the introduction is restricted to <del> * @param implementationClass implementation class <del> * @param advice delegation advice <add> * @param interceptor the delegation advice as {@link IntroductionInterceptor} <ide> */ <del> private DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, Class<?> implementationClass, Advice advice) { <add> private DeclareParentsAdvisor(Class<?> interfaceType, String typePattern, IntroductionInterceptor interceptor) { <add> this.advice = interceptor; <ide> this.introducedInterface = interfaceType; <del> ClassFilter typePatternFilter = new TypePatternClassFilter(typePattern); <ide> <ide> // Excludes methods implemented. <del> ClassFilter exclusion = clazz -> !(introducedInterface.isAssignableFrom(clazz)); <del> <add> ClassFilter typePatternFilter = new TypePatternClassFilter(typePattern); <add> ClassFilter exclusion = (clazz -> !introducedInterface.isAssignableFrom(clazz)); <ide> this.typePatternClassFilter = ClassFilters.intersection(typePatternFilter, exclusion); <del> this.advice = advice; <ide> } <ide> <ide> <ide><path>spring-core/src/main/java/org/springframework/asm/ClassWriter.java <ide> int addUninitializedType(final String type, final int offset) { <ide> */ <ide> private Item addType(final Item item) { <ide> ++typeCount; <del> Item result = new Item(typeCount, key); <add> Item result = new Item(typeCount, item); <ide> put(result); <ide> if (typeTable == null) { <ide> typeTable = new Item[16];
2
Javascript
Javascript
remove console log from release script
3b4d460afd8bcb6437dca1456be2ad178722d9bb
<ide><path>release.js <ide> const groupByLabels = async (commits, github) => { <ide> <ide> for (const commit of commits) { <ide> const pullRequest = await getCommitPullRequest(commit, github) <del> console.log({ pullRequest }) <ide> <ide> if (pullRequest) { <ide> const section = getSectionForPullRequest(pullRequest)
1
Ruby
Ruby
use a latch to avoid busy loops
4db4f909174420904d48a9712e337b697d372ac3
<ide><path>activerecord/test/cases/connection_pool_test.rb <ide> require "cases/helper" <add>require 'active_support/concurrency/latch' <ide> <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> def test_reap_and_active <ide> end <ide> <ide> def test_reap_inactive <del> ready = false <add> ready = ActiveSupport::Concurrency::Latch.new <ide> @pool.checkout <ide> child = Thread.new do <ide> @pool.checkout <ide> @pool.checkout <del> ready = true <add> ready.release <ide> Thread.stop <ide> end <del> Thread.pass until ready <add> ready.await <ide> <ide> assert_equal 3, active_connections(@pool).size <ide>
1
Python
Python
make defchararray to import
5c68587ecc8aec46c15b17f414c3ccad9c1ecb2d
<ide><path>numpy/core/defchararray.py <ide> 'array', 'asarray'] <ide> <ide> _globalvar = 0 <del>_unicode = unicode <add>if sys.version_info[0] >= 3: <add> _unicode = str <add>else: <add> _unicode = unicode <ide> _len = len <ide> <ide> def _use_unicode(*args):
1
Text
Text
clarify documentation for templatehtmlrenderer
3db88778893579e1d7609b584ef35409c8aa5a22
<ide><path>docs/api-guide/renderers.md <ide> Unlike other renderers, the data passed to the `Response` does not need to be se <ide> <ide> The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context. <ide> <add>--- <add> <add>**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionay and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example: <add> <add>``` <add>response.data = {'results': response.data} <add>``` <add> <add>--- <add> <ide> The template name is determined by (in order of preference): <ide> <ide> 1. An explicit `template_name` argument passed to the response.
1
Text
Text
specify return type for tty.isatty()
643a2fa447dd50644039d1ca1ce15c6d4d03bce4
<ide><path>doc/api/tty.md <ide> added: v0.5.8 <ide> --> <ide> <ide> * `fd` {number} A numeric file descriptor <add>* Returns: {boolean} <ide> <ide> The `tty.isatty()` method returns `true` if the given `fd` is associated with <ide> a TTY and `false` if it is not, including whenever `fd` is not a non-negative
1
Go
Go
normalize comment formatting
a45b3a92f60324d34cff24265d79a6f5d7fc99c2
<ide><path>pkg/idtools/utils_unix.go <ide> func resolveBinary(binname string) (string, error) { <ide> if err != nil { <ide> return "", err <ide> } <del> //only return no error if the final resolved binary basename <del> //matches what was searched for <add> // only return no error if the final resolved binary basename <add> // matches what was searched for <ide> if filepath.Base(resolvedPath) == binname { <ide> return resolvedPath, nil <ide> }
1
Text
Text
add full list of subsystems
166e52b80b64b60f128e5fdf3da98d76ed4f7dbf
<ide><path>doc/guides/contributing/pull-requests.md <ide> If you want to know more about the code review and the landing process, see the <ide> * `test` <ide> * `tools` <ide> <add>You can find the full list of supported subsystems in the <add>[nodejs/core-validate-commit][] repository. <ide> More than one subsystem may be valid for any particular issue or pull request. <ide> <ide> [Building guide]: ../../../BUILDING.md <ide> More than one subsystem may be valid for any particular issue or pull request. <ide> [guide for writing tests in Node.js]: ../writing-tests.md <ide> [hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment <ide> [https://ci.nodejs.org/]: https://ci.nodejs.org/ <add>[nodejs/core-validate-commit]: https://github.com/nodejs/core-validate-commit/blob/main/lib/rules/subsystem.js <ide> [pull request template]: https://raw.githubusercontent.com/nodejs/node/HEAD/.github/PULL_REQUEST_TEMPLATE.md <ide> [running tests]: ../../../BUILDING.md#running-tests
1
Javascript
Javascript
consider options.delay value for closing timeout
7ffb2d3c17643303a51eb4e324c365af70fe3824
<ide><path>src/ngAnimate/animateCss.js <ide> var $AnimateCssProvider = ['$animateProvider', function($animateProvider) { <ide> } <ide> <ide> if (options.delay != null) { <del> var delayStyle = parseFloat(options.delay); <add> var delayStyle; <add> if (typeof options.delay !== "boolean") { <add> delayStyle = parseFloat(options.delay); <add> // number in options.delay means we have to recalculate the delay for the closing timeout <add> maxDelay = Math.max(delayStyle, 0); <add> } <ide> <ide> if (flags.applyTransitionDelay) { <ide> temporaryStyles.push(getCssDelayStyle(delayStyle)); <ide><path>test/ngAnimate/animateCssSpec.js <ide> describe("ngAnimate $animateCss", function() { <ide> $timeout.flush(); <ide> }).not.toThrow(); <ide> })); <add> <add> it("should consider a positive options.delay value for the closing timeout", <add> inject(function($animateCss, $rootElement, $timeout, $document) { <add> <add> var element = jqLite('<div></div>'); <add> $rootElement.append(element); <add> jqLite($document[0].body).append($rootElement); <add> <add> var options = { <add> delay: 3, <add> duration: 3, <add> to: { <add> height: '100px' <add> } <add> }; <add> <add> var animator = $animateCss(element, options); <add> <add> animator.start(); <add> triggerAnimationStartFrame(); <add> <add> // At this point, the animation should still be running (closing timeout is 7500ms ... duration * 1.5 + delay => 7.5) <add> $timeout.flush(7000); <add> <add> expect(element.css(prefix + 'transition-delay')).toBe('3s'); <add> expect(element.css(prefix + 'transition-duration')).toBe('3s'); <add> <add> // Let's flush the remaining amout of time for the timeout timer to kick in <add> $timeout.flush(500); <add> <add> dump(element.attr('style')); <add> expect(element.css(prefix + 'transition-duration')).toBeOneOf('', '0s'); <add> expect(element.css(prefix + 'transition-delay')).toBeOneOf('', '0s'); <add> })); <add> <add> it("should ignore a boolean options.delay value for the closing timeout", <add> inject(function($animateCss, $rootElement, $timeout, $document) { <add> <add> var element = jqLite('<div></div>'); <add> $rootElement.append(element); <add> jqLite($document[0].body).append($rootElement); <add> <add> var options = { <add> delay: true, <add> duration: 3, <add> to: { <add> height: '100px' <add> } <add> }; <add> <add> var animator = $animateCss(element, options); <add> <add> animator.start(); <add> triggerAnimationStartFrame(); <add> <add> // At this point, the animation should still be running (closing timeout is 4500ms ... duration * 1.5 => 4.5) <add> $timeout.flush(4000); <add> <add> expect(element.css(prefix + 'transition-delay')).toBeOneOf('initial', '0s'); <add> expect(element.css(prefix + 'transition-duration')).toBe('3s'); <add> <add> // Let's flush the remaining amout of time for the timeout timer to kick in <add> $timeout.flush(500); <add> <add> expect(element.css(prefix + 'transition-duration')).toBeOneOf('', '0s'); <add> expect(element.css(prefix + 'transition-delay')).toBeOneOf('', '0s'); <add> })); <add> <ide> }); <ide> <ide> describe("getComputedStyle", function() {
2
Javascript
Javascript
add assert helpers, small cleanup
d7f3c31d9debffe72631b26ac79eaa1f981c0115
<ide><path>pdf.js <ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- / <ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */ <add> <ide> function warn(msg) { <ide> if (console && console.log) <ide> console.log(msg); <ide> function error(msg) { <ide> throw new Error(msg); <ide> } <ide> <add>function assert(cond, msg) { <add> if (!cond) <add> error(msg); <add>} <add> <add>// In a well-formed PDF, |cond| holds. If it doesn't, subsequent <add>// behavior is undefined. <add>function assertWellFormed(cond, msg) { <add> if (!cond) <add> error("Malformed PDF: "+ msg); <add>} <add> <ide> function shadow(obj, prop, value) { <ide> Object.defineProperty(obj, prop, { value: value, enumerable: true }); <ide> return value; <ide> var Page = (function() { <ide> var contents = xref.fetchIfRef(this.contents); <ide> var resources = xref.fetchIfRef(this.resources); <ide> var mediaBox = xref.fetchIfRef(this.mediaBox); <del> if (!IsStream(contents) || !IsDict(resources)) <del> error("invalid page contents or resources"); <add> assertWellFormed(IsStream(contents) && IsDict(resources), <add> "invalid page contents or resources"); <ide> gfx.beginDrawing({ x: mediaBox[0], y: mediaBox[1], <ide> width: mediaBox[2] - mediaBox[0], <ide> height: mediaBox[3] - mediaBox[1] }); <ide> var Catalog = (function() { <ide> function constructor(xref) { <ide> this.xref = xref; <ide> var obj = xref.getCatalogObj(); <del> if (!IsDict(obj)) <del> error("catalog object is not a dictionary"); <add> assertWellFormed(IsDict(obj), "catalog object is not a dictionary"); <ide> this.catDict = obj; <ide> } <ide> <ide> constructor.prototype = { <ide> get toplevelPagesDict() { <ide> var obj = this.catDict.get("Pages"); <del> if (!IsRef(obj)) <del> error("invalid top-level pages reference"); <add> assertWellFormed(IsRef(obj), "invalid top-level pages reference"); <ide> var obj = this.xref.fetch(obj); <del> if (!IsDict(obj)) <del> error("invalid top-level pages dictionary"); <add> assertWellFormed(IsDict(obj), "invalid top-level pages dictionary"); <ide> // shadow the prototype getter <ide> return shadow(this, "toplevelPagesDict", obj); <ide> }, <ide> get numPages() { <ide> obj = this.toplevelPagesDict.get("Count"); <del> if (!IsInt(obj)) <del> error("page count in top level pages object is not an integer"); <add> assertWellFormed(IsInt(obj), <add> "page count in top level pages object is not an integer"); <ide> // shadow the prototype getter <ide> return shadow(this, "num", obj); <ide> }, <ide> traverseKids: function(pagesDict) { <ide> var pageCache = this.pageCache; <ide> var kids = pagesDict.get("Kids"); <del> if (!IsArray(kids)) <del> error("page dictionary kids object is not an array"); <add> assertWellFormed(IsArray(kids), <add> "page dictionary kids object is not an array"); <ide> for (var i = 0; i < kids.length; ++i) { <ide> var kid = kids[i]; <del> if (!IsRef(kid)) <del> error("page dictionary kid is not a reference"); <add> assertWellFormed(IsRef(kid), <add> "page dictionary kid is not a reference"); <ide> var obj = this.xref.fetch(kid); <ide> if (IsDict(obj, "Page") || (IsDict(obj) && !obj.has("Kids"))) { <ide> pageCache.push(new Page(this.xref, pageCache.length, obj)); <del> } else if (IsDict(obj)) { // must be a child page dictionary <add> } else { // must be a child page dictionary <add> assertWellFormed(IsDict(obj), <add> "page dictionary kid reference points to wrong type of object"); <ide> this.traverseKids(obj); <del> } else { <del> error("page dictionary kid reference points to wrong type of object"); <ide> } <ide> } <ide> }, <ide> var PDFDoc = (function() { <ide> }, <ide> getPage: function(n) { <ide> var linearization = this.linearization; <del> if (linearization) { <del> error("linearized page access not implemented"); <del> } <add> assert(!linearization, "linearized page access not implemented"); <ide> return this.catalog.getPage(n); <ide> } <ide> }; <ide> var CanvasGraphics = (function() { <ide> if (IsCmd(obj)) { <ide> var cmd = obj.cmd; <ide> var fn = map[cmd]; <del> if (fn) <del> // TODO figure out how to type-check vararg functions <del> fn.apply(this, args); <del> else <del> error("Unknown command '" + cmd + "'"); <add> assertWellFormed(fn, "Unknown command '" + cmd + "'"); <add> // TODO figure out how to type-check vararg functions <add> fn.apply(this, args); <add> <ide> args.length = 0; <ide> } else { <del> if (args.length > 33) <del> error("Too many arguments '" + cmd + "'"); <add> assertWellFormed(args.length <= 33, "Too many arguments"); <ide> args.push(obj); <ide> } <ide> } <ide> var CanvasGraphics = (function() { <ide> var e = arr[i]; <ide> if (IsNum(e)) { <ide> this.current.curX -= e * 0.001 * this.current.fontSize; <del> } else if (IsString(e)) { <del> this.showText(e); <ide> } else { <del> error("Unexpected element in TJ array"); <add> assertWellFormed(IsString(e), <add> "TJ array element isn't string or num"); <add> this.showText(e); <ide> } <ide> } <ide> }, <ide> var CanvasGraphics = (function() { <ide> if (!xobj) <ide> return; <ide> xobj = this.xref.fetchIfRef(xobj); <del> if (!IsStream(xobj)) <del> error("XObject should be a stream"); <add> assertWellFormed(IsStream(xobj), "XObject should be a stream"); <ide> <ide> this.interpret(new Parser(new Lexer(xobj), false), <ide> this.xref, xobj.dict.get("Resources"));
1
Javascript
Javascript
fix first call to url in usewhatwg
c6b586de33b6ac208d3de83b304bfe50f13a4292
<ide><path>benchmark/url/legacy-vs-whatwg-url-parse.js <ide> function useLegacy(n, input) { <ide> } <ide> <ide> function useWHATWG(n, input) { <del> var noDead = url.parse(input); <add> var noDead = new URL(input); <ide> bench.start(); <ide> for (var i = 0; i < n; i += 1) { <ide> noDead = new URL(input);
1
Python
Python
modernize tests for snowflakehook
6f26af95022799cd463d30405b3ac1058f0689da
<ide><path>tests/providers/snowflake/hooks/test_snowflake.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> # <del>import os <ide> import re <ide> import unittest <add>from pathlib import Path <ide> from unittest import mock <ide> <add>import pytest <ide> from cryptography.hazmat.backends import default_backend <ide> from cryptography.hazmat.primitives import serialization <ide> from cryptography.hazmat.primitives.asymmetric import rsa <del>from parameterized import parameterized <ide> <add>from airflow.models import Connection <ide> from airflow.providers.snowflake.hooks.snowflake import SnowflakeHook <del>from airflow.utils.process_utils import patch_environ <ide> <add>_PASSWORD = 'snowflake42' <add> <add>BASE_CONNECTION_KWARGS = { <add> 'login': 'user', <add> 'password': 'pw', <add> 'schema': 'public', <add> 'extra': { <add> 'database': 'db', <add> 'account': 'airflow', <add> 'warehouse': 'af_wh', <add> 'region': 'af_region', <add> 'role': 'af_role', <add> }, <add>} <add> <add> <add>@pytest.fixture() <add>def non_encrypted_temporary_private_key(tmp_path: Path): <add> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <add> private_key = key.private_bytes( <add> serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() <add> ) <add> test_key_file = tmp_path / "test_key.pem" <add> test_key_file.write_bytes(private_key) <add> return test_key_file <add> <add> <add>@pytest.fixture() <add>def encrypted_temporary_private_key(tmp_path: Path): <add> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <add> private_key = key.private_bytes( <add> serialization.Encoding.PEM, <add> serialization.PrivateFormat.PKCS8, <add> encryption_algorithm=serialization.BestAvailableEncryption(_PASSWORD.encode()), <add> ) <add> test_key_file: Path = tmp_path / "test_key.p8" <add> test_key_file.write_bytes(private_key) <add> return test_key_file <ide> <del>class TestSnowflakeHook(unittest.TestCase): <del> def setUp(self): <del> super().setUp() <del> <del> self.conn = conn = mock.MagicMock() <ide> <del> self.conn.login = 'user' <del> self.conn.password = 'pw' <del> self.conn.schema = 'public' <del> self.conn.extra_dejson = { <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <add>class TestPytestSnowflakeHook: <add> @pytest.mark.parametrize( <add> "connection_kwargs,expected_uri,expected_conn_params", <add> [ <add> ( <add> BASE_CONNECTION_KWARGS, <add> ( <add> 'snowflake://user:pw@airflow.af_region/db/public?' <add> 'warehouse=af_wh&role=af_role&authenticator=snowflake' <add> ), <add> { <add> 'account': 'airflow', <add> 'application': 'AIRFLOW', <add> 'authenticator': 'snowflake', <add> 'database': 'db', <add> 'password': 'pw', <add> 'region': 'af_region', <add> 'role': 'af_role', <add> 'schema': 'public', <add> 'session_parameters': None, <add> 'user': 'user', <add> 'warehouse': 'af_wh', <add> }, <add> ), <add> ( <add> { <add> **BASE_CONNECTION_KWARGS, <add> 'extra': { <add> 'extra__snowflake__database': 'db', <add> 'extra__snowflake__account': 'airflow', <add> 'extra__snowflake__warehouse': 'af_wh', <add> 'extra__snowflake__region': 'af_region', <add> 'extra__snowflake__role': 'af_role', <add> }, <add> }, <add> ( <add> 'snowflake://user:pw@airflow.af_region/db/public?' <add> 'warehouse=af_wh&role=af_role&authenticator=snowflake' <add> ), <add> { <add> 'account': 'airflow', <add> 'application': 'AIRFLOW', <add> 'authenticator': 'snowflake', <add> 'database': 'db', <add> 'password': 'pw', <add> 'region': 'af_region', <add> 'role': 'af_role', <add> 'schema': 'public', <add> 'session_parameters': None, <add> 'user': 'user', <add> 'warehouse': 'af_wh', <add> }, <add> ), <add> ], <add> ) <add> def test_hook_should_support_pass_auth(self, connection_kwargs, expected_uri, expected_conn_params): <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**connection_kwargs).get_uri() <add> ): <add> assert SnowflakeHook(snowflake_conn_id='test_conn').get_uri() == expected_uri <add> assert SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params() == expected_conn_params <add> <add> def test_get_conn_params_should_support_private_auth_with_encrypted_key( <add> self, encrypted_temporary_private_key <add> ): <add> connection_kwargs = { <add> **BASE_CONNECTION_KWARGS, <add> 'password': _PASSWORD, <add> 'extra': { <add> 'database': 'db', <add> 'account': 'airflow', <add> 'warehouse': 'af_wh', <add> 'region': 'af_region', <add> 'role': 'af_role', <add> 'private_key_file': str(encrypted_temporary_private_key), <add> }, <ide> } <del> <del> class UnitTestSnowflakeHook(SnowflakeHook): <del> conn_name_attr = 'snowflake_conn_id' <del> <del> def get_conn(self): <del> return conn <del> <del> def get_connection(self, _): <del> return conn <del> <del> self.db_hook = UnitTestSnowflakeHook(session_parameters={"QUERY_TAG": "This is a test hook"}) <del> <del> self.non_encrypted_private_key = "/tmp/test_key.pem" <del> self.encrypted_private_key = "/tmp/test_key.p8" <del> <del> # Write some temporary private keys. First is not encrypted, second is with a passphrase. <del> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <del> private_key = key.private_bytes( <del> serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() <del> ) <del> <del> with open(self.non_encrypted_private_key, "wb") as file: <del> file.write(private_key) <del> <del> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <del> private_key = key.private_bytes( <del> serialization.Encoding.PEM, <del> serialization.PrivateFormat.PKCS8, <del> encryption_algorithm=serialization.BestAvailableEncryption(self.conn.password.encode()), <del> ) <del> <del> with open(self.encrypted_private_key, "wb") as file: <del> file.write(private_key) <del> <del> def tearDown(self): <del> os.remove(self.encrypted_private_key) <del> os.remove(self.non_encrypted_private_key) <del> <del> def test_get_uri(self): <del> uri_shouldbe = ( <del> 'snowflake://user:pw@airflow.af_region/db/public?' <del> 'warehouse=af_wh&role=af_role&authenticator=snowflake' <del> ) <del> assert uri_shouldbe == self.db_hook.get_uri() <del> <del> @parameterized.expand( <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**connection_kwargs).get_uri() <add> ): <add> assert 'private_key' in SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params() <add> <add> def test_get_conn_params_should_support_private_auth_with_unencrypted_key( <add> self, non_encrypted_temporary_private_key <add> ): <add> connection_kwargs = { <add> **BASE_CONNECTION_KWARGS, <add> 'password': None, <add> 'extra': { <add> 'database': 'db', <add> 'account': 'airflow', <add> 'warehouse': 'af_wh', <add> 'region': 'af_region', <add> 'role': 'af_role', <add> 'private_key_file': str(non_encrypted_temporary_private_key), <add> }, <add> } <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**connection_kwargs).get_uri() <add> ): <add> assert 'private_key' in SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params() <add> connection_kwargs['password'] = '' <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**connection_kwargs).get_uri() <add> ): <add> assert 'private_key' in SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params() <add> connection_kwargs['password'] = _PASSWORD <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**connection_kwargs).get_uri() <add> ), pytest.raises(TypeError, match="Password was given but private key is not encrypted."): <add> SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params() <add> <add> def test_should_add_partner_info(self): <add> with unittest.mock.patch.dict( <add> 'os.environ', <add> AIRFLOW_CONN_TEST_CONN=Connection(**BASE_CONNECTION_KWARGS).get_uri(), <add> AIRFLOW_SNOWFLAKE_PARTNER='PARTNER_NAME', <add> ): <add> assert ( <add> SnowflakeHook(snowflake_conn_id='test_conn')._get_conn_params()['application'] <add> == "PARTNER_NAME" <add> ) <add> <add> def test_get_conn_should_call_connect(self): <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**BASE_CONNECTION_KWARGS).get_uri() <add> ), unittest.mock.patch('airflow.providers.snowflake.hooks.snowflake.connector') as mock_connector: <add> hook = SnowflakeHook(snowflake_conn_id='test_conn') <add> conn = hook.get_conn() <add> mock_connector.connect.assert_called_once_with(**hook._get_conn_params()) <add> assert mock_connector.connect.return_value == conn <add> <add> def test_hook_parameters_should_take_precedence(self): <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_TEST_CONN=Connection(**BASE_CONNECTION_KWARGS).get_uri() <add> ): <add> hook = SnowflakeHook( <add> snowflake_conn_id='test_conn', <add> account="TEST_ACCOUNT", <add> warehouse="TEST_WAREHOUSE", <add> database="TEST_DATABASE", <add> region="TEST_REGION", <add> role="TEST_ROLE", <add> schema="TEST_SCHEMA", <add> authenticator='TEST_AUTH', <add> session_parameters={"AA": "AAA"}, <add> ) <add> assert { <add> 'account': 'TEST_ACCOUNT', <add> 'application': 'AIRFLOW', <add> 'authenticator': 'TEST_AUTH', <add> 'database': 'TEST_DATABASE', <add> 'password': 'pw', <add> 'region': 'TEST_REGION', <add> 'role': 'TEST_ROLE', <add> 'schema': 'TEST_SCHEMA', <add> 'session_parameters': {'AA': 'AAA'}, <add> 'user': 'user', <add> 'warehouse': 'TEST_WAREHOUSE', <add> } == hook._get_conn_params() <add> assert ( <add> "snowflake://user:pw@TEST_ACCOUNT.TEST_REGION/TEST_DATABASE/TEST_SCHEMA" <add> "?warehouse=TEST_WAREHOUSE&role=TEST_ROLE&authenticator=TEST_AUTH" <add> ) == hook.get_uri() <add> <add> @pytest.mark.parametrize( <add> "sql,query_ids", <ide> [ <ide> ('select * from table', ['uuid', 'uuid']), <ide> ('select * from table;select * from table2', ['uuid', 'uuid', 'uuid2', 'uuid2']), <ide> (['select * from table;'], ['uuid', 'uuid']), <ide> (['select * from table;', 'select * from table2;'], ['uuid', 'uuid', 'uuid2', 'uuid2']), <ide> ], <ide> ) <del> def test_run_storing_query_ids(self, sql, query_ids): <del> cur = mock.MagicMock(rowcount=0) <del> self.conn.cursor.return_value = cur <del> type(cur).sfqid = mock.PropertyMock(side_effect=query_ids) <del> mock_params = {"mock_param": "mock_param"} <del> self.db_hook.run(sql, parameters=mock_params) <del> <del> sql_list = sql if isinstance(sql, list) else re.findall(".*?[;]", sql) <del> cur.execute.assert_has_calls([mock.call(query, mock_params) for query in sql_list]) <del> assert self.db_hook.query_ids == query_ids[::2] <del> cur.close.assert_called() <del> <del> def test_get_conn_params(self): <del> conn_params_shouldbe = { <del> 'user': 'user', <del> 'password': 'pw', <del> 'schema': 'public', <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'authenticator': 'snowflake', <del> 'session_parameters': {"QUERY_TAG": "This is a test hook"}, <del> "application": "AIRFLOW", <del> } <del> assert self.db_hook.snowflake_conn_id == 'snowflake_default' <del> assert conn_params_shouldbe == self.db_hook._get_conn_params() <del> <del> def test_get_conn_params_env_variable(self): <del> conn_params_shouldbe = { <del> 'user': 'user', <del> 'password': 'pw', <del> 'schema': 'public', <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'authenticator': 'snowflake', <del> 'session_parameters': {"QUERY_TAG": "This is a test hook"}, <del> "application": "AIRFLOW_TEST", <del> } <del> with patch_environ({"AIRFLOW_SNOWFLAKE_PARTNER": 'AIRFLOW_TEST'}): <del> assert self.db_hook.snowflake_conn_id == 'snowflake_default' <del> assert conn_params_shouldbe == self.db_hook._get_conn_params() <del> <del> def test_get_conn(self): <del> assert self.db_hook.get_conn() == self.conn <del> <del> def test_key_pair_auth_encrypted(self): <del> self.conn.extra_dejson = { <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'private_key_file': self.encrypted_private_key, <del> } <del> <del> params = self.db_hook._get_conn_params() <del> assert 'private_key' in params <del> <del> def test_key_pair_auth_not_encrypted(self): <del> self.conn.extra_dejson = { <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'private_key_file': self.non_encrypted_private_key, <del> } <del> <del> self.conn.password = '' <del> params = self.db_hook._get_conn_params() <del> assert 'private_key' in params <del> <del> self.conn.password = None <del> params = self.db_hook._get_conn_params() <del> assert 'private_key' in params <add> def test_run_storing_query_ids_extra(self, sql, query_ids): <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_SNOWFLAKE_DEFAULT=Connection(**BASE_CONNECTION_KWARGS).get_uri() <add> ), unittest.mock.patch('airflow.providers.snowflake.hooks.snowflake.connector') as mock_connector: <add> hook = SnowflakeHook() <add> conn = mock_connector.connect.return_value <add> cur = mock.MagicMock(rowcount=0) <add> conn.cursor.return_value = cur <add> type(cur).sfqid = mock.PropertyMock(side_effect=query_ids) <add> mock_params = {"mock_param": "mock_param"} <add> hook.run(sql, parameters=mock_params) <add> <add> sql_list = sql if isinstance(sql, list) else re.findall(".*?[;]", sql) <add> cur.execute.assert_has_calls([mock.call(query, mock_params) for query in sql_list]) <add> assert hook.query_ids == query_ids[::2] <add> cur.close.assert_called() <ide> <ide> @mock.patch('airflow.providers.snowflake.hooks.snowflake.SnowflakeHook.run') <ide> def test_connection_success(self, mock_run): <del> mock_run.return_value = [{'1': 1}] <del> status, msg = self.db_hook.test_connection() <del> assert status is True <del> assert msg == 'Connection successfully tested' <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_SNOWFLAKE_DEFAULT=Connection(**BASE_CONNECTION_KWARGS).get_uri() <add> ): <add> hook = SnowflakeHook() <add> mock_run.return_value = [{'1': 1}] <add> status, msg = hook.test_connection() <add> assert status is True <add> assert msg == 'Connection successfully tested' <add> mock_run.assert_called_once_with(sql='select 1') <ide> <ide> @mock.patch( <ide> 'airflow.providers.snowflake.hooks.snowflake.SnowflakeHook.run', <ide> side_effect=Exception('Connection Errors'), <ide> ) <ide> def test_connection_failure(self, mock_run): <del> status, msg = self.db_hook.test_connection() <del> assert status is False <del> assert msg == 'Connection Errors' <del> <del> <del>""" <del> Testing hooks with assigning`extra_` parameters <del>""" <del> <del> <del>class TestSnowflakeHookExtra(unittest.TestCase): <del> def setUp(self): <del> super().setUp() <del> <del> self.conn = conn = mock.MagicMock() <del> <del> self.conn.login = 'user' <del> self.conn.password = 'pw' <del> self.conn.schema = 'public' <del> self.conn.extra_dejson = { <del> 'extra__snowflake__database': 'db', <del> 'extra__snowflake__account': 'airflow', <del> 'extra__snowflake__warehouse': 'af_wh', <del> 'extra__snowflake__region': 'af_region', <del> 'extra__snowflake__role': 'af_role', <del> } <del> <del> class UnitTestSnowflakeHookExtra(SnowflakeHook): <del> conn_name_attr = 'snowflake_conn_id' <del> <del> def get_conn(self): <del> return conn <del> <del> def get_connection(self, _): <del> return conn <del> <del> self.db_hook_extra = UnitTestSnowflakeHookExtra( <del> session_parameters={"QUERY_TAG": "This is a test hook"} <del> ) <del> <del> self.non_encrypted_private_key = "/tmp/test_key.pem" <del> self.encrypted_private_key = "/tmp/test_key.p8" <del> <del> # Write some temporary private keys. First is not encrypted, second is with a passphrase. <del> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <del> private_key = key.private_bytes( <del> serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() <del> ) <del> <del> with open(self.non_encrypted_private_key, "wb") as file: <del> file.write(private_key) <del> <del> key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) <del> private_key = key.private_bytes( <del> serialization.Encoding.PEM, <del> serialization.PrivateFormat.PKCS8, <del> encryption_algorithm=serialization.BestAvailableEncryption(self.conn.password.encode()), <del> ) <del> <del> with open(self.encrypted_private_key, "wb") as file: <del> file.write(private_key) <del> <del> def tearDownExtra(self): <del> os.remove(self.encrypted_private_key) <del> os.remove(self.non_encrypted_private_key) <del> <del> def test_get_uri_extra(self): <del> uri_shouldbe = ( <del> 'snowflake://user:pw@airflow.af_region/db/public?' <del> 'warehouse=af_wh&role=af_role&authenticator=snowflake' <del> ) <del> assert uri_shouldbe == self.db_hook_extra.get_uri() <del> <del> @parameterized.expand( <del> [ <del> ('select * from table', ['uuid', 'uuid']), <del> ('select * from table;select * from table2', ['uuid', 'uuid', 'uuid2', 'uuid2']), <del> (['select * from table;'], ['uuid', 'uuid']), <del> (['select * from table;', 'select * from table2;'], ['uuid', 'uuid', 'uuid2', 'uuid2']), <del> ], <del> ) <del> def test_run_storing_query_ids_extra(self, sql, query_ids): <del> cur = mock.MagicMock(rowcount=0) <del> self.conn.cursor.return_value = cur <del> type(cur).sfqid = mock.PropertyMock(side_effect=query_ids) <del> mock_params = {"mock_param": "mock_param"} <del> self.db_hook_extra.run(sql, parameters=mock_params) <del> <del> sql_list = sql if isinstance(sql, list) else re.findall(".*?[;]", sql) <del> cur.execute.assert_has_calls([mock.call(query, mock_params) for query in sql_list]) <del> assert self.db_hook_extra.query_ids == query_ids[::2] <del> cur.close.assert_called() <del> <del> def test_get_conn_params_extra(self): <del> conn_params_shouldbe = { <del> 'user': 'user', <del> 'password': 'pw', <del> 'schema': 'public', <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'authenticator': 'snowflake', <del> 'session_parameters': {"QUERY_TAG": "This is a test hook"}, <del> "application": "AIRFLOW", <del> } <del> assert self.db_hook_extra.snowflake_conn_id == 'snowflake_default' <del> assert conn_params_shouldbe == self.db_hook_extra._get_conn_params() <del> <del> def test_get_conn_params_env_variable_extra(self): <del> conn_params_shouldbe = { <del> 'user': 'user', <del> 'password': 'pw', <del> 'schema': 'public', <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'authenticator': 'snowflake', <del> 'session_parameters': {"QUERY_TAG": "This is a test hook"}, <del> "application": "AIRFLOW_TEST", <del> } <del> with patch_environ({"AIRFLOW_SNOWFLAKE_PARTNER": 'AIRFLOW_TEST'}): <del> assert self.db_hook_extra.snowflake_conn_id == 'snowflake_default' <del> assert conn_params_shouldbe == self.db_hook_extra._get_conn_params() <del> <del> def test_get_conn_extra(self): <del> assert self.db_hook_extra.get_conn() == self.conn <del> <del> def test_key_pair_auth_encrypted_extra(self): <del> self.conn.extra_dejson = { <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'private_key_file': self.encrypted_private_key, <del> } <del> <del> params = self.db_hook_extra._get_conn_params() <del> assert 'private_key' in params <del> <del> def test_key_pair_auth_not_encrypted_extra(self): <del> self.conn.extra_dejson = { <del> 'database': 'db', <del> 'account': 'airflow', <del> 'warehouse': 'af_wh', <del> 'region': 'af_region', <del> 'role': 'af_role', <del> 'private_key_file': self.non_encrypted_private_key, <del> } <del> <del> self.conn.password = '' <del> params = self.db_hook_extra._get_conn_params() <del> assert 'private_key' in params <del> <del> self.conn.password = None <del> params = self.db_hook_extra._get_conn_params() <del> assert 'private_key' in params <add> with unittest.mock.patch.dict( <add> 'os.environ', AIRFLOW_CONN_SNOWFLAKE_DEFAULT=Connection(**BASE_CONNECTION_KWARGS).get_uri() <add> ): <add> hook = SnowflakeHook() <add> status, msg = hook.test_connection() <add> assert status is False <add> assert msg == 'Connection Errors' <add> mock_run.assert_called_once_with(sql='select 1')
1
Text
Text
clarify reactdom.render usage
bff8e3704928292d4643462dcef70266e382acd0
<ide><path>guide/english/certifications/front-end-libraries/react/render-a-class-component-to-the-dom/index.md <ide> class TypesOfVehicles extends React.Component { <ide> ); <ide> } <ide> } <del>ReactDOM.render(<TypesOfVehicles />,'node-id') <add>ReactDOM.render(<TypesOfVehicles />, document.getElementById('node-id')) <ide> ``` <ide> The ReactDOM.render syntax may be a little tricky, you need to use the triangle brackets when passing in a Class Component. Also the two subcomponents are declared behind the scenes, which may be confusing if you are used to all the variables being defined in the code editor and visible in front of you. <ide> <del>## Hint <del> - use document.getElementById('id') to get target node <del>## Relevant Link <add>### Hint <add> - use `document.getElementById('node-id')` to get target node whose id has the value 'node-id' <add>### Relevant Link <add> <ide> - [Rendering Elements](https://reactjs.org/docs/rendering-elements.html) <ide> <ide> ## Solution
1
Javascript
Javascript
remove lines with only spaces
013b99b61bd693b98d22b3dd2c9102a9d423c451
<ide><path>packages/container/lib/container.js <ide> function Container(registry, options) { <ide> <ide> // TODO - See note above about transpiler import workaround. <ide> if (!Registry) { Registry = requireModule('container/registry')['default']; } <del> <add> <ide> return new Registry(); <ide> }()); <ide> <ide><path>packages/ember-debug/lib/main.js <ide> Ember.runInDebug = function(func) { <ide> any specific FEATURES flag is truthy. <ide> <ide> This method is called automatically in debug canary builds. <del> <add> <ide> @private <ide> @method _warnIfUsingStrippedFeatureFlags <ide> @return {void} <ide> if (!Ember.testing) { <ide> // Complain if they're using FEATURE flags in builds other than canary <ide> Ember.FEATURES['features-stripped-test'] = true; <ide> var featuresWereStripped = true; <del> <add> <ide> if (Ember.FEATURES.isEnabled('features-stripped-test')) { <ide> featuresWereStripped = false; <ide> } <ide><path>packages/ember-routing/lib/location/hash_location.js <ide> export default EmberObject.extend({ <ide> getURL: function() { <ide> var originalPath = this.getHash().substr(1); <ide> var outPath = originalPath; <del> <add> <ide> if (outPath.charAt(0) !== '/') { <ide> outPath = '/'; <ide> <ide><path>packages/ember-routing/tests/location/hash_location_test.js <ide> test("HashLocation.getURL() returns a normal forward slash when there is no loca <ide> createLocation({ <ide> _location: mockBrowserLocation('/') <ide> }); <del> <add> <ide> equal(location.getURL(), '/'); <ide> }); <ide> <ide> test("HashLocation.willDestroy() cleans up hashchange event listener", function( <ide> <ide> // clean up <ide> Ember.$ = oldJquery; <del>}); <ide>\ No newline at end of file <add>}); <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> export default Mixin.create({ <ide> var found = this.find(function(item) { <ide> return item === obj; <ide> }); <del> <add> <ide> return found !== undefined; <ide> }, <ide> <ide><path>packages/ember-views/tests/views/view/stream_test.js <ide> test("the stream returned is labeled with the requested path", function() { <ide> controller: { <ide> name: 'Robert' <ide> }, <del> <add> <ide> foo: 'bar' <ide> }); <ide>
6
Python
Python
update ukrainian lemmatizer with new lookups
dda86118bd04f4b653e6e9e612998273a6011f4d
<ide><path>spacy/lang/uk/__init__.py <ide> from ..norm_exceptions import BASE_NORMS <ide> from ...util import update_exc, add_lookups <ide> from ...language import Language <add>from ...lookups import Lookups <ide> from ...attrs import LANG, NORM <ide> from .lemmatizer import UkrainianLemmatizer <ide> <ide> class UkrainianDefaults(Language.Defaults): <ide> stop_words = STOP_WORDS <ide> <ide> @classmethod <del> def create_lemmatizer(cls, nlp=None, **kwargs): <del> return UkrainianLemmatizer() <add> def create_lemmatizer(cls, nlp=None, lookups=None): <add> if lookups is None: <add> lookups = Lookups() <add> return UkrainianLemmatizer(lookups) <ide> <ide> <ide> class Ukrainian(Language): <ide><path>spacy/lang/uk/lemmatizer.py <ide> class UkrainianLemmatizer(Lemmatizer): <ide> _morph = None <ide> <del> def __init__(self): <del> super(UkrainianLemmatizer, self).__init__() <add> def __init__(self, lookups=None): <add> super(UkrainianLemmatizer, self).__init__(lookups) <ide> try: <ide> from pymorphy2 import MorphAnalyzer <ide> <ide> def normalize_univ_pos(univ_pos): <ide> return symbols_to_str[univ_pos] <ide> return None <ide> <del> def is_base_form(self, univ_pos, morphology=None): <del> # TODO <del> raise NotImplementedError <del> <del> def det(self, string, morphology=None): <del> return self(string, "det", morphology) <del> <del> def num(self, string, morphology=None): <del> return self(string, "num", morphology) <del> <del> def pron(self, string, morphology=None): <del> return self(string, "pron", morphology) <del> <ide> def lookup(self, string, orth=None): <ide> analyses = self._morph.parse(string) <ide> if len(analyses) == 1:
2
Python
Python
fix typo in example
6fb58d30b9a857089d1ce623ee5f90e56533160f
<ide><path>src/transformers/models/speech_to_text/modeling_speech_to_text.py <ide> def forward( <ide> >>> import soundfile as sf <ide> <ide> >>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") <del> >>> processor = Speech2Textprocessor.from_pretrained("facebook/s2t-small-librispeech-asr") <add> >>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr") <ide> <ide> >>> def map_to_array(batch): <ide> >>> speech, _ = sf.read(batch["file"]) <ide> def forward( <ide> >>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") <ide> >>> ds = ds.map(map_to_array) <ide> <del> >>> input_features = processor(ds["speech"][0], sampling_rate=16_000, return_tensors="pt").input_features # Batch size 1 <add> >>> input_features = processor(ds["speech"][0], sampling_rate=16000, return_tensors="pt").input_features # Batch size 1 <ide> >>> generated_ids = model.generate(input_ids=input_features) <ide> <ide> >>> transcription = processor.batch_decode(generated_ids)
1
Ruby
Ruby
reuse immutable objects
0aa5150f9fb81fc6cf9d7b7915c8d7b015e452a2
<ide><path>activerecord/lib/active_record/relation/from_clause.rb <ide> def empty? <ide> end <ide> <ide> def self.empty <del> new(nil, nil) <add> @empty ||= new(nil, nil) <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def not(opts, *rest) <ide> end <ide> end <ide> <add> FROZEN_EMPTY_ARRAY = [].freeze <ide> Relation::MULTI_VALUE_METHODS.each do |name| <ide> class_eval <<-CODE, __FILE__, __LINE__ + 1 <del> def #{name}_values # def select_values <del> @values[:#{name}] || [] # @values[:select] || [] <del> end # end <del> # <del> def #{name}_values=(values) # def select_values=(values) <del> assert_mutability! # assert_mutability! <del> @values[:#{name}] = values # @values[:select] = values <del> end # end <add> def #{name}_values <add> @values[:#{name}] || FROZEN_EMPTY_ARRAY <add> end <add> <add> def #{name}_values=(values) <add> assert_mutability! <add> @values[:#{name}] = values <add> end <ide> CODE <ide> end <ide> <ide> def bound_attributes <ide> result <ide> end <ide> <add> FROZEN_EMPTY_HASH = {}.freeze <ide> def create_with_value # :nodoc: <del> @values[:create_with] || {} <add> @values[:create_with] || FROZEN_EMPTY_HASH <ide> end <ide> <ide> alias extensions extending_values <ide> def check_if_method_has_arguments!(method_name, args) <ide> def structurally_compatible_for_or?(other) <ide> Relation::SINGLE_VALUE_METHODS.all? { |m| send("#{m}_value") == other.send("#{m}_value") } && <ide> (Relation::MULTI_VALUE_METHODS - [:extending]).all? { |m| send("#{m}_values") == other.send("#{m}_values") } && <del> (Relation::CLAUSE_METHODS - [:having, :where]).all? { |m| send("#{m}_clause") != other.send("#{m}_clause") } <add> (Relation::CLAUSE_METHODS - [:having, :where]).all? { |m| send("#{m}_clause") == other.send("#{m}_clause") } <ide> end <ide> <ide> def new_where_clause <ide><path>activerecord/lib/active_record/relation/where_clause.rb <ide> def invert <ide> end <ide> <ide> def self.empty <del> new([], []) <add> @empty ||= new([], []) <ide> end <ide> <ide> protected <ide><path>activerecord/test/cases/relation_test.rb <ide> def test_initialize_single_values <ide> (Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |method| <ide> assert_nil relation.send("#{method}_value"), method.to_s <ide> end <del> assert_equal({}, relation.create_with_value) <add> value = relation.create_with_value <add> assert_equal({}, value) <add> assert_predicate value, :frozen? <ide> end <ide> <ide> def test_multi_value_initialize <ide> relation = Relation.new(FakeKlass, :b, nil) <ide> Relation::MULTI_VALUE_METHODS.each do |method| <del> assert_equal [], relation.send("#{method}_values"), method.to_s <add> values = relation.send("#{method}_values") <add> assert_equal [], values, method.to_s <add> assert_predicate values, :frozen?, method.to_s <ide> end <ide> end <ide>
4
Ruby
Ruby
fix tests on action_mailer
e6b0b760cc8bac99765fc43b182505db73e6586b
<ide><path>actionmailer/lib/action_mailer/test_case.rb <ide> module Behavior <ide> <ide> include ActiveSupport::Testing::ConstantLookup <ide> include TestHelper <del> include Rails::Dom::Testing::Assertions::SelectorAssertions <add> include Rails::Dom::Testing::Assertions <ide> <ide> included do <ide> class_attribute :_mailer_class <ide><path>actionmailer/test/asset_host_test.rb <ide> def teardown <ide> <ide> def test_asset_host_as_string <ide> mail = AssetHostMailer.email_with_asset <del> assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip <add> assert_dom_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip <ide> end <ide> <ide> def test_asset_host_as_one_argument_proc <ide> def test_asset_host_as_one_argument_proc <ide> end <ide> } <ide> mail = AssetHostMailer.email_with_asset <del> assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip <add> assert_dom_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip <ide> end <ide> end <ide><path>actionmailer/test/base_test.rb <ide> require 'mailers/asset_mailer' <ide> <ide> class BaseTest < ActiveSupport::TestCase <add> include Rails::Dom::Testing::Assertions <add> <ide> setup do <ide> @original_delivery_method = ActionMailer::Base.delivery_method <ide> ActionMailer::Base.delivery_method = :test <ide> def welcome <ide> <ide> mail = AssetMailer.welcome <ide> <del> assert_equal(%{<img alt="Dummy" src="http://global.com/images/dummy.png" />}, mail.body.to_s.strip) <add> assert_dom_equal(%{<img alt="Dummy" src="http://global.com/images/dummy.png" />}, mail.body.to_s.strip) <ide> end <ide> <ide> test "assets tags should use a Mailer's asset_host settings when available" do <ide> def welcome <ide> <ide> mail = TempAssetMailer.welcome <ide> <del> assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip) <add> assert_dom_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip) <ide> end <ide> <ide> test 'the view is not rendered when mail was never called' do <ide><path>actionmailer/test/url_test.rb <ide> def test_signed_up_with_url <ide> <ide> expected.message_id = '<123@456>' <ide> created.message_id = '<123@456>' <del> assert_equal expected.encoded, created.encoded <add> assert_dom_equal expected.encoded, created.encoded <ide> <ide> assert_nothing_raised { UrlTestMailer.signed_up_with_url(@recipient).deliver_now } <ide> assert_not_nil ActionMailer::Base.deliveries.first <ide> delivered = ActionMailer::Base.deliveries.first <ide> <ide> delivered.message_id = '<123@456>' <del> assert_equal expected.encoded, delivered.encoded <add> assert_dom_equal expected.encoded, delivered.encoded <ide> end <ide> end
4
Java
Java
add constants for application/cbor to mediatype
83078eb6fdc6def52902a4f6abc3a4d347ccb485
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java <ide> public class MediaType extends MimeType implements Serializable { <ide> */ <ide> public static final String APPLICATION_ATOM_XML_VALUE = "application/atom+xml"; <ide> <add> /** <add> * Public constant media type for {@code application/cbor}. <add> * @since 5.2 <add> */ <add> public static final MediaType APPLICATION_CBOR; <add> <add> /** <add> * A String equivalent of {@link MediaType#APPLICATION_CBOR}. <add> * @since 5.2 <add> */ <add> public static final String APPLICATION_CBOR_VALUE = "application/cbor"; <add> <ide> /** <ide> * Public constant media type for {@code application/x-www-form-urlencoded}. <ide> */ <ide> public class MediaType extends MimeType implements Serializable { <ide> // Not using "valueOf' to avoid static init cost <ide> ALL = new MediaType("*", "*"); <ide> APPLICATION_ATOM_XML = new MediaType("application", "atom+xml"); <add> APPLICATION_CBOR = new MediaType("application", "cbor"); <ide> APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded"); <ide> APPLICATION_JSON = new MediaType("application", "json"); <ide> APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8); <ide><path>spring-web/src/main/java/org/springframework/http/codec/cbor/Jackson2CborDecoder.java <ide> public class Jackson2CborDecoder extends AbstractJackson2Decoder { <ide> <ide> public Jackson2CborDecoder() { <del> this(Jackson2ObjectMapperBuilder.cbor().build(), new MediaType("application", "cbor")); <add> this(Jackson2ObjectMapperBuilder.cbor().build(), MediaType.APPLICATION_CBOR); <ide> } <ide> <ide> public Jackson2CborDecoder(ObjectMapper mapper, MimeType... mimeTypes) { <ide><path>spring-web/src/main/java/org/springframework/http/codec/cbor/Jackson2CborEncoder.java <ide> public class Jackson2CborEncoder extends AbstractJackson2Encoder { <ide> <ide> public Jackson2CborEncoder() { <del> this(Jackson2ObjectMapperBuilder.cbor().build(), new MediaType("application", "cbor")); <add> this(Jackson2ObjectMapperBuilder.cbor().build(), MediaType.APPLICATION_CBOR); <ide> } <ide> <ide> public Jackson2CborEncoder(ObjectMapper mapper, MimeType... mimeTypes) { <ide><path>spring-web/src/main/java/org/springframework/http/converter/cbor/MappingJackson2CborHttpMessageConverter.java <ide> * <a href="https://github.com/FasterXML/jackson-dataformats-binary/tree/master/cbor"> <ide> * the dedicated Jackson 2.x extension</a>. <ide> * <del> * <p>By default, this converter supports {@code "application/cbor"} media type. This can be <add> * <p>By default, this converter supports {@value MediaType#APPLICATION_CBOR_VALUE} media type. This can be <ide> * overridden by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property. <ide> * <ide> * <p>The default constructor uses the default configuration provided by {@link Jackson2ObjectMapperBuilder}. <ide> public MappingJackson2CborHttpMessageConverter() { <ide> * @see Jackson2ObjectMapperBuilder#cbor() <ide> */ <ide> public MappingJackson2CborHttpMessageConverter(ObjectMapper objectMapper) { <del> super(objectMapper, new MediaType("application", "cbor")); <add> super(objectMapper, MediaType.APPLICATION_CBOR); <ide> Assert.isInstanceOf(CBORFactory.class, objectMapper.getFactory(), "CBORFactory required"); <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java <ide> private Properties getDefaultMediaTypes() { <ide> defaultMediaTypes.put("smile", "application/x-jackson-smile"); <ide> } <ide> if (jackson2CborPresent) { <del> defaultMediaTypes.put("cbor", "application/cbor"); <add> defaultMediaTypes.put("cbor", MediaType.APPLICATION_CBOR_VALUE); <ide> } <ide> return defaultMediaTypes; <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> protected Map<String, MediaType> getDefaultMediaTypes() { <ide> map.put("smile", MediaType.valueOf("application/x-jackson-smile")); <ide> } <ide> if (jackson2CborPresent) { <del> map.put("cbor", MediaType.valueOf("application/cbor")); <add> map.put("cbor", MediaType.APPLICATION_CBOR); <ide> } <ide> return map; <ide> }
6
Java
Java
add systrace to render logic
8394f9b553fc4349cd8fab4737d8f98ec5525b9d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java <ide> public void measureLayoutRelativeToParent( <ide> * Invoked at the end of the transaction to commit any updates to the node hierarchy. <ide> */ <ide> public void dispatchViewUpdates(int batchId) { <del> updateViewHierarchy(); <del> mNativeViewHierarchyOptimizer.onBatchComplete(); <del> mOperationsQueue.dispatchViewUpdates(batchId); <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "UIImplementation.dispatchViewUpdates") <add> .arg("batchId", batchId) <add> .flush(); <add> try { <add> updateViewHierarchy(); <add> mNativeViewHierarchyOptimizer.onBatchComplete(); <add> mOperationsQueue.dispatchViewUpdates(batchId); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> } <ide> <ide> protected void updateViewHierarchy() { <del> for (int i = 0; i < mShadowNodeRegistry.getRootNodeCount(); i++) { <del> int tag = mShadowNodeRegistry.getRootTag(i); <del> ReactShadowNode cssRoot = mShadowNodeRegistry.getNode(tag); <del> notifyOnBeforeLayoutRecursive(cssRoot); <add> Systrace.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "UIImplementation.updateViewHierarchy"); <add> try { <add> for (int i = 0; i < mShadowNodeRegistry.getRootNodeCount(); i++) { <add> int tag = mShadowNodeRegistry.getRootTag(i); <add> ReactShadowNode cssRoot = mShadowNodeRegistry.getNode(tag); <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "UIImplementation.notifyOnBeforeLayoutRecursive") <add> .arg("rootTag", cssRoot.getReactTag()) <add> .flush(); <add> try { <add> notifyOnBeforeLayoutRecursive(cssRoot); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> <del> calculateRootLayout(cssRoot); <del> applyUpdatesRecursive(cssRoot, 0f, 0f); <add> calculateRootLayout(cssRoot); <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "UIImplementation.applyUpdatesRecursive") <add> .arg("rootTag", cssRoot.getReactTag()) <add> .flush(); <add> try { <add> applyUpdatesRecursive(cssRoot, 0f, 0f); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> } <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java <ide> public void enqueueUIBlock(UIBlock block) { <ide> } <ide> <ide> /* package */ void dispatchViewUpdates(final int batchId) { <del> // Store the current operation queues to dispatch and create new empty ones to continue <del> // receiving new operations <del> final ArrayList<UIOperation> operations = mOperations.isEmpty() ? null : mOperations; <del> if (operations != null) { <del> mOperations = new ArrayList<>(); <del> } <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "UIImplementation.dispatchViewUpdates") <add> .arg("batchId", batchId) <add> .flush(); <add> try { <add> // Store the current operation queues to dispatch and create new empty ones to continue <add> // receiving new operations <add> final ArrayList<UIOperation> operations = mOperations.isEmpty() ? null : mOperations; <add> if (operations != null) { <add> mOperations = new ArrayList<>(); <add> } <ide> <del> final UIOperation[] nonBatchedOperations; <del> synchronized (mNonBatchedOperationsLock) { <del> if (!mNonBatchedOperations.isEmpty()) { <del> nonBatchedOperations = <del> mNonBatchedOperations.toArray(new UIOperation[mNonBatchedOperations.size()]); <del> mNonBatchedOperations.clear(); <del> } else { <del> nonBatchedOperations = null; <add> final UIOperation[] nonBatchedOperations; <add> synchronized (mNonBatchedOperationsLock) { <add> if (!mNonBatchedOperations.isEmpty()) { <add> nonBatchedOperations = <add> mNonBatchedOperations.toArray(new UIOperation[mNonBatchedOperations.size()]); <add> mNonBatchedOperations.clear(); <add> } else { <add> nonBatchedOperations = null; <add> } <ide> } <del> } <ide> <del> if (mViewHierarchyUpdateDebugListener != null) { <del> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateEnqueued(); <del> } <add> if (mViewHierarchyUpdateDebugListener != null) { <add> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateEnqueued(); <add> } <ide> <del> synchronized (mDispatchRunnablesLock) { <del> mDispatchUIRunnables.add( <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "acquiring mDispatchRunnablesLock") <add> .arg("batchId", batchId) <add> .flush(); <add> synchronized (mDispatchRunnablesLock) { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> mDispatchUIRunnables.add( <ide> new Runnable() { <del> @Override <del> public void run() { <del> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "DispatchUI") <del> .arg("BatchId", batchId) <del> .flush(); <del> try { <del> // All nonBatchedOperations should be executed before regular operations as <del> // regular operations may depend on them <del> if (nonBatchedOperations != null) { <del> for (UIOperation op : nonBatchedOperations) { <del> op.execute(); <del> } <del> } <del> <del> if (operations != null) { <del> for (int i = 0; i < operations.size(); i++) { <del> operations.get(i).execute(); <del> } <del> } <del> <del> // Clear layout animation, as animation only apply to current UI operations batch. <del> mNativeViewHierarchyManager.clearLayoutAnimation(); <del> <del> if (mViewHierarchyUpdateDebugListener != null) { <del> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateFinished(); <del> } <del> } catch (Exception e) { <del> mIsInIllegalUIState = true; <del> throw e; <del> } finally { <del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <del> } <del> } <del> }); <del> } <del> <del> // In the case where the frame callback isn't enqueued, the UI isn't being displayed or is being <del> // destroyed. In this case it's no longer important to align to frames, but it is imporant to make <del> // sure any late-arriving UI commands are executed. <del> if (!mIsDispatchUIFrameCallbackEnqueued) { <del> UiThreadUtil.runOnUiThread( <add> @Override <add> public void run() { <add> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "DispatchUI") <add> .arg("BatchId", batchId) <add> .flush(); <add> try { <add> // All nonBatchedOperations should be executed before regular operations as <add> // regular operations may depend on them <add> if (nonBatchedOperations != null) { <add> for (UIOperation op : nonBatchedOperations) { <add> op.execute(); <add> } <add> } <add> <add> if (operations != null) { <add> for (int i = 0; i < operations.size(); i++) { <add> operations.get(i).execute(); <add> } <add> } <add> <add> // Clear layout animation, as animation only apply to current UI operations batch. <add> mNativeViewHierarchyManager.clearLayoutAnimation(); <add> <add> if (mViewHierarchyUpdateDebugListener != null) { <add> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateFinished(); <add> } <add> } catch (Exception e) { <add> mIsInIllegalUIState = true; <add> throw e; <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> } <add> }); <add> } <add> <add> // In the case where the frame callback isn't enqueued, the UI isn't being displayed or is being <add> // destroyed. In this case it's no longer important to align to frames, but it is imporant to make <add> // sure any late-arriving UI commands are executed. <add> if (!mIsDispatchUIFrameCallbackEnqueued) { <add> UiThreadUtil.runOnUiThread( <ide> new GuardedRunnable(mReactApplicationContext) { <ide> @Override <ide> public void runGuarded() { <ide> flushPendingBatches(); <ide> } <ide> }); <add> } <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide>
2
Text
Text
fix typo in changelog.md
bde2b3e39724457147001e66a6dc9af1a5360805
<ide><path>CHANGELOG.md <ide> * **fs**: corruption can be caused by `fs.writeFileSync()` and append-mode `fs.writeFile()` and `fs.writeFileSync()` under certain circumstances, reported in [#1058](https://github.com/iojs/io.js/issues/1058), fixed in [#1063](https://github.com/iojs/io.js/pull/1063) (Olov Lassus). <ide> * **iojs**: an "internal modules" API has been introduced to allow core code to share JavaScript modules internally only without having to expose them as a public API, this feature is for core-only [#848](https://github.com/iojs/io.js/pull/848) (Vladimir Kurchatkin). <ide> * **timers**: two minor problems with timers have been fixed: <del> - `Timer#close()` is now properly idempotent [#1288](https://github.com/iojs/io.js/issues/1288) (Petka Antonov). <add> - `Timer.close()` is now properly idempotent [#1288](https://github.com/iojs/io.js/issues/1288) (Petka Antonov). <ide> - `setTimeout()` will only run the callback once now after an `unref()` during the callback [#1231](https://github.com/iojs/io.js/pull/1231) (Roman Reiss). <ide> - NOTE: there are still other unresolved concerns with the timers code, such as [#1152](https://github.com/iojs/io.js/pull/1152). <ide> * **Windows**: a "delay-load hook" has been added for compiled add-ons on Windows that should alleviate some of the problems that Windows users may be experiencing with add-ons in io.js [#1251](https://github.com/iojs/io.js/pull/1251) (Bert Belder).
1