content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | update usage with react doc | 10551a1e1e691882e51e8b94c01079cf5aea629b | <ide><path>docs/basics/UsageWithReact.md
<ide> Let’s write the components! We begin with the presentational components, so we
<ide>
<ide> ### Presentational Components
<ide>
<del>These are all normal React components, so we'll not stop and examine them in detail. Here they are:
<add>These are all normal React components, so we'll not stop and examine them in detail. We write functional stateless components unless we need to use either React state or the React life-cycle functions.
<ide>
<ide> #### `components/Todo.js`
<ide>
<ide> export default Link
<ide>
<ide> ### Container Components
<ide>
<add>We will now write the container components. Container components use connect() to retrieve data from Redux state.
<add>
<ide> #### `containers/AddTodo.js`
<ide>
<ide> ```js
<ide> import { connect } from "react-redux";
<ide> import { setVisibilityFilter } from "../actions";
<ide> import Link from "../components/Link";
<ide>
<del>const mapStateToProps = (
<del> state,
<del> ownProps
<del>) => {
<del> return {
<del> active:
<del> ownProps.filter ===
<del> state.visibilityFilter
<del> };
<add>const mapStateToProps = (state, ownProps) => {
<add> return { active: ownProps.filter === state.visibilityFilter };
<ide> };
<ide>
<del>const mapDispatchToProps = (
<del> dispatch,
<del> ownProps
<del>) => {
<del> return {
<del> onClick: () => {
<del> dispatch(
<del> setVisibilityFilter(ownProps.filter)
<del> );
<del> }
<del> };
<add>const mapDispatchToProps = (dispatch, ownProps) => {
<add> return { onClick: () => { dispatch(setVisibilityFilter(ownProps.filter)); }};
<ide> }
<ide>
<del>const FilterLink = connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(Link);
<add>const FilterLink = connect(mapStateToProps, mapDispatchToProps)(Link);
<ide>
<ide> export default FilterLink
<ide> ```
<ide> const mapStateToProps = (
<ide> };
<ide>
<ide> const mapDispatchToProps = (dispatch) => {
<del> return {
<del> onTodoClick: (id) => {
<del> dispatch(toggleTodo(id));
<del> }
<del> };
<add> return { onTodoClick: (id) => { dispatch(toggleTodo(id)); }};
<ide> };
<ide>
<del>const VisibleTodoList = connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(TodoList);
<add>const VisibleTodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList);
<ide>
<ide> export default VisibleTodoList
<ide> ```
<ide>
<del>Then we'll write the `TodoApp` component that assembles the app.
<add>Then we’ll write the `TodoApp` component that renders these components together.
<ide>
<ide> #### `components/TodoApp.js`
<ide>
<ide> render(
<ide> );
<ide> ```
<ide>
<del>That’s it! Our todo app now functions correctly.
<del>
<ide> This makes our store instance available to the components below. (Internally, this is done via React’s [“context” feature](http://facebook.github.io/react/docs/context.html).)
<ide>
<ide> Then, we **wrap the components we want to connect to Redux with the `connect()` function from [`react-redux`](http://github.com/gaearon/react-redux)**. Try to only do this for a top-level component, or route handlers. While technically you can `connect()` any component in your app to Redux store, avoid doing this too deeply, because it will make the data flow harder to trace. | 1 |
Text | Text | add @othiym23 to list of collaborators | 34d1932135c9f53cf6d71f7a336d661bf3adf82d | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [mikeal](https://github.com/mikeal) - **Mikeal Rogers** <mikeal.rogers@gmail.com>
<ide> * [monsanto](https://github.com/monsanto) - **Christopher Monsanto** <chris@monsan.to>
<ide> * [Olegas](https://github.com/Olegas) - **Oleg Elifantiev** <oleg@elifantiev.ru>
<add>* [othiym23](https://github.com/othiym23) - **Forrest L Norvell** <ogd@aoaioxxysz.net>
<ide> * [petkaantonov](https://github.com/petkaantonov) - **Petka Antonov** <petka_antonov@hotmail.com>
<ide> * [phillipj](https://github.com/phillipj) - **Phillip Johnsen** <johphi@gmail.com>
<ide> * [pmq20](https://github.com/pmq20) - **Minqi Pan** <pmq2001@gmail.com> | 1 |
Javascript | Javascript | pass enhancer to base createstore | 72ae943646fe5e23e55e4b287744028bc46e593c | <ide><path>src/applyMiddleware.js
<ide> import compose from './compose'
<ide> * @returns {Function} A store enhancer applying the middleware.
<ide> */
<ide> export default function applyMiddleware(...middlewares) {
<del> return (createStore) => (reducer, initialState) => {
<del> var store = createStore(reducer, initialState)
<add> return (createStore) => (reducer, initialState, enhancer) => {
<add> var store = createStore(reducer, initialState, enhancer)
<ide> var dispatch = store.dispatch
<ide> var chain = []
<ide> | 1 |
Ruby | Ruby | add test case | aaf1af3cb83dad300c87e8abf2d1717cc528ff36 | <ide><path>activerecord/test/cases/validations/presence_validation_test.rb
<ide> require 'models/man'
<ide> require 'models/face'
<ide> require 'models/interest'
<add>require 'models/speedometer'
<add>require 'models/dashboard'
<ide>
<ide> class PresenceValidationTest < ActiveRecord::TestCase
<ide> class Boy < Man; end
<ide> def test_validates_presence_of_has_many_marked_for_destruction
<ide> i2.mark_for_destruction
<ide> assert b.invalid?
<ide> end
<add>
<add>
<add> def test_validates_presence_doesnt_convert_to_array
<add> Speedometer.validates_presence_of :dashboard
<add>
<add> dash = Dashboard.new
<add>
<add> # dashboard has to_a method
<add> def dash.to_a; ['(/)', '(\)']; end
<add>
<add> s = Speedometer.new
<add> s.dashboard = dash
<add>
<add> assert_nothing_raised { s.valid? }
<add> end
<ide> end | 1 |
Go | Go | remove use of deprecated pkg/system constants | f22ff19668e220fcc06182ca3dae14fd086e0a4a | <ide><path>builder/dockerfile/copy_windows.go
<ide> func fixPermissionsWindows(source, destination, SID string) error {
<ide> return err
<ide> }
<ide>
<del> return system.SetNamedSecurityInfo(windows.StringToUTF16Ptr(destination), system.SE_FILE_OBJECT, system.OWNER_SECURITY_INFORMATION|system.DACL_SECURITY_INFORMATION, sid, nil, dacl, nil)
<add> return system.SetNamedSecurityInfo(windows.StringToUTF16Ptr(destination), windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION, sid, nil, dacl, nil)
<ide> }
<ide>
<ide> func validateCopySourcePath(imageSource *imageMount, origPath, platform string) error { | 1 |
Javascript | Javascript | make ember.map keys and values private | 685d9e36fee7a8d99f3811a9f99758a1231ffaa7 | <ide><path>packages/ember-metal/lib/map.js
<ide> function copyNull(obj) {
<ide> }
<ide>
<ide> function copyMap(original, newObject) {
<del> var keys = original.keys.copy();
<del> var values = copyNull(original.values);
<add> var keys = original._keys.copy();
<add> var values = copyNull(original._values);
<ide>
<del> newObject.keys = keys;
<del> newObject.values = values;
<add> newObject._keys = keys;
<add> newObject._values = values;
<ide> newObject.size = original.size;
<ide>
<ide> return newObject;
<ide> deprecateProperty(OrderedSet.prototype, 'length', 'size');
<ide> */
<ide> function Map() {
<ide> if (this instanceof this.constructor) {
<del> this.keys = OrderedSet.create();
<del> this.keys._silenceRemoveDeprecation = true;
<del> this.values = create(null);
<add> this._keys = OrderedSet.create();
<add> this._keys._silenceRemoveDeprecation = true;
<add> this._values = create(null);
<ide> this.size = 0;
<ide> } else {
<ide> missingNew("OrderedSet");
<ide> Map.prototype = {
<ide> get: function(key) {
<ide> if (this.size === 0) { return; }
<ide>
<del> var values = this.values;
<add> var values = this._values;
<ide> var guid = guidFor(key);
<ide>
<ide> return values[guid];
<ide> Map.prototype = {
<ide> @return {Ember.Map}
<ide> */
<ide> set: function(key, value) {
<del> var keys = this.keys;
<del> var values = this.values;
<add> var keys = this._keys;
<add> var values = this._values;
<ide> var guid = guidFor(key);
<ide>
<ide> // ensure we don't store -0
<ide> Map.prototype = {
<ide> if (this.size === 0) { return false; }
<ide> // don't use ES6 "delete" because it will be annoying
<ide> // to use in browsers that are not ES6 friendly;
<del> var keys = this.keys;
<del> var values = this.values;
<add> var keys = this._keys;
<add> var values = this._values;
<ide> var guid = guidFor(key);
<ide>
<ide> if (keys.delete(key, guid)) {
<ide> Map.prototype = {
<ide> @return {Boolean} true if the item was present, false otherwise
<ide> */
<ide> has: function(key) {
<del> return this.keys.has(key);
<add> return this._keys.has(key);
<ide> },
<ide>
<ide> /**
<ide> Map.prototype = {
<ide> };
<ide> }
<ide>
<del> this.keys.forEach(cb);
<add> this._keys.forEach(cb);
<ide> },
<ide>
<ide> /**
<ide> @method clear
<ide> */
<ide> clear: function() {
<del> this.keys.clear();
<del> this.values = create(null);
<add> this._keys.clear();
<add> this._values = create(null);
<ide> this.size = 0;
<ide> },
<ide> | 1 |
Javascript | Javascript | use updated path | 309dd89e2a677ed5a66963bc76978e03e00d61d4 | <ide><path>test/WatchDetection.test.js
<ide> describe("WatchDetection", () => {
<ide> function step1() {
<ide> onChange = () => {
<ide> if (
<del> memfs.readFileSync("/bundle.js") &&
<add> memfs.readFileSync("/directory/bundle.js") &&
<ide> memfs
<del> .readFileSync("/bundle.js")
<add> .readFileSync("/directory/bundle.js")
<ide> .toString()
<ide> .indexOf("original") >= 0
<ide> )
<ide> describe("WatchDetection", () => {
<ide> onChange = () => {
<ide> if (
<ide> memfs
<del> .readFileSync("/bundle.js")
<add> .readFileSync("/directory/bundle.js")
<ide> .toString()
<ide> .indexOf("correct") >= 0
<ide> ) | 1 |
Javascript | Javascript | add test case | 2b210f98fa05857c15b5a7114e8df71a368fbe2a | <ide><path>test/ConfigTestCases.template.js
<ide> const describeCases = config => {
<ide> module in testConfig.modules
<ide> ) {
<ide> return testConfig.modules[module];
<del> } else return require(module);
<add> } else {
<add> return require(module.startsWith("node:")
<add> ? module.slice(5)
<add> : module);
<add> }
<ide> };
<ide>
<ide> results.push(
<ide><path>test/configCases/node/node-prefix/index.js
<add>import vm1 from "vm";
<add>import vm2 from "node:vm";
<add>
<add>it("should allow importing node builtin modules with the node: prefix", () => {
<add> expect(require("node:fs")).toBe(require("fs"));
<add> expect(require("node:path")).toBe(require("path"));
<add> expect(vm2).toBe(vm1);
<add>});
<ide><path>test/configCases/node/node-prefix/webpack.config.js
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> target: "node"
<add>}; | 3 |
Javascript | Javascript | remove string error from strictequal | fd520e7b4365dcda47dc209f8f1e3dd4a9d8665c | <ide><path>test/parallel/test-stream-writableState-uncorked-bufferedRequestCount.js
<ide> const stream = require('stream');
<ide> const writable = new stream.Writable();
<ide>
<ide> writable._writev = common.mustCall((chunks, cb) => {
<del> assert.strictEqual(chunks.length, 2, 'two chunks to write');
<add> assert.strictEqual(chunks.length, 2);
<ide> cb();
<ide> }, 1);
<ide> | 1 |
Javascript | Javascript | fix a spelling error | fabd0963c2c14d874ad17ebf65a9ed974ce0a905 | <ide><path>packages/learn/src/components/Donation/components/DonateForm.js
<ide> class DonateForm extends PureComponent {
<ide> donationState: {
<ide> ...state.donationState,
<ide> error:
<del> 'We need a valid email address to send your donation tax reciept to'
<add> 'We need a valid email address to send your donation tax receipt to'
<ide> }
<ide> }));
<ide> }
<ide> class DonateForm extends PureComponent {
<ide> return (
<ide> <div className='donation-email-container'>
<ide> <label>
<del> Email where we should send your donation tax reciept:
<add> Email where we should send your donation tax receipt:
<ide> <input
<ide> onChange={this.handleEmailChange}
<ide> placeholder='email@example.com' | 1 |
Go | Go | add awslogs benchmarks | 84b03660dab03ac366d99ba817a5ec8523808386 | <ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go
<ide> const (
<ide> sequenceToken = "sequenceToken"
<ide> nextSequenceToken = "nextSequenceToken"
<ide> logline = "this is a log line\r"
<add> multilineLogline = "2017-01-01 01:01:44 This is a multiline log entry\r"
<ide> )
<ide>
<add>// Generates i multi-line events each with j lines
<add>func (l *logStream) logGenerator(lineCount int, multilineCount int) {
<add> for i := 0; i < multilineCount; i++ {
<add> l.Log(&logger.Message{
<add> Line: []byte(multilineLogline),
<add> Timestamp: time.Time{},
<add> })
<add> for j := 0; j < lineCount; j++ {
<add> l.Log(&logger.Message{
<add> Line: []byte(logline),
<add> Timestamp: time.Time{},
<add> })
<add> }
<add> }
<add>}
<add>
<ide> func TestNewAWSLogsClientUserAgentHandler(t *testing.T) {
<ide> info := logger.Info{
<ide> Config: map[string]string{
<ide> func TestCollectBatchMultilinePattern(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func BenchmarkCollectBatch(b *testing.B) {
<add> for i := 0; i < b.N; i++ {
<add> mockClient := newMockClient()
<add> stream := &logStream{
<add> client: mockClient,
<add> logGroupName: groupName,
<add> logStreamName: streamName,
<add> sequenceToken: aws.String(sequenceToken),
<add> messages: make(chan *logger.Message),
<add> }
<add> mockClient.putLogEventsResult <- &putLogEventsResult{
<add> successResult: &cloudwatchlogs.PutLogEventsOutput{
<add> NextSequenceToken: aws.String(nextSequenceToken),
<add> },
<add> }
<add> ticks := make(chan time.Time)
<add> newTicker = func(_ time.Duration) *time.Ticker {
<add> return &time.Ticker{
<add> C: ticks,
<add> }
<add> }
<add>
<add> go stream.collectBatch()
<add> stream.logGenerator(10, 100)
<add> ticks <- time.Time{}
<add> stream.Close()
<add> }
<add>}
<add>
<add>func BenchmarkCollectBatchMultilinePattern(b *testing.B) {
<add> for i := 0; i < b.N; i++ {
<add> mockClient := newMockClient()
<add> multilinePattern := regexp.MustCompile(`\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1,2][0-9]|3[0,1]) (?:[0,1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]`)
<add> stream := &logStream{
<add> client: mockClient,
<add> logGroupName: groupName,
<add> logStreamName: streamName,
<add> multilinePattern: multilinePattern,
<add> sequenceToken: aws.String(sequenceToken),
<add> messages: make(chan *logger.Message),
<add> }
<add> mockClient.putLogEventsResult <- &putLogEventsResult{
<add> successResult: &cloudwatchlogs.PutLogEventsOutput{
<add> NextSequenceToken: aws.String(nextSequenceToken),
<add> },
<add> }
<add> ticks := make(chan time.Time)
<add> newTicker = func(_ time.Duration) *time.Ticker {
<add> return &time.Ticker{
<add> C: ticks,
<add> }
<add> }
<add> go stream.collectBatch()
<add> stream.logGenerator(10, 100)
<add> ticks <- time.Time{}
<add> stream.Close()
<add> }
<add>}
<add>
<ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
<ide> mockClient := newMockClient()
<ide> multilinePattern := regexp.MustCompile("xxxx") | 1 |
Javascript | Javascript | add scrollview example | 158abfe8bfd20d05cd67c6e861d5db02b4420916 | <ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js
<ide> const React = require('react');
<ide> const {
<ide> Platform,
<ide> ScrollView,
<add> Picker,
<ide> StyleSheet,
<ide> Text,
<ide> TouchableOpacity,
<ide> View,
<add> TextInput,
<add> RefreshControl,
<ide> } = require('react-native');
<ide>
<ide> const nullthrows = require('nullthrows');
<ide>
<add>import {useState, useCallback} from 'react';
<ide> import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
<ide>
<ide> exports.displayName = 'ScrollViewExample';
<ide> exports.examples = [
<ide> return <EnableDisableList />;
<ide> },
<ide> },
<add> {
<add> title: '<ScrollView> Content\n',
<add> description: 'Adjust properties of content inside ScrollView.',
<add> render: function(): React.Node {
<add> return <ContentExample />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Deceleration Rate\n',
<add> description:
<add> 'Determines how quickly the scroll view decelerates after the user lifts their finger.',
<add> render: function(): React.Node {
<add> return <DecelerationRateExample />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Enable & Disable Scrolling Behavior\n',
<add> description:
<add> 'DirectionalLockEnabled (iOS), disableIntervalMomentum, disableScrollViewPanResponder can be enabled or disabled.',
<add> render: function(): React.Node {
<add> return <DisableEnable />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Invert Sticky Headers\n',
<add> description:
<add> 'If sticky headers should stick at the bottom instead of the top of the ScrollView. This is usually used with inverted ScrollViews.',
<add> render: function(): React.Node {
<add> return <InvertStickyHeaders />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Keyboard Options\n',
<add> description:
<add> 'Toggle the keyboard using the search bar and determine keyboard behavior in response to drag and tap.',
<add> render: function(): React.Node {
<add> return <KeyboardExample />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> OnContentSizeChange\n',
<add> description:
<add> 'The text below will change when scrollable content view of the ScrollView changes.',
<add> render: function(): React.Node {
<add> return <OnContentSizeChange />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> OnMomentumScroll\n',
<add> description:
<add> 'An alert will be called when the momentum scroll starts or ends.',
<add> render: function(): React.Node {
<add> return <OnMomentumScroll />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> OnScroll Options\n',
<add> description:
<add> 'Change the behavior of onScroll using these options: onScrollBeginDrag, onScrollEndDrag, onScrollToTop (iOS), and overScrollMode (Android).',
<add> render: function(): React.Node {
<add> return <OnScrollOptions />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> RefreshControl\n',
<add> description: 'Pull down to see RefreshControl indicator.',
<add> render: function(): React.Node {
<add> return <RefreshControlExample />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Remove Clipped Subviews\n',
<add> description:
<add> 'When true, offscreen child views (whose overflow value is hidden) are removed from their native backing superview when offscreen.',
<add> render: function(): React.Node {
<add> return <RemoveClippedSubviews />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> Scroll Indicator\n',
<add> description: 'Adjust properties of the scroll indicator.',
<add> render: function(): React.Node {
<add> return <ScrollIndicatorExample />;
<add> },
<add> },
<add> {
<add> title: '<ScrollView> SnapTo Options\n',
<add> description: 'Adjust properties of snapping to the scroll view.',
<add> render: function(): React.Node {
<add> return <SnapToOptions />;
<add> },
<add> },
<ide> ];
<ide> if (Platform.OS === 'ios') {
<ide> exports.examples.push({
<ide> if (Platform.OS === 'ios') {
<ide> return <CenterContentList />;
<ide> },
<ide> });
<add> exports.examples.push({
<add> title: '<ScrollView> Always Bounces\n',
<add> description: 'Always bounce vertically or horizontally.',
<add> render: function(): React.Node {
<add> return (
<add> <>
<add> <Text style={styles.text}>Vertical</Text>
<add> <BouncesExampleVertical />
<add> <Text style={styles.text}>Horizontal</Text>
<add> <BouncesExampleHorizontal />
<add> </>
<add> );
<add> },
<add> });
<add> exports.examples.push({
<add> title: '<ScrollView> Bounces & Bounces Zoom\n',
<add> description: 'There are different options for bouncing behavior.',
<add> render: function(): React.Node {
<add> return <BouncesExample />;
<add> },
<add> });
<add> exports.examples.push({
<add> title: '<ScrollView> Indicator Style\n',
<add> description: 'There are different options for indicator style colors.',
<add> render: function(): React.Node {
<add> return <IndicatorStyle />;
<add> },
<add> });
<add> exports.examples.push({
<add> title: '<ScrollView> Maximum & Minimum Zoom Scale\n',
<add> description: 'Set the maximum and minimum allowed zoom scale.',
<add> render: function(): React.Node {
<add> return <MaxMinZoomScale />;
<add> },
<add> });
<add> exports.examples.push({
<add> title: '<ScrollView> Maximum & Minimum Zoom Scale\n',
<add> description: 'Set the maximum and minimum allowed zoom scale.',
<add> render: function(): React.Node {
<add> return <MaxMinZoomScale />;
<add> },
<add> });
<add> exports.examples.push({
<add> title: '<ScrollView> ScrollTo Options\n',
<add> description:
<add> 'Toggle scrollToOverflowEnabled and scrollsToTop. When scrollToOverflowEnabled is true, the scroll view can be programmatically scrolled beyond its content size. When scrollsToTop is true, the scroll view scrolls to top when the status bar is tapped.',
<add> render: function(): React.Node {
<add> return <ScrollToOptions />;
<add> },
<add> });
<add>} else {
<add> exports.examples.push({
<add> title: '<ScrollView> EndFillColor & FadingEdgeLength\n',
<add> description: 'Toggle to set endFillColor and fadingEdgeLength.',
<add> render: function(): React.Node {
<add> return <EndFillColorFadingEdgeLen />;
<add> },
<add> });
<ide> }
<ide>
<add>const AndroidScrollBarOptions = () => {
<add> const [persistentScrollBar, setPersistentScrollBar] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> persistentScrollbar={persistentScrollBar}>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label={'persistentScrollBar: ' + persistentScrollBar.toString()}
<add> onPress={() => setPersistentScrollBar(!persistentScrollBar)}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const EndFillColorFadingEdgeLen = () => {
<add> const [endFillColor, setEndFillColor] = useState('');
<add> const [fadingEdgeLen, setFadingEdgeLen] = useState(0);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> endFillColor={endFillColor}
<add> fadingEdgeLength={fadingEdgeLen}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label={endFillColor === '' ? 'setEndFillColor' : 'resetEndFillColor'}
<add> onPress={() =>
<add> endFillColor === '' ? setEndFillColor('#A9DFD0') : setEndFillColor('')
<add> }
<add> />
<add> <Button
<add> label={fadingEdgeLen === 0 ? 'setFadingEdgeLen' : 'resetFadingEdgeLen'}
<add> onPress={() =>
<add> fadingEdgeLen === 0 ? setFadingEdgeLen(300) : setFadingEdgeLen(0)
<add> }
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const SnapToOptions = () => {
<add> const [snapToAlignment, setSnapToAlignment] = useState('start');
<add> const snapToAlignmentModes = ['start', 'center', 'end'];
<add> const [snapToEnd, setSnapToEnd] = useState(true);
<add> const [snapToInterval, setSnapToInterval] = useState(0);
<add> const [snapToOffsets, setSnapToOffsets] = useState([]);
<add> const [snapToStart, setSnapToStart] = useState(true);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> snapToAlignment={snapToAlignment}
<add> snapToEnd={snapToEnd}
<add> snapToInterval={snapToInterval}
<add> snapToOffsets={snapToOffsets}
<add> snapToStart={snapToStart}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> {Platform.OS === 'ios' ? (
<add> <>
<add> <Text style={styles.rowTitle}>Snap to Alignment Mode</Text>
<add> <Picker
<add> selectedValue={snapToAlignment}
<add> onValueChange={value => {
<add> if (value === 'start' || value === 'center' || value === 'end')
<add> setSnapToAlignment(value);
<add> }}
<add> itemStyle={styles.pickerItem}>
<add> {snapToAlignmentModes.map(label => {
<add> return <Picker.Item label={label} value={label} key={label} />;
<add> })}
<add> </Picker>
<add> </>
<add> ) : null}
<add> <Button
<add> label={'snapToEnd: ' + snapToEnd.toString()}
<add> onPress={() => setSnapToEnd(!snapToEnd)}
<add> />
<add> <Button
<add> label={'snapToStart: ' + snapToStart.toString()}
<add> onPress={() => setSnapToStart(!snapToStart)}
<add> />
<add> <Button
<add> label={
<add> snapToInterval === 0 ? 'setSnapToInterval' : 'reset snapToInterval'
<add> }
<add> onPress={() =>
<add> snapToInterval === 0 ? setSnapToInterval(2) : setSnapToInterval(0)
<add> }
<add> />
<add> <Button
<add> label={
<add> snapToOffsets === [] ? 'setSnapToOffsets' : 'reset snapToOffsets'
<add> }
<add> onPress={() =>
<add> snapToOffsets === []
<add> ? setSnapToOffsets([2, 4, 6, 8, 10])
<add> : setSnapToOffsets([])
<add> }
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const ScrollToOptions = () => {
<add> const [scrollToOverflowEnabled, setScrollToOverflowEnabled] = useState(false);
<add> const [scrollsToTop, setScrollsToTop] = useState(true);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> scrollToOverflowEnabled={scrollToOverflowEnabled}
<add> scrollsToTop={scrollsToTop}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label={'scrollToOverflowEnabled: ' + scrollToOverflowEnabled.toString()}
<add> onPress={() => setScrollToOverflowEnabled(!scrollToOverflowEnabled)}
<add> />
<add> <Button
<add> label={'scrollsToTop: ' + scrollsToTop.toString()}
<add> onPress={() => setScrollsToTop(!scrollsToTop)}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const ScrollIndicatorExample = () => {
<add> const [scrollIndicatorInsets, setScrollIndicatorInsets] = useState(null);
<add> const [showsHorizontalScrollIndic, setShowsHorizontalScrollIndic] = useState(
<add> true,
<add> );
<add> const [showsVerticallScrollIndic, setShowsVerticalScrollIndic] = useState(
<add> true,
<add> );
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> contentInset={{top: 10, bottom: 10, left: 10, right: 10}}
<add> scrollIndicatorInsets={scrollIndicatorInsets}
<add> showsHorizontalScrollIndicator={showsHorizontalScrollIndic}
<add> showsVerticalScrollIndicator={showsVerticallScrollIndic}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label={
<add> scrollIndicatorInsets == null
<add> ? 'setScrollIndicatorInsets'
<add> : 'Reset scrollIndicatorInsets'
<add> }
<add> onPress={() =>
<add> scrollIndicatorInsets == null
<add> ? setScrollIndicatorInsets({
<add> top: 10,
<add> left: 10,
<add> bottom: 10,
<add> right: 10,
<add> })
<add> : setScrollIndicatorInsets(null)
<add> }
<add> />
<add> <Button
<add> label={
<add> 'showsHorizontalScrollIndicator: ' +
<add> showsHorizontalScrollIndic.toString()
<add> }
<add> onPress={() =>
<add> setShowsHorizontalScrollIndic(!showsHorizontalScrollIndic)
<add> }
<add> />
<add> <Button
<add> label={
<add> 'showsVerticalScrollIndicator: ' +
<add> showsVerticallScrollIndic.toString()
<add> }
<add> onPress={() => setShowsVerticalScrollIndic(!showsVerticallScrollIndic)}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const RemoveClippedSubviews = () => {
<add> const [removeClippedSubviews, setRemoveClippedSubviews] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> removeClippedSubviews={removeClippedSubviews}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label={'removeClippedSubviews: ' + removeClippedSubviews.toString()}
<add> onPress={() => setRemoveClippedSubviews(!removeClippedSubviews)}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const RefreshControlExample = () => {
<add> const [refreshing, setRefreshing] = useState(false);
<add> const onRefresh = useCallback(() => {
<add> setRefreshing(true);
<add> wait(2000).then(() => setRefreshing(false));
<add> }, []);
<add>
<add> const wait = timeout => {
<add> return new Promise(resolve => {
<add> setTimeout(resolve, timeout);
<add> });
<add> };
<add>
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> refreshControl={
<add> <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
<add> }
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> </View>
<add> );
<add>};
<add>
<add>const OnScrollOptions = () => {
<add> const [onScrollDrag, setOnScrollDrag] = useState('none');
<add> const [overScrollMode, setOverScrollMode] = useState('auto');
<add> const overScrollModeOptions = ['auto', 'always', 'never'];
<add> return (
<add> <View>
<add> <Text>onScroll: {onScrollDrag}</Text>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> onScrollBeginDrag={() => setOnScrollDrag('onScrollBeginDrag')}
<add> onScrollEndDrag={() => setOnScrollDrag('onScrollEndDrag')}
<add> onScrollToTop={() => setOnScrollDrag('onScrollToTop')}
<add> overScrollMode={overScrollMode}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> {Platform.OS === 'android' ? (
<add> <>
<add> <Text style={styles.rowTitle}>Over Scroll Mode</Text>
<add> <Picker
<add> selectedValue={overScrollMode}
<add> onValueChange={value => {
<add> if (value === 'always' || value === 'auto' || value === 'never')
<add> setOverScrollMode(value);
<add> }}
<add> itemStyle={styles.pickerItem}>
<add> {overScrollModeOptions.map(label => {
<add> return <Picker.Item label={label} value={label} key={label} />;
<add> })}
<add> </Picker>
<add> </>
<add> ) : null}
<add> </View>
<add> );
<add>};
<add>
<add>const OnMomentumScroll = () => {
<add> const [scroll, setScroll] = useState('none');
<add> return (
<add> <View>
<add> <Text>Scroll State: {scroll}</Text>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> onMomentumScrollBegin={() => setScroll('onMomentumScrollBegin')}
<add> onMomentumScrollEnd={() => setScroll('onMomentumScrollEnd')}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> </View>
<add> );
<add>};
<add>
<add>const OnContentSizeChange = () => {
<add> const [items, setItems] = useState(ITEMS);
<add> const [contentSizeChanged, setContentSizeChanged] = useState('original');
<add> return (
<add> <View>
<add> <Text>Content Size Changed: {contentSizeChanged}</Text>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> onContentSizeChange={() =>
<add> contentSizeChanged === 'original'
<add> ? setContentSizeChanged('changed')
<add> : setContentSizeChanged('original')
<add> }
<add> nestedScrollEnabled>
<add> {items.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> label="Change Content Size"
<add> onPress={() =>
<add> items === ITEMS
<add> ? setItems(['1', '2', '3', '4', '5'])
<add> : setItems(ITEMS)
<add> }
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const MaxMinZoomScale = () => {
<add> const [maxZoomScale, setMaxZoomScale] = useState('1.0');
<add> const [minZoomScale, setMinZoomScale] = useState('1.0');
<add> const [zoomScale, setZoomScale] = useState('1.0');
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> pinchGestureEnabled
<add> maximumZoomScale={maxZoomScale !== '' ? parseFloat(maxZoomScale) : 0.0}
<add> minimumZoomScale={minZoomScale !== '' ? parseFloat(minZoomScale) : 0.0}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Text style={styles.rowTitle}>Set Maximum Zoom Scale</Text>
<add> <TextInput
<add> style={styles.textInput}
<add> value={maxZoomScale}
<add> onChangeText={val => setMaxZoomScale(val)}
<add> keyboardType="decimal-pad"
<add> />
<add> <Text style={styles.rowTitle}>Set Minimum Zoom Scale</Text>
<add> <TextInput
<add> style={styles.textInput}
<add> value={minZoomScale.toString()}
<add> onChangeText={val => setMinZoomScale(val)}
<add> keyboardType="decimal-pad"
<add> />
<add> {Platform.OS === 'ios' ? (
<add> <>
<add> <Text style={styles.rowTitle}>Set Zoom Scale</Text>
<add> <TextInput
<add> style={styles.textInput}
<add> value={zoomScale.toString()}
<add> onChangeText={val => setZoomScale(val)}
<add> keyboardType="decimal-pad"
<add> />
<add> </>
<add> ) : null}
<add> </View>
<add> );
<add>};
<add>
<add>const KeyboardExample = () => {
<add> const [keyboardDismissMode, setKeyboardDismissMode] = useState('none');
<add> const [keyboardShouldPersistTaps, setKeyboardShouldPersistTaps] = useState(
<add> 'never',
<add> );
<add> const dismissOptions =
<add> Platform.OS === 'ios'
<add> ? ['none', 'on-drag', 'interactive']
<add> : ['none', 'on-drag'];
<add> const persistOptions = ['never', 'always', 'handled'];
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> keyboardDismissMode={keyboardDismissMode}
<add> keyboardShouldPersistTaps={keyboardShouldPersistTaps}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Text style={styles.rowTitle}>Keyboard Dismiss Mode</Text>
<add> <Picker
<add> selectedValue={keyboardDismissMode}
<add> onValueChange={value => {
<add> if (
<add> value === 'none' ||
<add> value === 'on-drag' ||
<add> value === 'interactive'
<add> )
<add> setKeyboardDismissMode(value);
<add> }}
<add> itemStyle={styles.pickerItem}>
<add> {dismissOptions.map(label => {
<add> return <Picker.Item label={label} value={label} key={label} />;
<add> })}
<add> </Picker>
<add> <Text style={styles.rowTitle}>Keyboard Should Persist taps</Text>
<add> <Picker
<add> selectedValue={keyboardShouldPersistTaps}
<add> onValueChange={value => {
<add> if (value === 'never' || value === 'always' || value === 'handled')
<add> setKeyboardShouldPersistTaps(value);
<add> }}
<add> itemStyle={styles.pickerItem}>
<add> {persistOptions.map(label => {
<add> return <Picker.Item label={label} value={label} key={label} />;
<add> })}
<add> </Picker>
<add> </View>
<add> );
<add>};
<add>
<add>const InvertStickyHeaders = () => {
<add> const [invertStickyHeaders, setInvertStickyHeaders] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> stickyHeaderIndices={[0]}
<add> invertStickyHeaders={invertStickyHeaders}
<add> nestedScrollEnabled>
<add> {<Text>STICKY HEADER</Text>}
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() => setInvertStickyHeaders(!invertStickyHeaders)}
<add> label={'invertStickyHeaders: ' + invertStickyHeaders.toString()}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const IndicatorStyle = () => {
<add> const [indicatorStyle, setIndicatorStyle] = useState('default');
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> indicatorStyle={indicatorStyle}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() =>
<add> indicatorStyle === 'default'
<add> ? setIndicatorStyle('white')
<add> : setIndicatorStyle('default')
<add> }
<add> label={'Indicator Style: ' + indicatorStyle}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const DisableEnable = () => {
<add> const [directionalLockEnabled, setDirectionalLockEnabled] = useState(false);
<add> const [disableIntervalMomentum, setDisableIntervalMomentum] = useState(false);
<add> const [
<add> disableScrollViewPanResponder,
<add> setDisableScrollViewPanResponder,
<add> ] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> contentInset={{top: 10, bottom: 10, left: 10, right: 10}}
<add> snapToInterval={0}
<add> directionalLockEnabled={directionalLockEnabled}
<add> disableIntervalMomentum={disableIntervalMomentum}
<add> disableScrollViewPanResponder={disableScrollViewPanResponder}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> {Platform.OS === 'ios' ? (
<add> <Button
<add> onPress={() => setDirectionalLockEnabled(!directionalLockEnabled)}
<add> label={'directionalLockEnabled: ' + directionalLockEnabled.toString()}
<add> />
<add> ) : null}
<add> <Button
<add> onPress={() => setDisableIntervalMomentum(!disableIntervalMomentum)}
<add> label={
<add> 'setDisableIntervalMomentum: ' + disableIntervalMomentum.toString()
<add> }
<add> />
<add> <Button
<add> onPress={() =>
<add> setDisableScrollViewPanResponder(!disableScrollViewPanResponder)
<add> }
<add> label={
<add> 'setDisableScrollViewPanResponder: ' +
<add> disableScrollViewPanResponder.toString()
<add> }
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const DecelerationRateExample = () => {
<add> const [decelRate, setDecelRate] = useState('normal');
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> decelerationRate={decelRate}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() =>
<add> decelRate === 'normal' ? setDecelRate('fast') : setDecelRate('normal')
<add> }
<add> label={'Deceleration Rate: ' + decelRate}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const ContentExample = () => {
<add> const [canCancelContentTouches, setCanCancelContentTouches] = useState(false);
<add> const [contentInset, setContentInset] = useState(null);
<add> const [contentContainerStyle, setContentContainerStyle] = useState(null);
<add> const [
<add> contentInsetAdjustmentBehavior,
<add> setContentInsetAdjustmentBehavior,
<add> ] = useState('never');
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> canCancelContentTouches={canCancelContentTouches}
<add> contentOffset={{x: 100, y: 0}}
<add> contentContainerStyle={contentContainerStyle}
<add> contentInset={contentInset}
<add> contentInsetAdjustmentBehavior={contentInsetAdjustmentBehavior}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> {Platform.OS === 'ios' ? (
<add> <>
<add> <Button
<add> onPress={() => setCanCancelContentTouches(!canCancelContentTouches)}
<add> label={
<add> 'canCancelContentTouches: ' + canCancelContentTouches.toString()
<add> }
<add> />
<add> <Button
<add> onPress={() =>
<add> contentInsetAdjustmentBehavior === 'never'
<add> ? setContentInsetAdjustmentBehavior('always')
<add> : setContentInsetAdjustmentBehavior('never')
<add> }
<add> label={
<add> contentInsetAdjustmentBehavior === 'never'
<add> ? "setContentInsetAdjustmentBehavior to 'always'"
<add> : 'reset content inset adjustment behavior'
<add> }
<add> />
<add> </>
<add> ) : null}
<add> <Button
<add> onPress={() =>
<add> contentContainerStyle === null
<add> ? setContentContainerStyle(styles.containerStyle)
<add> : setContentContainerStyle(null)
<add> }
<add> label={
<add> contentContainerStyle === null
<add> ? 'setContentContainerStyle'
<add> : 'reset content container style'
<add> }
<add> />
<add> <Button
<add> onPress={() =>
<add> contentInset === null
<add> ? setContentInset({top: 10, bottom: 10, left: 10, right: 10})
<add> : setContentInset(null)
<add> }
<add> label={
<add> contentInset === null ? 'setContentInset' : 'reset content inset'
<add> }
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const BouncesExample = () => {
<add> const [bounces, setBounces] = useState(false);
<add> const [bouncesZoom, setBouncesZoom] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> bounces={bounces}
<add> bouncesZoom={bouncesZoom}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() => setBounces(!bounces)}
<add> label={'Bounces: ' + bounces.toString()}
<add> />
<add> <Button
<add> onPress={() => setBouncesZoom(!bouncesZoom)}
<add> label={'Bounces Zoom: ' + bouncesZoom.toString()}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const BouncesExampleHorizontal = () => {
<add> const [bounce, setBounce] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> horizontal={true}
<add> alwaysBounceHorizontal={bounce}
<add> contentOffset={{x: 100, y: 0}}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() => setBounce(!bounce)}
<add> label={'Always Bounce Horizontal: ' + bounce.toString()}
<add> />
<add> </View>
<add> );
<add>};
<add>
<add>const BouncesExampleVertical = () => {
<add> const [bounce, setBounce] = useState(false);
<add> return (
<add> <View>
<add> <ScrollView
<add> style={[styles.scrollView, {height: 200}]}
<add> alwaysBounceVertical={bounce}
<add> contentOffset={{x: 100, y: 0}}
<add> nestedScrollEnabled>
<add> {ITEMS.map(createItemRow)}
<add> </ScrollView>
<add> <Button
<add> onPress={() => setBounce(!bounce)}
<add> label={'Always Bounce Vertical: ' + bounce.toString()}
<add> />
<add> </View>
<add> );
<add>};
<add>
<ide> class Item extends React.PureComponent<{|
<ide> msg?: string,
<ide> style?: ViewStyleProp,
<ide> const styles = StyleSheet.create({
<ide> borderRadius: 3,
<ide> minWidth: 96,
<ide> },
<add> containerStyle: {
<add> backgroundColor: '#aae3b6',
<add> },
<add> pickerItem: {
<add> fontSize: 16,
<add> },
<add> rowTitle: {
<add> flex: 1,
<add> fontWeight: 'bold',
<add> },
<add> textInput: {
<add> height: 40,
<add> borderColor: 'gray',
<add> borderWidth: 1,
<add> },
<ide> }); | 1 |
Ruby | Ruby | remove unused require | 3e0293a09293b0052ad443cc5eb67880032c83c6 | <ide><path>railties/lib/rails/generators/actions.rb
<del>require 'open-uri'
<del>
<ide> module Rails
<ide> module Generators
<ide> module Actions | 1 |
Javascript | Javascript | add named exports | 890c305dff01505e108b0b0d3f6fbd4def7cc23c | <ide><path>src/Immutable.js
<ide> export default {
<ide> fromJS: fromJS
<ide>
<ide> };
<add>
<add>export {
<add> Iterable,
<add>
<add> Seq,
<add> Collection,
<add> Map,
<add> OrderedMap,
<add> List,
<add> Stack,
<add> Set,
<add> OrderedSet,
<add>
<add> Record,
<add> Range,
<add> Repeat,
<add>
<add> is,
<add> fromJS
<add>} | 1 |
Ruby | Ruby | pull initialization code out of begin block | 0578f1ff5a5234a4e7ca59c49dc0b0bb414cb78a | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def binread(*open_args)
<ide> def atomic_write content
<ide> require "tempfile"
<ide> tf = Tempfile.new(basename.to_s, dirname)
<del> tf.binmode
<del> tf.write(content)
<del>
<ide> begin
<del> old_stat = stat
<del> rescue Errno::ENOENT
<del> old_stat = default_stat
<del> end
<add> tf.binmode
<add> tf.write(content)
<ide>
<del> uid = Process.uid
<del> gid = Process.groups.delete(old_stat.gid) { Process.gid }
<add> begin
<add> old_stat = stat
<add> rescue Errno::ENOENT
<add> old_stat = default_stat
<add> end
<ide>
<del> begin
<del> tf.chown(uid, gid)
<del> tf.chmod(old_stat.mode)
<del> rescue Errno::EPERM
<del> end
<add> uid = Process.uid
<add> gid = Process.groups.delete(old_stat.gid) { Process.gid }
<ide>
<del> File.rename(tf.path, self)
<del> ensure
<del> tf.close!
<add> begin
<add> tf.chown(uid, gid)
<add> tf.chmod(old_stat.mode)
<add> rescue Errno::EPERM
<add> end
<add>
<add> File.rename(tf.path, self)
<add> ensure
<add> tf.close!
<add> end
<ide> end
<ide>
<ide> def default_stat | 1 |
Mixed | Javascript | remove conflicting <head> tags in amp mode | 2d6a73cb66bec40105fec31d1117dd97ae3fe909 | <ide><path>errors/conflicting-amp-tag.md
<add># Conflicting AMP Tag
<add>
<add>#### Why This Error Occurred
<add>
<add>In AMP mode Next.js adds certain necessary tags automatically to comply with the AMP standard. You added a tag using `next/head` that conflicts with one of these automatically added tags.
<add>
<add>#### Possible Ways to Fix It
<add>
<add>Remove the tag mentioned in the error message from any `<Head></Head>` elements
<ide><path>packages/next/pages/_document.js
<ide> export class Head extends Component {
<ide> render() {
<ide> const {
<ide> ampEnabled,
<del> head,
<ide> styles,
<ide> amphtml,
<ide> assetPrefix,
<ide> export class Head extends Component {
<ide> const { _devOnlyInvalidateCacheQueryString } = this.context
<ide> const { page, buildId } = __NEXT_DATA__
<ide>
<add> let { head } = this.context._documentProps
<ide> let children = this.props.children
<ide> // show a warning if Head contains <title> (only in development)
<ide> if (process.env.NODE_ENV !== 'production') {
<ide> export class Head extends Component {
<ide> 'Warning: `Head` attribute `crossOrigin` is deprecated. https://err.sh/next.js/doc-crossorigin-deprecated'
<ide> )
<ide> }
<add> // show warning and remove conflicting amp head tags
<add> head = !amphtml ? head : React.Children.map(head, child => {
<add> if (!child) return child
<add> const { type, props } = child
<add> let badProp
<add>
<add> if (type === 'meta' && props.name === 'viewport') {
<add> badProp = 'name="viewport"'
<add> } else if (type === 'link' && props.rel === 'canonical') {
<add> badProp = 'rel="canonical"'
<add> }
<add>
<add> if (badProp) {
<add> console.warn(`Found conflicting amp tag "${child.type}" with conflicting prop ${badProp}. https://err.sh/next.js/conflicting-amp-tag`)
<add> return null
<add> }
<add> return child
<add> })
<ide> return (
<ide> <head {...this.props}>
<ide> {children}
<ide><path>test/integration/amphtml/pages/conflicting-tag.js
<add>import Head from 'next/head'
<add>
<add>export default () => (
<add> <amp-layout className='abc' layout='responsive' width='1' height='1'>
<add> <Head>
<add> <meta name='viewport' content='something :p' />
<add> </Head>
<add> <span>Hello World</span>
<add> </amp-layout>
<add>)
<ide><path>test/integration/amphtml/test/index.test.js
<ide> describe('AMP Usage', () => {
<ide> .attr('href')
<ide> ).toBe('/use-amp-hook')
<ide> })
<add>
<add> it('should remove conflicting amp tags', async () => {
<add> const html = await renderViaHTTP(appPort, '/conflicting-tag?amp=1')
<add> const $ = cheerio.load(html)
<add> await validateAMP(html)
<add> expect(
<add> $('meta[name=viewport]').attr('content')
<add> ).not.toBe('something :p')
<add> })
<ide> })
<ide>
<ide> describe('combined styles', () => { | 4 |
Python | Python | add tests for pipe.label_data | c2401fca411559c66fa4172886a24d4d632de162 | <ide><path>spacy/tests/pipeline/test_pipe_methods.py
<ide> import pytest
<ide> from spacy.language import Language
<del>from spacy.util import SimpleFrozenList
<add>from spacy.util import SimpleFrozenList, get_arg_names
<ide>
<ide>
<ide> @pytest.fixture
<ide> def test_pipe_methods_frozen():
<ide> nlp.components.sort()
<ide> with pytest.raises(NotImplementedError):
<ide> nlp.component_names.clear()
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "pipe",
<add> [
<add> "tagger",
<add> "parser",
<add> "ner",
<add> "textcat",
<add> pytest.param("morphologizer", marks=pytest.mark.xfail),
<add> ],
<add>)
<add>def test_pipe_label_data_exports_labels(pipe):
<add> nlp = Language()
<add> pipe = nlp.add_pipe(pipe)
<add> # Make sure pipe has pipe labels
<add> assert getattr(pipe, "label_data", None) is not None
<add> # Make sure pipe can be initialized with labels
<add> initialize = getattr(pipe, "initialize", None)
<add> assert initialize is not None
<add> assert "labels" in get_arg_names(initialize)
<add>
<add>
<add>@pytest.mark.parametrize("pipe", ["senter", "entity_linker"])
<add>def test_pipe_label_data_no_labels(pipe):
<add> nlp = Language()
<add> pipe = nlp.add_pipe(pipe)
<add> assert getattr(pipe, "label_data", None) is None
<add> initialize = getattr(pipe, "initialize", None)
<add> if initialize is not None:
<add> assert "labels" not in get_arg_names(initialize) | 1 |
Javascript | Javascript | remove cta and add current challenge button | d01ce3bbc11fb0736ed3ad81e8565c6d23c342b9 | <ide><path>client/src/components/Intro/index.js
<ide> import { Link, Spacer, Loader, FullWidthRow } from '../helpers';
<ide> import { Row, Col } from '@freecodecamp/react-bootstrap';
<ide> import { apiLocation } from '../../../config/env.json';
<ide> import { randomQuote } from '../../utils/get-words';
<add>import CurrentChallengeLink from '../helpers/CurrentChallengeLink';
<ide>
<ide> import './intro.css';
<ide>
<ide> const propTypes = {
<ide> complete: PropTypes.bool,
<add> completedChallengeCount: PropTypes.number,
<ide> isSignedIn: PropTypes.bool,
<ide> name: PropTypes.string,
<ide> navigate: PropTypes.func,
<ide> function Intro({
<ide> navigate,
<ide> pending,
<ide> complete,
<add> completedChallengeCount,
<ide> slug
<ide> }) {
<ide> if (pending && !complete) {
<ide> function Intro({
<ide> <Link className='btn btn-lg btn-primary btn-block' to='/settings'>
<ide> Update my account settings
<ide> </Link>
<add> {completedChallengeCount > 0 ? (
<add> <CurrentChallengeLink isLargeBtn={true}>
<add> Go to current challenge
<add> </CurrentChallengeLink>
<add> ) : (
<add> ''
<add> )}
<ide> </FullWidthRow>
<ide> <Spacer />
<ide> <Row className='text-center quote-partial'>
<ide> function Intro({
<ide> </Col>
<ide> </Row>
<ide> <Row>
<del> <Col sm={10} smOffset={1} xs={12}>
<del> <Spacer />
<del> <h4>
<del> If you are new to coding, we recommend you{' '}
<del> <Link to={slug}>start at the beginning</Link>.
<del> </h4>
<del> </Col>
<add> {completedChallengeCount < 15 ? (
<add> <Col sm={10} smOffset={1} xs={12}>
<add> <Spacer />
<add> <h4>
<add> If you are new to coding, we recommend you{' '}
<add> <Link to={slug}>start at the beginning</Link>.
<add> </h4>
<add> </Col>
<add> ) : (
<add> ''
<add> )}
<ide> </Row>
<ide> </>
<ide> );
<ide><path>client/src/components/helpers/CurrentChallengeLink.js
<ide> const currentChallengeApi = '/challenges/current-challenge';
<ide>
<ide> const propTypes = {
<ide> children: PropTypes.any,
<del> hardGoTo: PropTypes.func.isRequired
<add> hardGoTo: PropTypes.func.isRequired,
<add> isLargeBtn: PropTypes.bool
<ide> };
<ide>
<ide> const mapStateToProps = () => ({});
<ide> const createClickHandler = hardGoTo => e => {
<ide> return hardGoTo(`${apiLocation}${currentChallengeApi}`);
<ide> };
<ide>
<del>function CurrentChallengeLink({ children, hardGoTo }) {
<add>function CurrentChallengeLink({ children, hardGoTo, isLargeBtn }) {
<add> let classNames;
<add> if (isLargeBtn) {
<add> classNames = 'btn btn-lg btn-primary btn-block';
<add> } else {
<add> classNames = 'btn btn-cta-big btn-primary btn-block';
<add> }
<ide> return (
<ide> <a
<del> className='btn-cta-big btn btn-primary btn-block'
<add> className={classNames}
<ide> href={currentChallengeApi}
<ide> onClick={createClickHandler(hardGoTo)}
<ide> >
<ide><path>client/src/pages/learn.js
<ide> const propTypes = {
<ide> state: PropTypes.object,
<ide> user: PropTypes.shape({
<ide> name: PropTypes.string,
<del> username: PropTypes.string
<add> username: PropTypes.string,
<add> completedChallengeCount: PropTypes.number
<ide> })
<ide> };
<ide>
<ide> export const LearnPage = ({
<ide> isSignedIn,
<ide> navigate,
<ide> fetchState: { pending, complete },
<del> user: { name = '', username = '' },
<add> user: { name = '', username = '', completedChallengeCount = 0 },
<ide> data: {
<ide> challengeNode: {
<ide> fields: { slug }
<ide> export const LearnPage = ({
<ide> <Grid>
<ide> <Intro
<ide> complete={complete}
<add> completedChallengeCount={completedChallengeCount}
<ide> isSignedIn={isSignedIn}
<ide> name={name}
<ide> navigate={navigate} | 3 |
Text | Text | add v4.0.0-beta.2 to changelog | 4f403127602efca9ca81288bcabb1671a0212b1d | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.0.0-beta.2 (August 23, 2021)
<add>
<add>- [#19680](https://github.com/emberjs/ember.js/pull/19680) [DEPRECATION] Deprecate owner.inject per [RFC #680](https://github.com/emberjs/rfcs/blob/sn/owner-inject-deprecation/text/0680-implicit-injection-deprecation.md#1-deprecate-implicit-injection-on-target-object) and cleanup related deprecations that are `until: 4.0.0`.
<add>- [#19706](https://github.com/emberjs/ember.js/pull/19706) [BUGFIX] Explicitly drop Node 10 support to match support policy.
<add>- [#19650](https://github.com/emberjs/ember.js/pull/19650) [CLEANUP] Remove deprecated mouse events
<add>- [#19675](https://github.com/emberjs/ember.js/pull/19675) [CLEANUP] Remove jQuery usage from ember-testing
<add>- [#19704](https://github.com/emberjs/ember.js/pull/19704) [CLEANUP] Remove template-compiler.registerPlugin
<add>- [#19707](https://github.com/emberjs/ember.js/pull/19707) [CLEANUP] Remove Application Controller Router Properties
<add>
<ide> ### v4.0.0-beta.1 (August 17, 2021)
<ide>
<ide> - [#19649](https://github.com/emberjs/ember.js/pull/19649) / [#19692](https://github.com/emberjs/ember.js/pull/19692) [DEPRECATION] Add deprecation warning to Ember.assign implementing [RFC #750](https://github.com/emberjs/rfcs/blob/master/text/0750-deprecate-ember-assign.md). | 1 |
Ruby | Ruby | check nil? || empty? instead of to_s.empty? | a5895ad1fe1ae4ae296c71483e7a77d87606cdd8 | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def remove_from_cflags val
<ide> def append keys, value, separator = ' '
<ide> value = value.to_s
<ide> Array(keys).each do |key|
<del> unless self[key].to_s.empty?
<del> self[key] = self[key] + separator + value
<del> else
<add> old = self[key]
<add> if old.nil? || old.empty?
<ide> self[key] = value
<add> else
<add> self[key] += separator + value
<ide> end
<ide> end
<ide> end
<ide> def prepend keys, value, separator = ' '
<ide> value = value.to_s
<ide> Array(keys).each do |key|
<del> unless self[key].to_s.empty?
<del> self[key] = value + separator + self[key]
<del> else
<add> old = self[key]
<add> if old.nil? || old.empty?
<ide> self[key] = value
<add> else
<add> self[key] = value + separator + old
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | use direct filter in winnow | 4765bb5c7840fc5f725f5bda38afcebc3730fbfc | <ide><path>src/traversing/findFilter.js
<ide> define( [
<ide>
<ide> "use strict";
<ide>
<del>var risSimple = /^.[^:#\[\.,]*$/;
<del>
<ide> // Implement the identical functionality for filter and not
<ide> function winnow( elements, qualifier, not ) {
<ide> if ( isFunction( qualifier ) ) {
<ide> function winnow( elements, qualifier, not ) {
<ide> } );
<ide> }
<ide>
<del> // Simple selector that can be filtered directly, removing non-Elements
<del> if ( risSimple.test( qualifier ) ) {
<del> return jQuery.filter( qualifier, elements, not );
<del> }
<del>
<del> // Complex selector, compare the two sets, removing non-Elements
<del> qualifier = jQuery.filter( qualifier, elements );
<del> return jQuery.grep( elements, function( elem ) {
<del> return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
<del> } );
<add> // Filtered directly for both simple and complex selectors
<add> return jQuery.filter( qualifier, elements, not );
<ide> }
<ide>
<ide> jQuery.filter = function( expr, elems, not ) { | 1 |
Javascript | Javascript | remove message from strictequal assertions | 2a88f02f2ff861b794ea9b83bbdfe71950d584ed | <ide><path>test/parallel/test-http2-cookies.js
<ide> server.on('listening', common.mustCall(() => {
<ide>
<ide> req.on('response', common.mustCall((headers) => {
<ide> assert(Array.isArray(headers['set-cookie']));
<del> assert.deepStrictEqual(headers['set-cookie'], setCookie,
<del> 'set-cookie header does not match');
<add> assert.deepStrictEqual(headers['set-cookie'], setCookie);
<ide> }));
<ide>
<ide> req.on('end', common.mustCall(() => { | 1 |
Go | Go | fix some minor linting issues | 968ff5ab44b1846964e832d4509e17f814d6116d | <ide><path>distribution/pull_v2_test.go
<ide> package distribution // import "github.com/docker/docker/distribution"
<ide> import (
<ide> "context"
<ide> "encoding/json"
<del> "fmt"
<ide> "net/http"
<ide> "net/http/httptest"
<ide> "net/url"
<ide> func TestFormatPlatform(t *testing.T) {
<ide> }
<ide> matches, _ := regexp.MatchString("windows.* [0-9]", result)
<ide> if !matches {
<del> t.Fatal(fmt.Sprintf("expected formatPlatform to show windows platform with a version, but got '%s'", result))
<add> t.Fatalf("expected formatPlatform to show windows platform with a version, but got '%s'", result)
<ide> }
<ide> }
<ide> }
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerCLIBuildSuite) TestBuildMultiStageResetScratch(c *testing.T) {
<ide> }
<ide>
<ide> func (s *DockerCLIBuildSuite) TestBuildIntermediateTarget(c *testing.T) {
<del> //todo: need to be removed after 18.06 release
<del> if strings.Contains(testEnv.DaemonInfo.ServerVersion, "18.05.0") {
<del> c.Skip(fmt.Sprintf("Bug fixed in 18.06 or higher.Skipping it for %s", testEnv.DaemonInfo.ServerVersion))
<del> }
<ide> dockerfile := `
<ide> FROM busybox AS build-env
<ide> CMD ["/dev"]
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *testing.T)
<ide> var newBasesizeBytes int64 = 53687091200 // 50GB in bytes
<ide>
<ide> if newBasesizeBytes < oldBasesizeBytes {
<del> c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes))))
<add> c.Skipf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes)))
<ide> }
<ide>
<ide> err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
<ide><path>libnetwork/firewall_linux.go
<ide> import (
<ide>
<ide> const userChain = "DOCKER-USER"
<ide>
<del>var (
<del> ctrl *controller = nil
<del>)
<add>var ctrl *controller
<ide>
<ide> func setupArrangeUserFilterRule(c *controller) {
<ide> ctrl = c | 4 |
PHP | PHP | remove unnessary extra loop | 34ca97417818d9fe6eb4e25774df307538df3aa3 | <ide><path>src/Mailer/Renderer.php
<ide> public function renderTemplates(Email $email, ?string $content = null): array
<ide> $view->setTemplatePath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type);
<ide> $view->setLayoutPath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type);
<ide>
<del> $render = $view->render();
<del> $render = str_replace(["\r\n", "\r"], "\n", $render);
<del> $rendered[$type] = $this->encodeString($render, $email->getCharset());
<del> }
<del>
<del> foreach ($rendered as $type => $content) {
<del> $rendered[$type] = $this->wrap($content);
<add> $content = $view->render();
<add> $content = str_replace(["\r\n", "\r"], "\n", $content);
<add> $rendered[$type] = $this->encodeString($content, $email->getCharset());
<add> $rendered[$type] = $this->wrap($rendered[$type]);
<ide> $rendered[$type] = implode("\n", $rendered[$type]);
<ide> $rendered[$type] = rtrim($rendered[$type], "\n");
<ide> } | 1 |
Python | Python | use textwrap.dedent for multiline strings | f89414564743495ca9104400e9ab1a6ba0963e2e | <ide><path>numpy/distutils/command/autodist.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<add>import textwrap
<ide>
<ide> # We put them here since they could be easily reused outside numpy.distutils
<ide>
<ide> def check_inline(cmd):
<ide> """Return the inline identifier (may be empty)."""
<ide> cmd._check_compiler()
<del> body = """
<del>#ifndef __cplusplus
<del>static %(inline)s int static_func (void)
<del>{
<del> return 0;
<del>}
<del>%(inline)s int nostatic_func (void)
<del>{
<del> return 0;
<del>}
<del>#endif"""
<add> body = textwrap.dedent("""
<add> #ifndef __cplusplus
<add> static %(inline)s int static_func (void)
<add> {
<add> return 0;
<add> }
<add> %(inline)s int nostatic_func (void)
<add> {
<add> return 0;
<add> }
<add> #endif""")
<ide>
<ide> for kw in ['inline', '__inline__', '__inline']:
<ide> st = cmd.try_compile(body % {'inline': kw}, None, None)
<ide> def check_inline(cmd):
<ide>
<ide> return ''
<ide>
<add>
<ide> def check_restrict(cmd):
<ide> """Return the restrict identifier (may be empty)."""
<ide> cmd._check_compiler()
<del> body = """
<del>static int static_func (char * %(restrict)s a)
<del>{
<del> return 0;
<del>}
<del>"""
<add> body = textwrap.dedent("""
<add> static int static_func (char * %(restrict)s a)
<add> {
<add> return 0;
<add> }
<add> """)
<ide>
<ide> for kw in ['restrict', '__restrict__', '__restrict']:
<ide> st = cmd.try_compile(body % {'restrict': kw}, None, None)
<ide> def check_restrict(cmd):
<ide>
<ide> return ''
<ide>
<add>
<ide> def check_compiler_gcc4(cmd):
<ide> """Return True if the C compiler is GCC 4.x."""
<ide> cmd._check_compiler()
<del> body = """
<del>int
<del>main()
<del>{
<del>#if (! defined __GNUC__) || (__GNUC__ < 4)
<del>#error gcc >= 4 required
<del>#endif
<del> return 0;
<del>}
<del>"""
<add> body = textwrap.dedent("""
<add> int
<add> main()
<add> {
<add> #if (! defined __GNUC__) || (__GNUC__ < 4)
<add> #error gcc >= 4 required
<add> #endif
<add> return 0;
<add> }
<add> """)
<ide> return cmd.try_compile(body, None, None)
<ide>
<ide>
<ide> def check_gcc_function_attribute(cmd, attribute, name):
<ide> """Return True if the given function attribute is supported."""
<ide> cmd._check_compiler()
<del> body = """
<del>#pragma GCC diagnostic error "-Wattributes"
<del>#pragma clang diagnostic error "-Wattributes"
<del>
<del>int %s %s(void*);
<del>
<del>int
<del>main()
<del>{
<del> return 0;
<del>}
<del>""" % (attribute, name)
<add> body = textwrap.dedent("""
<add> #pragma GCC diagnostic error "-Wattributes"
<add> #pragma clang diagnostic error "-Wattributes"
<add>
<add> int %s %s(void*);
<add>
<add> int
<add> main()
<add> {
<add> return 0;
<add> }
<add> """) % (attribute, name)
<ide> return cmd.try_compile(body, None, None) != 0
<ide>
<add>
<ide> def check_gcc_function_attribute_with_intrinsics(cmd, attribute, name, code,
<ide> include):
<ide> """Return True if the given function attribute is supported with
<ide> intrinsics."""
<ide> cmd._check_compiler()
<del> body = """
<del>#include<%s>
<del>int %s %s(void)
<del>{
<del> %s;
<del> return 0;
<del>}
<del>
<del>int
<del>main()
<del>{
<del> return 0;
<del>}
<del>""" % (include, attribute, name, code)
<add> body = textwrap.dedent("""
<add> #include<%s>
<add> int %s %s(void)
<add> {
<add> %s;
<add> return 0;
<add> }
<add>
<add> int
<add> main()
<add> {
<add> return 0;
<add> }
<add> """) % (include, attribute, name, code)
<ide> return cmd.try_compile(body, None, None) != 0
<add>
<add>
<ide> def check_gcc_variable_attribute(cmd, attribute):
<ide> """Return True if the given variable attribute is supported."""
<ide> cmd._check_compiler()
<del> body = """
<del>#pragma GCC diagnostic error "-Wattributes"
<del>#pragma clang diagnostic error "-Wattributes"
<del>
<del>int %s foo;
<del>
<del>int
<del>main()
<del>{
<del> return 0;
<del>}
<del>""" % (attribute, )
<add> body = textwrap.dedent("""
<add> #pragma GCC diagnostic error "-Wattributes"
<add> #pragma clang diagnostic error "-Wattributes"
<add>
<add> int %s foo;
<add>
<add> int
<add> main()
<add> {
<add> return 0;
<add> }
<add> """) % (attribute, )
<ide> return cmd.try_compile(body, None, None) != 0
<ide><path>numpy/distutils/command/config.py
<ide> import warnings
<ide> import sys
<ide> import subprocess
<add>import textwrap
<ide>
<ide> from distutils.command.config import config as old_config
<ide> from distutils.command.config import LANG_EXT
<ide> def _check_compiler (self):
<ide> self.compiler.initialize()
<ide> except IOError:
<ide> e = get_exception()
<del> msg = """\
<del>Could not initialize compiler instance: do you have Visual Studio
<del>installed? If you are trying to build with MinGW, please use "python setup.py
<del>build -c mingw32" instead. If you have Visual Studio installed, check it is
<del>correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2,
<del>VS 2010 for >= 3.3).
<del>
<del>Original exception was: %s, and the Compiler class was %s
<del>============================================================================""" \
<add> msg = textwrap.dedent("""\
<add> Could not initialize compiler instance: do you have Visual Studio
<add> installed? If you are trying to build with MinGW, please use "python setup.py
<add> build -c mingw32" instead. If you have Visual Studio installed, check it is
<add> correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2,
<add> VS 2010 for >= 3.3).
<add>
<add> Original exception was: %s, and the Compiler class was %s
<add> ============================================================================""") \
<ide> % (e, self.compiler.__class__.__name__)
<del> print ("""\
<del>============================================================================""")
<add> print(textwrap.dedent("""\
<add> ============================================================================"""))
<ide> raise distutils.errors.DistutilsPlatformError(msg)
<ide>
<ide> # After MSVC is initialized, add an explicit /MANIFEST to linker
<ide> def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'):
<ide> def check_decl(self, symbol,
<ide> headers=None, include_dirs=None):
<ide> self._check_compiler()
<del> body = """
<del>int main(void)
<del>{
<del>#ifndef %s
<del> (void) %s;
<del>#endif
<del> ;
<del> return 0;
<del>}""" % (symbol, symbol)
<add> body = textwrap.dedent("""
<add> int main(void)
<add> {
<add> #ifndef %s
<add> (void) %s;
<add> #endif
<add> ;
<add> return 0;
<add> }""") % (symbol, symbol)
<ide>
<ide> return self.try_compile(body, headers, include_dirs)
<ide>
<ide> def check_macro_true(self, symbol,
<ide> headers=None, include_dirs=None):
<ide> self._check_compiler()
<del> body = """
<del>int main(void)
<del>{
<del>#if %s
<del>#else
<del>#error false or undefined macro
<del>#endif
<del> ;
<del> return 0;
<del>}""" % (symbol,)
<add> body = textwrap.dedent("""
<add> int main(void)
<add> {
<add> #if %s
<add> #else
<add> #error false or undefined macro
<add> #endif
<add> ;
<add> return 0;
<add> }""") % (symbol,)
<ide>
<ide> return self.try_compile(body, headers, include_dirs)
<ide>
<ide> def check_type(self, type_name, headers=None, include_dirs=None,
<ide> self._check_compiler()
<ide>
<ide> # First check the type can be compiled
<del> body = r"""
<del>int main(void) {
<del> if ((%(name)s *) 0)
<del> return 0;
<del> if (sizeof (%(name)s))
<del> return 0;
<del>}
<del>""" % {'name': type_name}
<add> body = textwrap.dedent(r"""
<add> int main(void) {
<add> if ((%(name)s *) 0)
<add> return 0;
<add> if (sizeof (%(name)s))
<add> return 0;
<add> }
<add> """) % {'name': type_name}
<ide>
<ide> st = False
<ide> try:
<ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_di
<ide> self._check_compiler()
<ide>
<ide> # First check the type can be compiled
<del> body = r"""
<del>typedef %(type)s npy_check_sizeof_type;
<del>int main (void)
<del>{
<del> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
<del> test_array [0] = 0
<del>
<del> ;
<del> return 0;
<del>}
<del>"""
<add> body = textwrap.dedent(r"""
<add> typedef %(type)s npy_check_sizeof_type;
<add> int main (void)
<add> {
<add> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
<add> test_array [0] = 0
<add>
<add> ;
<add> return 0;
<add> }
<add> """)
<ide> self._compile(body % {'type': type_name},
<ide> headers, include_dirs, 'c')
<ide> self._clean()
<ide>
<ide> if expected:
<del> body = r"""
<del>typedef %(type)s npy_check_sizeof_type;
<del>int main (void)
<del>{
<del> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
<del> test_array [0] = 0
<del>
<del> ;
<del> return 0;
<del>}
<del>"""
<add> body = textwrap.dedent(r"""
<add> typedef %(type)s npy_check_sizeof_type;
<add> int main (void)
<add> {
<add> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
<add> test_array [0] = 0
<add>
<add> ;
<add> return 0;
<add> }
<add> """)
<ide> for size in expected:
<ide> try:
<ide> self._compile(body % {'type': type_name, 'size': size},
<ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_di
<ide> pass
<ide>
<ide> # this fails to *compile* if size > sizeof(type)
<del> body = r"""
<del>typedef %(type)s npy_check_sizeof_type;
<del>int main (void)
<del>{
<del> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
<del> test_array [0] = 0
<del>
<del> ;
<del> return 0;
<del>}
<del>"""
<add> body = textwrap.dedent(r"""
<add> typedef %(type)s npy_check_sizeof_type;
<add> int main (void)
<add> {
<add> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
<add> test_array [0] = 0
<add>
<add> ;
<add> return 0;
<add> }
<add> """)
<ide>
<ide> # The principle is simple: we first find low and high bounds of size
<ide> # for the type, where low/high are looked up on a log scale. Then, we
<ide><path>numpy/distutils/mingw32ccompiler.py
<ide> import sys
<ide> import subprocess
<ide> import re
<add>import textwrap
<ide>
<ide> # Overwrite certain distutils.ccompiler functions:
<ide> import numpy.distutils.ccompiler
<ide> def msvc_manifest_xml(maj, min):
<ide> # embedded in the binary...
<ide> # This template was copied directly from the python 2.6 binary (using
<ide> # strings.exe from mingw on python.exe).
<del> template = """\
<del><assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<del> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<del> <security>
<del> <requestedPrivileges>
<del> <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
<del> </requestedPrivileges>
<del> </security>
<del> </trustInfo>
<del> <dependency>
<del> <dependentAssembly>
<del> <assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
<del> </dependentAssembly>
<del> </dependency>
<del></assembly>"""
<add> template = textwrap.dedent("""\
<add> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<add> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<add> <security>
<add> <requestedPrivileges>
<add> <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
<add> </requestedPrivileges>
<add> </security>
<add> </trustInfo>
<add> <dependency>
<add> <dependentAssembly>
<add> <assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
<add> </dependentAssembly>
<add> </dependency>
<add> </assembly>""")
<ide>
<ide> return template % {'fullver': fullver, 'maj': maj, 'min': min}
<ide>
<ide><path>numpy/distutils/misc_util.py
<ide> import subprocess
<ide> import shutil
<ide> import multiprocessing
<add>import textwrap
<ide>
<ide> import distutils
<ide> from distutils.errors import DistutilsError
<ide> def generate_config_py(target):
<ide> f.write('__all__ = ["get_info","show"]\n\n')
<ide>
<ide> # For gfortran+msvc combination, extra shared libraries may exist
<del> f.write("""
<add> f.write(textwrap.dedent("""
<add> import os
<add> import sys
<ide>
<del>import os
<del>import sys
<del>
<del>extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
<add> extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
<ide>
<del>if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
<del> os.environ.setdefault('PATH', '')
<del> os.environ['PATH'] += os.pathsep + extra_dll_dir
<add> if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
<add> os.environ.setdefault('PATH', '')
<add> os.environ['PATH'] += os.pathsep + extra_dll_dir
<ide>
<del>""")
<add> """))
<ide>
<ide> for k, i in system_info.saved_results.items():
<ide> f.write('%s=%r\n' % (k, i))
<del> f.write(r'''
<del>def get_info(name):
<del> g = globals()
<del> return g.get(name, g.get(name + "_info", {}))
<del>
<del>def show():
<del> for name,info_dict in globals().items():
<del> if name[0] == "_" or type(info_dict) is not type({}): continue
<del> print(name + ":")
<del> if not info_dict:
<del> print(" NOT AVAILABLE")
<del> for k,v in info_dict.items():
<del> v = str(v)
<del> if k == "sources" and len(v) > 200:
<del> v = v[:60] + " ...\n... " + v[-60:]
<del> print(" %s = %s" % (k,v))
<del> ''')
<add> f.write(textwrap.dedent(r'''
<add> def get_info(name):
<add> g = globals()
<add> return g.get(name, g.get(name + "_info", {}))
<add>
<add> def show():
<add> for name,info_dict in globals().items():
<add> if name[0] == "_" or type(info_dict) is not type({}): continue
<add> print(name + ":")
<add> if not info_dict:
<add> print(" NOT AVAILABLE")
<add> for k,v in info_dict.items():
<add> v = str(v)
<add> if k == "sources" and len(v) > 200:
<add> v = v[:60] + " ...\n... " + v[-60:]
<add> print(" %s = %s" % (k,v))
<add> '''))
<ide>
<ide> return target
<ide>
<ide><path>numpy/distutils/system_info.py
<ide> import copy
<ide> import warnings
<ide> import subprocess
<add>import textwrap
<ide>
<ide> from glob import glob
<ide> from functools import reduce
<ide> def calc_info(self):
<ide> else:
<ide> dict_append(info, **atlas)
<ide> dict_append(info, define_macros=[('ATLAS_WITHOUT_LAPACK', None)])
<del> message = """
<del>*********************************************************************
<del> Could not find lapack library within the ATLAS installation.
<del>*********************************************************************
<del>"""
<add> message = textwrap.dedent("""
<add> *********************************************************************
<add> Could not find lapack library within the ATLAS installation.
<add> *********************************************************************
<add> """)
<ide> warnings.warn(message, stacklevel=2)
<ide> self.set_info(**info)
<ide> return
<ide> def calc_info(self):
<ide> if lapack_lib is not None:
<ide> sz = os.stat(lapack_lib)[6]
<ide> if sz <= 4000 * 1024:
<del> message = """
<del>*********************************************************************
<del> Lapack library (from ATLAS) is probably incomplete:
<del> size of %s is %sk (expected >4000k)
<del>
<del> Follow the instructions in the KNOWN PROBLEMS section of the file
<del> numpy/INSTALL.txt.
<del>*********************************************************************
<del>""" % (lapack_lib, sz / 1024)
<add> message = textwrap.dedent("""
<add> *********************************************************************
<add> Lapack library (from ATLAS) is probably incomplete:
<add> size of %s is %sk (expected >4000k)
<add>
<add> Follow the instructions in the KNOWN PROBLEMS section of the file
<add> numpy/INSTALL.txt.
<add> *********************************************************************
<add> """) % (lapack_lib, sz / 1024)
<ide> warnings.warn(message, stacklevel=2)
<ide> else:
<ide> info['language'] = 'f77'
<ide> def get_atlas_version(**config):
<ide> library_dirs=library_dirs,
<ide> use_tee=(system_info.verbosity > 0))
<ide> if not s:
<del> warnings.warn("""
<del>*****************************************************
<del>Linkage with ATLAS requires gfortran. Use
<add> warnings.warn(textwrap.dedent("""
<add> *****************************************************
<add> Linkage with ATLAS requires gfortran. Use
<ide>
<del> python setup.py config_fc --fcompiler=gnu95 ...
<add> python setup.py config_fc --fcompiler=gnu95 ...
<ide>
<del>when building extension libraries that use ATLAS.
<del>Make sure that -lgfortran is used for C++ extensions.
<del>*****************************************************
<del>""", stacklevel=2)
<add> when building extension libraries that use ATLAS.
<add> Make sure that -lgfortran is used for C++ extensions.
<add> *****************************************************
<add> """), stacklevel=2)
<ide> dict_append(info, language='f90',
<ide> define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)])
<ide> except Exception: # failed to get version from file -- maybe on Windows
<ide> def get_cblas_libs(self, info):
<ide> # cblas or blas
<ide> c = customized_ccompiler()
<ide> tmpdir = tempfile.mkdtemp()
<del> s = """#include <cblas.h>
<del> int main(int argc, const char *argv[])
<del> {
<del> double a[4] = {1,2,3,4};
<del> double b[4] = {5,6,7,8};
<del> return cblas_ddot(4, a, 1, b, 1) > 10;
<del> }"""
<add> s = textwrap.dedent("""\
<add> #include <cblas.h>
<add> int main(int argc, const char *argv[])
<add> {
<add> double a[4] = {1,2,3,4};
<add> double b[4] = {5,6,7,8};
<add> return cblas_ddot(4, a, 1, b, 1) > 10;
<add> }""")
<ide> src = os.path.join(tmpdir, 'source.c')
<ide> try:
<ide> with open(src, 'wt') as f:
<ide> def check_embedded_lapack(self, info):
<ide> c = customized_ccompiler()
<ide>
<ide> tmpdir = tempfile.mkdtemp()
<del> s = """void zungqr_();
<del> int main(int argc, const char *argv[])
<del> {
<del> zungqr_();
<del> return 0;
<del> }"""
<add> s = textwrap.dedent("""\
<add> void zungqr_();
<add> int main(int argc, const char *argv[])
<add> {
<add> zungqr_();
<add> return 0;
<add> }""")
<ide> src = os.path.join(tmpdir, 'source.c')
<ide> out = os.path.join(tmpdir, 'a.out')
<ide> # Add the additional "extra" arguments
<ide> def check_embedded_lapack(self, info):
<ide> c = customized_ccompiler()
<ide>
<ide> tmpdir = tempfile.mkdtemp()
<del> s = """void zungqr_();
<del> int main(int argc, const char *argv[])
<del> {
<del> zungqr_();
<del> return 0;
<del> }"""
<add> s = textwrap.dedent("""\
<add> void zungqr_();
<add> int main(int argc, const char *argv[])
<add> {
<add> zungqr_();
<add> return 0;
<add> }""")
<ide> src = os.path.join(tmpdir, 'source.c')
<ide> out = os.path.join(tmpdir, 'a.out')
<ide> # Add the additional "extra" arguments | 5 |
Ruby | Ruby | remove warning from postgresql geometric test | 4ab20ed563e832a09b22a4c6e87da2e6a3227263 | <ide><path>activerecord/test/cases/adapters/postgresql/geometric_test.rb
<ide> class PostgresqlLine < ActiveRecord::Base; end
<ide> end
<ide>
<ide> teardown do
<del> @connection.drop_table 'postgresql_lines', if_exists: true
<add> if defined?(@connection)
<add> @connection.drop_table 'postgresql_lines', if_exists: true
<add> end
<ide> end
<ide>
<ide> def test_geometric_line_type | 1 |
PHP | PHP | fix various things | 057492d31c569e96a3ba2f99722112a9762c6071 | <ide><path>src/Illuminate/Cache/ArrayStore.php
<ide> public function forget($key)
<ide> public function flush()
<ide> {
<ide> $this->storage = [];
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>src/Illuminate/Cache/FileStore.php
<ide> public function flush()
<ide> {
<ide> if ($this->files->isDirectory($this->directory)) {
<ide> foreach ($this->files->directories($this->directory) as $directory) {
<del> if(!$this->files->deleteDirectory($directory)){
<add> if (! $this->files->deleteDirectory($directory)) {
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Illuminate/Cache/NullStore.php
<ide> public function forget($key)
<ide> */
<ide> public function flush()
<ide> {
<del> //
<add> return true;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/RedisStore.php
<ide> public function forget($key)
<ide> */
<ide> public function flush()
<ide> {
<del> return (bool) $this->connection()->flushdb();
<add> $this->connection()->flushdb();
<add>
<add> return true;
<ide> }
<ide>
<ide> /** | 4 |
Text | Text | limit lines to 80 cols in internal readme | 40b6cf241e1b383abe7a0476a604979a123d17d4 | <ide><path>lib/internal/readme.md
<ide> # Internal Modules
<ide>
<del>The modules in `lib/internal` are intended for internal use in Node.js core only, and are not accessible with `require()` from user modules.
<del>These are subject to change at **any** time. Reliance on these modules outside of core is **not supported** in any way.
<add>The modules in `lib/internal` are intended for internal use in Node.js core
<add>only, and are not accessible with `require()` from user modules. These are
<add>subject to change at **any** time. Reliance on these modules outside of core
<add>is **not supported** in any way. | 1 |
Go | Go | emit a buildresult after squashing | 9777ec3be0e3056d0bedcf36052704f832e45759 | <ide><path>api/server/backend/build/backend.go
<ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string
<ide> if imageID, err = squashBuild(build, b.imageComponent); err != nil {
<ide> return "", err
<ide> }
<add> if config.ProgressWriter.AuxFormatter != nil {
<add> if err = config.ProgressWriter.AuxFormatter.Emit(types.BuildResult{ID: imageID}); err != nil {
<add> return "", err
<add> }
<add> }
<ide> }
<ide>
<ide> stdout := config.ProgressWriter.StdoutFormatter
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *check.C) {
<ide> c.Assert(err, check.NotNil)
<ide> c.Assert(os.IsNotExist(err), check.Equals, true)
<ide> }
<add>
<add>func (s *DockerSuite) TestBuildIidFileSquash(c *check.C) {
<add> testRequires(c, ExperimentalDaemon)
<add> tmpDir, err := ioutil.TempDir("", "TestBuildIidFileSquash")
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add> defer os.RemoveAll(tmpDir)
<add> tmpIidFile := filepath.Join(tmpDir, "iidsquash")
<add>
<add> name := "testbuildiidfilesquash"
<add> // Use a Dockerfile with multiple stages to ensure we get the last one
<add> cli.BuildCmd(c, name,
<add> // This could be minimalBaseImage except
<add> // https://github.com/moby/moby/issues/33823 requires
<add> // `touch` to workaround.
<add> build.WithDockerfile(`FROM busybox
<add>ENV FOO FOO
<add>ENV BAR BAR
<add>RUN touch /foop
<add>`),
<add> cli.WithFlags("--iidfile", tmpIidFile, "--squash"))
<add>
<add> id, err := ioutil.ReadFile(tmpIidFile)
<add> c.Assert(err, check.IsNil)
<add> d, err := digest.Parse(string(id))
<add> c.Assert(err, check.IsNil)
<add> c.Assert(d.String(), checker.Equals, getIDByName(c, name))
<add>} | 2 |
Javascript | Javascript | simplify jquery.removeattr and return this | b85d2cd8a5c49487dc3ea7f6fad963efd9fd0f55 | <ide><path>src/attributes.js
<ide> jQuery.extend({
<ide> }
<ide> },
<ide>
<del> // removeAttribute returns boolean in IE
<del> // set property to null if getSetAttribute not supported (IE6-7)
<ide> removeAttr: function( elem, name ) {
<ide> name = jQuery.attrFix[ name ] || name;
<del> if ( typeof elem.removeAttribute( name ) === "boolean" && !jQuery.support.getSetAttribute ) {
<del> // Setting className to null sets a class of "null"
<add>
<add> jQuery.support.getSetAttribute ? elem.removeAttribute( name ) :
<add> // set property to null if getSetAttribute not supported (IE6-7)
<add> // setting className to null makes the class "null"
<ide> name === "className" ? elem.className = "" : elem.setAttribute( name, null );
<del> }
<add>
<add> return this;
<ide> },
<ide>
<ide> attrHooks: { | 1 |
Text | Text | add v2.11.0-beta.2 to the changelog | be54b40bf0b1fc5b21aca44ce96cf12db9848294 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.11.0-beta.2 (November 29, 2016)
<add>
<add>- [#14658](https://github.com/emberjs/ember.js/pull/14658) [BUGFIX] Make the ember-source build work.
<add>
<ide> ### 2.11.0-beta.1 (November 28, 2016)
<ide>
<ide> - [#14389](https://github.com/emberjs/ember.js/pull/14389) [BUGFIX] Move `classNames` and `classNameBindings` properties into the component's prototype. | 1 |
Text | Text | add squash guideline to pull-requests doc | 24a5ac797d6eb2431d532ddb3a9e2062490a7737 | <ide><path>doc/guides/contributing/pull-requests.md
<ide> whether the failure was caused by the changes in the Pull Request.
<ide>
<ide> ### Commit Squashing
<ide>
<del>When the commits in your Pull Request land, they may be squashed
<del>into one commit per logical change. Metadata will be added to the commit
<del>message (including links to the Pull Request, links to relevant issues,
<add>In most cases, do not squash commits that you add to your Pull Request during
<add>the review process. When the commits in your Pull Request land, they may be
<add>squashed into one commit per logical change. Metadata will be added to the
<add>commit message (including links to the Pull Request, links to relevant issues,
<ide> and the names of the reviewers). The commit history of your Pull Request,
<ide> however, will stay intact on the Pull Request page.
<ide> | 1 |
Python | Python | fix flake8 errors | b2355463366cc30ba5af518e1587fefb87f30c28 | <ide><path>celery/schedules.py
<ide> def day_out_of_range(year, month, day):
<ide> return True
<ide> return False
<ide>
<add> def is_before_last_run(year, month, day):
<add> return self.maybe_make_aware(datetime(year,
<add> month,
<add> day)) < last_run_at
<add>
<ide> def roll_over():
<ide> for _ in range(2000):
<ide> flag = (datedata.dom == len(days_of_month) or
<ide> day_out_of_range(datedata.year,
<ide> months_of_year[datedata.moy],
<ide> days_of_month[datedata.dom]) or
<del> (self.maybe_make_aware(datetime(datedata.year,
<del> months_of_year[datedata.moy],
<del> days_of_month[datedata.dom])) < last_run_at))
<add> (is_before_last_run(datedata.year,
<add> months_of_year[datedata.moy],
<add> days_of_month[datedata.dom])))
<ide>
<ide> if flag:
<ide> datedata.dom = 0 | 1 |
Javascript | Javascript | remove picker from scrollview examples | f12f0e679dd6f1cdbd3c993d940a736ea1e952a3 | <ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js
<ide> const React = require('react');
<ide> const {
<ide> Platform,
<ide> ScrollView,
<del> Picker,
<ide> StyleSheet,
<ide> Text,
<ide> TouchableOpacity,
<ide> const SnapToOptions = () => {
<ide> const [snapToInterval, setSnapToInterval] = useState(0);
<ide> const [snapToOffsets, setSnapToOffsets] = useState([]);
<ide> const [snapToStart, setSnapToStart] = useState(true);
<add>
<ide> return (
<ide> <View>
<ide> <ScrollView
<ide> const SnapToOptions = () => {
<ide> </ScrollView>
<ide> {Platform.OS === 'ios' ? (
<ide> <>
<del> <Text style={styles.rowTitle}>Snap to Alignment Mode</Text>
<del> <Picker
<del> selectedValue={snapToAlignment}
<del> onValueChange={value => {
<del> if (value === 'start' || value === 'center' || value === 'end') {
<del> setSnapToAlignment(value);
<del> }
<del> }}
<del> itemStyle={styles.pickerItem}>
<del> {snapToAlignmentModes.map(label => {
<del> return <Picker.Item label={label} value={label} key={label} />;
<del> })}
<del> </Picker>
<add> <Text style={styles.rowTitle}>Select Snap to Alignment Mode</Text>
<add> <View style={styles.row}>
<add> {snapToAlignmentModes.map(label => (
<add> <Button
<add> active={snapToAlignment === label}
<add> key={label}
<add> label={label}
<add> onPress={() => setSnapToAlignment(label)}
<add> />
<add> ))}
<add> </View>
<ide> </>
<ide> ) : null}
<ide> <Button
<ide> const OnScrollOptions = () => {
<ide> {Platform.OS === 'android' ? (
<ide> <>
<ide> <Text style={styles.rowTitle}>Over Scroll Mode</Text>
<del> <Picker
<del> selectedValue={overScrollMode}
<del> onValueChange={value => {
<del> if (value === 'always' || value === 'auto' || value === 'never') {
<del> setOverScrollMode(value);
<del> }
<del> }}
<del> itemStyle={styles.pickerItem}>
<del> {overScrollModeOptions.map(label => {
<del> return <Picker.Item label={label} value={label} key={label} />;
<del> })}
<del> </Picker>
<add> <View style={styles.row}>
<add> {overScrollModeOptions.map(value => (
<add> <Button
<add> active={value === overScrollMode}
<add> label={value}
<add> key={value}
<add> onPress={() => setOverScrollMode(value)}
<add> />
<add> ))}
<add> </View>
<ide> </>
<ide> ) : null}
<ide> </View>
<ide> const KeyboardExample = () => {
<ide> {ITEMS.map(createItemRow)}
<ide> </ScrollView>
<ide> <Text style={styles.rowTitle}>Keyboard Dismiss Mode</Text>
<del> <Picker
<del> selectedValue={keyboardDismissMode}
<del> onValueChange={value => {
<del> if (
<del> value === 'none' ||
<del> value === 'on-drag' ||
<del> value === 'interactive'
<del> ) {
<del> setKeyboardDismissMode(value);
<del> }
<del> }}
<del> itemStyle={styles.pickerItem}>
<del> {dismissOptions.map(label => {
<del> return <Picker.Item label={label} value={label} key={label} />;
<del> })}
<del> </Picker>
<add> <View style={styles.row}>
<add> {dismissOptions.map(value => (
<add> <Button
<add> active={value === keyboardDismissMode}
<add> label={value}
<add> key={value}
<add> onPress={() => setKeyboardDismissMode(value)}
<add> />
<add> ))}
<add> </View>
<ide> <Text style={styles.rowTitle}>Keyboard Should Persist taps</Text>
<del> <Picker
<del> selectedValue={keyboardShouldPersistTaps}
<del> onValueChange={value => {
<del> if (value === 'never' || value === 'always' || value === 'handled') {
<del> setKeyboardShouldPersistTaps(value);
<del> }
<del> }}
<del> itemStyle={styles.pickerItem}>
<del> {persistOptions.map(label => {
<del> return <Picker.Item label={label} value={label} key={label} />;
<del> })}
<del> </Picker>
<add> <View style={styles.row}>
<add> {persistOptions.map(value => (
<add> <Button
<add> active={value === keyboardShouldPersistTaps}
<add> label={value}
<add> key={value}
<add> onPress={() => setKeyboardShouldPersistTaps(value)}
<add> />
<add> ))}
<add> </View>
<ide> </View>
<ide> );
<ide> };
<ide> let ITEMS = [...Array(12)].map((_, i) => `Item ${i}`);
<ide> const createItemRow = (msg, index) => <Item key={index} msg={msg} />;
<ide>
<ide> const Button = (props: {
<add> active?: boolean,
<ide> label: string,
<ide> onPress: () => void,
<ide> testID?: string,
<ide> }) => (
<ide> <TouchableOpacity
<del> style={styles.button}
<add> style={StyleSheet.compose(
<add> styles.button,
<add> props.active === true ? styles.activeButton : null,
<add> )}
<ide> onPress={props.onPress}
<ide> testID={props.testID}>
<ide> <Text>{props.label}</Text>
<ide> const styles = StyleSheet.create({
<ide> fontWeight: 'bold',
<ide> margin: 5,
<ide> },
<add> activeButton: {
<add> backgroundColor: 'rgba(100,215,255,.3)',
<add> },
<ide> button: {
<add> flex: 1,
<ide> margin: 5,
<ide> padding: 5,
<ide> alignItems: 'center',
<ide> const styles = StyleSheet.create({
<ide> containerStyle: {
<ide> backgroundColor: '#aae3b6',
<ide> },
<del> pickerItem: {
<del> fontSize: 16,
<del> },
<ide> rowTitle: {
<ide> flex: 1,
<ide> fontWeight: 'bold',
<add> alignSelf: 'center',
<ide> },
<ide> textInput: {
<ide> height: 40, | 1 |
Mixed | Python | delete all mentions of model2model | 9df74b8bc42eedc496f7148b9370728054ca3b6a | <ide><path>docs/source/quickstart.md
<ide> print(sequence)
<ide> ```
<ide>
<ide> The model only requires a single token as input as all the previous tokens' key/value pairs are contained in the `past`.
<del>
<del>### Model2Model example
<del>
<del>Encoder-decoder architectures require two tokenized inputs: one for the encoder and the other one for the decoder. Let's assume that we want to use `Model2Model` for generative question answering, and start by tokenizing the question and answer that will be fed to the model.
<del>
<del>```python
<del>import torch
<del>from transformers import BertTokenizer, Model2Model
<del>
<del># OPTIONAL: if you want to have more information on what's happening under the hood, activate the logger as follows
<del>import logging
<del>logging.basicConfig(level=logging.INFO)
<del>
<del># Load pre-trained model tokenizer (vocabulary)
<del>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<del>
<del># Encode the input to the encoder (the question)
<del>question = "Who was Jim Henson?"
<del>encoded_question = tokenizer.encode(question)
<del>
<del># Encode the input to the decoder (the answer)
<del>answer = "Jim Henson was a puppeteer"
<del>encoded_answer = tokenizer.encode(answer)
<del>
<del># Convert inputs to PyTorch tensors
<del>question_tensor = torch.tensor([encoded_question])
<del>answer_tensor = torch.tensor([encoded_answer])
<del>```
<del>
<del>Let's see how we can use `Model2Model` to get the value of the loss associated with this (question, answer) pair:
<del>
<del>```python
<del># In order to compute the loss we need to provide language model
<del># labels (the token ids that the model should have produced) to
<del># the decoder.
<del>lm_labels = encoded_answer
<del>labels_tensor = torch.tensor([lm_labels])
<del>
<del># Load pre-trained model (weights)
<del>model = Model2Model.from_pretrained('bert-base-uncased')
<del>
<del># Set the model in evaluation mode to deactivate the DropOut modules
<del># This is IMPORTANT to have reproducible results during evaluation!
<del>model.eval()
<del>
<del># If you have a GPU, put everything on cuda
<del>question_tensor = question_tensor.to('cuda')
<del>answer_tensor = answer_tensor.to('cuda')
<del>labels_tensor = labels_tensor.to('cuda')
<del>model.to('cuda')
<del>
<del># Predict hidden states features for each layer
<del>with torch.no_grad():
<del> # See the models docstrings for the detail of the inputs
<del> outputs = model(question_tensor, answer_tensor, decoder_lm_labels=labels_tensor)
<del> # Transformers models always output tuples.
<del> # See the models docstrings for the detail of all the outputs
<del> # In our case, the first element is the value of the LM loss
<del> lm_loss = outputs[0]
<del>```
<del>
<del>This loss can be used to fine-tune `Model2Model` on the question answering task. Assuming that we fine-tuned the model, let us now see how to generate an answer:
<del>
<del>```python
<del># Let's re-use the previous question
<del>question = "Who was Jim Henson?"
<del>encoded_question = tokenizer.encode(question)
<del>question_tensor = torch.tensor([encoded_question])
<del>
<del># This time we try to generate the answer, so we start with an empty sequence
<del>answer = "[CLS]"
<del>encoded_answer = tokenizer.encode(answer, add_special_tokens=False)
<del>answer_tensor = torch.tensor([encoded_answer])
<del>
<del># Load pre-trained model (weights)
<del>model = Model2Model.from_pretrained('fine-tuned-weights')
<del>model.eval()
<del>
<del># If you have a GPU, put everything on cuda
<del>question_tensor = question_tensor.to('cuda')
<del>answer_tensor = answer_tensor.to('cuda')
<del>model.to('cuda')
<del>
<del># Predict all tokens
<del>with torch.no_grad():
<del> outputs = model(question_tensor, answer_tensor)
<del> predictions = outputs[0]
<del>
<del># confirm we were able to predict 'jim'
<del>predicted_index = torch.argmax(predictions[0, -1]).item()
<del>predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]
<del>assert predicted_token == 'jim'
<del>```
<ide><path>src/transformers/__init__.py
<ide> CamembertForTokenClassification,
<ide> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP,
<ide> )
<del> from .modeling_encoder_decoder import PreTrainedEncoderDecoder, Model2Model
<add> from .modeling_encoder_decoder import PreTrainedEncoderDecoder
<ide> from .modeling_t5 import (
<ide> T5PreTrainedModel,
<ide> T5Model,
<ide><path>src/transformers/modeling_encoder_decoder.py
<ide> def forward(self, encoder_input_ids, decoder_input_ids, **kwargs):
<ide> decoder_outputs = self.decoder(decoder_input_ids, **kwargs_decoder)
<ide>
<ide> return decoder_outputs + encoder_outputs
<del>
<del>
<del>class Model2Model(PreTrainedEncoderDecoder):
<del> r"""
<del> :class:`~transformers.Model2Model` instantiates a Seq2Seq2 model
<del> where both of the encoder and decoder are of the same family. If the
<del> name of or that path to a pretrained model is specified the encoder and
<del> the decoder will be initialized with the pretrained weight (the
<del> cross-attention will be intialized randomly if its weights are not
<del> present).
<del>
<del> It is possible to override this behavior and initialize, say, the decoder randomly
<del> by creating it beforehand as follows
<del>
<del> config = BertConfig.from_pretrained()
<del> decoder = BertForMaskedLM(config)
<del> model = Model2Model.from_pretrained('bert-base-uncased', decoder_model=decoder)
<del> """
<del>
<del> def __init__(self, *args, **kwargs):
<del> super().__init__(*args, **kwargs)
<del> self.tie_weights()
<del>
<del> def tie_weights(self):
<del> """ Tying the encoder and decoders' embeddings together.
<del>
<del> We need for each to get down to the embedding weights. However the
<del> different model classes are inconsistent to that respect:
<del> - BertModel: embeddings.word_embeddings
<del> - RoBERTa: embeddings.word_embeddings
<del> - XLMModel: embeddings
<del> - GPT2: wte
<del> - BertForMaskedLM: bert.embeddings.word_embeddings
<del> - RobertaForMaskedLM: roberta.embeddings.word_embeddings
<del>
<del> argument of the XEmbedding layer for each model, but it is "blocked"
<del> by a model-specific keyword (bert, )...
<del> """
<del> # self._tie_or_clone_weights(self.encoder, self.decoder)
<del> pass
<del>
<del> @classmethod
<del> def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
<del>
<del> if (
<del> "bert" not in pretrained_model_name_or_path
<del> or "roberta" in pretrained_model_name_or_path
<del> or "distilbert" in pretrained_model_name_or_path
<del> ):
<del> raise ValueError("Only the Bert model is currently supported.")
<del>
<del> model = super().from_pretrained(
<del> encoder_pretrained_model_name_or_path=pretrained_model_name_or_path,
<del> decoder_pretrained_model_name_or_path=pretrained_model_name_or_path,
<del> *args,
<del> **kwargs,
<del> )
<del>
<del> return model
<ide><path>tests/test_modeling_encoder_decoder.py
<del># coding=utf-8
<del># Copyright 2018 The Hugging Face Inc. Team
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del>
<del>import logging
<del>import unittest
<del>
<del>from transformers import is_torch_available
<del>
<del>from .utils import require_torch, slow
<del>
<del>
<del>if is_torch_available():
<del> from transformers import BertModel, BertForMaskedLM, Model2Model
<del> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP
<del>
<del>
<del>@require_torch
<del>class EncoderDecoderModelTest(unittest.TestCase):
<del> @slow
<del> def test_model2model_from_pretrained(self):
<del> logging.basicConfig(level=logging.INFO)
<del> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:
<del> model = Model2Model.from_pretrained(model_name)
<del> self.assertIsInstance(model.encoder, BertModel)
<del> self.assertIsInstance(model.decoder, BertForMaskedLM)
<del> self.assertEqual(model.decoder.config.is_decoder, True)
<del> self.assertEqual(model.encoder.config.is_decoder, False)
<del>
<del> def test_model2model_from_pretrained_not_bert(self):
<del> logging.basicConfig(level=logging.INFO)
<del> with self.assertRaises(ValueError):
<del> _ = Model2Model.from_pretrained("roberta")
<del>
<del> with self.assertRaises(ValueError):
<del> _ = Model2Model.from_pretrained("distilbert")
<del>
<del> with self.assertRaises(ValueError):
<del> _ = Model2Model.from_pretrained("does-not-exist") | 4 |
Java | Java | add onrawstatus to webclient | 6cb4b8bd43be9c741377f52cc98b43abde27dbc8 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java
<ide> import java.util.function.BiFunction;
<ide> import java.util.function.Consumer;
<ide> import java.util.function.Function;
<add>import java.util.function.IntPredicate;
<ide> import java.util.function.Predicate;
<ide> import java.util.function.Supplier;
<ide>
<ide> public HttpHeaders getHeaders() {
<ide>
<ide> private static class DefaultResponseSpec implements ResponseSpec {
<ide>
<add> private static final IntPredicate STATUS_CODE_ERROR = value -> value >= 400;
<add>
<ide> private static final StatusHandler DEFAULT_STATUS_HANDLER =
<del> new StatusHandler(HttpStatus::isError, DefaultResponseSpec::createResponseException);
<add> new StatusHandler(STATUS_CODE_ERROR, DefaultResponseSpec::createResponseException);
<ide>
<ide> private final Mono<ClientResponse> responseMono;
<ide>
<ide> private static class DefaultResponseSpec implements ResponseSpec {
<ide> @Override
<ide> public ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate,
<ide> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
<add> return onRawStatus(toIntPredicate(statusPredicate), exceptionFunction);
<add> }
<add>
<add> private static IntPredicate toIntPredicate(Predicate<HttpStatus> predicate) {
<add> return value -> {
<add> HttpStatus status = HttpStatus.resolve(value);
<add> return (status != null) && predicate.test(status);
<add> };
<add> }
<add>
<add> @Override
<add> public ResponseSpec onRawStatus(IntPredicate statusCodePredicate,
<add> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
<ide>
<ide> if (this.statusHandlers.size() == 1 && this.statusHandlers.get(0) == DEFAULT_STATUS_HANDLER) {
<ide> this.statusHandlers.clear();
<ide> }
<del> this.statusHandlers.add(new StatusHandler(statusPredicate,
<add> this.statusHandlers.add(new StatusHandler(statusCodePredicate,
<ide> (clientResponse, request) -> exceptionFunction.apply(clientResponse)));
<ide>
<ide> return this;
<ide> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementType) {
<ide> private <T extends Publisher<?>> T handleBody(ClientResponse response,
<ide> T bodyPublisher, Function<Mono<? extends Throwable>, T> errorFunction) {
<ide>
<del> if (HttpStatus.resolve(response.rawStatusCode()) != null) {
<del> for (StatusHandler handler : this.statusHandlers) {
<del> if (handler.test(response.statusCode())) {
<del> HttpRequest request = this.requestSupplier.get();
<del> Mono<? extends Throwable> exMono;
<del> try {
<del> exMono = handler.apply(response, request);
<del> exMono = exMono.flatMap(ex -> drainBody(response, ex));
<del> exMono = exMono.onErrorResume(ex -> drainBody(response, ex));
<del> }
<del> catch (Throwable ex2) {
<del> exMono = drainBody(response, ex2);
<del> }
<del> return errorFunction.apply(exMono);
<add> int statusCode = response.rawStatusCode();
<add> for (StatusHandler handler : this.statusHandlers) {
<add> if (handler.test(statusCode)) {
<add> HttpRequest request = this.requestSupplier.get();
<add> Mono<? extends Throwable> exMono;
<add> try {
<add> exMono = handler.apply(response, request);
<add> exMono = exMono.flatMap(ex -> drainBody(response, ex));
<add> exMono = exMono.onErrorResume(ex -> drainBody(response, ex));
<ide> }
<add> catch (Throwable ex2) {
<add> exMono = drainBody(response, ex2);
<add> }
<add> return errorFunction.apply(exMono);
<ide> }
<del> return bodyPublisher;
<del> }
<del> else {
<del> return errorFunction.apply(createResponseException(response, this.requestSupplier.get()));
<ide> }
<add> return bodyPublisher;
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private static Mono<WebClientResponseException> createResponseException(
<ide>
<ide> private static class StatusHandler {
<ide>
<del> private final Predicate<HttpStatus> predicate;
<add> private final IntPredicate predicate;
<ide>
<ide> private final BiFunction<ClientResponse, HttpRequest, Mono<? extends Throwable>> exceptionFunction;
<ide>
<del> public StatusHandler(Predicate<HttpStatus> predicate,
<add> public StatusHandler(IntPredicate predicate,
<ide> BiFunction<ClientResponse, HttpRequest, Mono<? extends Throwable>> exceptionFunction) {
<ide>
<ide> Assert.notNull(predicate, "Predicate must not be null");
<ide> public StatusHandler(Predicate<HttpStatus> predicate,
<ide> this.exceptionFunction = exceptionFunction;
<ide> }
<ide>
<del> public boolean test(HttpStatus status) {
<add> public boolean test(int status) {
<ide> return this.predicate.test(status);
<ide> }
<ide>
<ide> public Mono<? extends Throwable> apply(ClientResponse response, HttpRequest request) {
<ide> return this.exceptionFunction.apply(response, request);
<ide> }
<add>
<add>
<ide> }
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.Map;
<ide> import java.util.function.Consumer;
<ide> import java.util.function.Function;
<add>import java.util.function.IntPredicate;
<ide> import java.util.function.Predicate;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> interface ResponseSpec {
<ide> * Register a custom error function that gets invoked when the given {@link HttpStatus}
<ide> * predicate applies. The exception returned from the function will be returned from
<ide> * {@link #bodyToMono(Class)} and {@link #bodyToFlux(Class)}.
<del> * <p>By default, an error handler is register that throws a
<add> * <p>By default, an error handler is registered that throws a
<ide> * {@link WebClientResponseException} when the response status code is 4xx or 5xx.
<ide> * @param statusPredicate a predicate that indicates whether {@code exceptionFunction}
<ide> * applies
<ide> interface ResponseSpec {
<ide> ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate,
<ide> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction);
<ide>
<add> /**
<add> * Register a custom error function that gets invoked when the given raw status code
<add> * predicate applies. The exception returned from the function will be returned from
<add> * {@link #bodyToMono(Class)} and {@link #bodyToFlux(Class)}.
<add> * <p>By default, an error handler is registered that throws a
<add> * {@link WebClientResponseException} when the response status code is 4xx or 5xx.
<add> * @param statusCodePredicate a predicate of the raw status code that indicates
<add> * whether {@code exceptionFunction} applies.
<add> * <p><strong>NOTE:</strong> if the response is expected to have content,
<add> * the exceptionFunction should consume it. If not, the content will be
<add> * automatically drained to ensure resources are released.
<add> * @param exceptionFunction the function that returns the exception
<add> * @return this builder
<add> * @since 5.1.9
<add> */
<add> ResponseSpec onRawStatus(IntPredicate statusCodePredicate,
<add> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction);
<add>
<ide> /**
<ide> * Extract the body to a {@code Mono}. By default, if the response has status code 4xx or
<ide> * 5xx, the {@code Mono} will contain a {@link WebClientException}. This can be overridden
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<ide> import org.springframework.http.codec.Pojo;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNotNull;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.assertThat;
<add>import static org.junit.Assert.assertTrue;
<ide>
<ide> /**
<ide> * Integration tests using an {@link ExchangeFunction} through {@link WebClient}.
<ide> public void shouldApplyCustomStatusHandler() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> public void shouldApplyCustomRawStatusHandler() {
<add> prepareResponse(response -> response.setResponseCode(500)
<add> .setHeader("Content-Type", "text/plain").setBody("Internal Server error"));
<add>
<add> Mono<String> result = this.webClient.get()
<add> .uri("/greeting?name=Spring")
<add> .retrieve()
<add> .onRawStatus(value -> value >= 500 && value < 600, response -> Mono.just(new MyException("500 error!")))
<add> .bodyToMono(String.class);
<add>
<add> StepVerifier.create(result)
<add> .expectError(MyException.class)
<add> .verify(Duration.ofSeconds(3));
<add>
<add> expectRequestCount(1);
<add> expectRequest(request -> {
<add> assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT));
<add> assertEquals("/greeting?name=Spring", request.getPath());
<add> });
<add> }
<add>
<ide> @Test
<ide> public void shouldApplyCustomStatusHandlerParameterizedTypeReference() {
<ide> prepareResponse(response -> response.setResponseCode(500) | 3 |
Java | Java | optimize iteration of readablenativemaps | 503a6f4463f5d2f7576b33158c18d8d8e99f3291 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.jni.HybridData;
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<add>import com.facebook.react.config.ReactFeatureFlags;
<ide> import java.util.HashMap;
<ide> import java.util.Iterator;
<ide> import java.util.Map;
<ide> private HashMap<String, Object> getLocalMap() {
<ide> return mLocalTypeMap;
<ide> }
<ide>
<add> private Iterator<Map.Entry<String, Object>> createExperimentalIterator() {
<add> if (mKeys == null) {
<add> mKeys = Assertions.assertNotNull(importKeys());
<add> }
<add> final String[] iteratorKeys = mKeys;
<add> final Object[] iteratorValues = Assertions.assertNotNull(importValues());
<add> return new Iterator<Map.Entry<String, Object>>() {
<add> int currentIndex = 0;
<add>
<add> @Override
<add> public boolean hasNext() {
<add> return currentIndex < iteratorKeys.length;
<add> }
<add>
<add> @Override
<add> public Map.Entry<String, Object> next() {
<add> final int index = currentIndex++;
<add> return new Map.Entry<String, Object>() {
<add> @Override
<add> public String getKey() {
<add> return iteratorKeys[index];
<add> }
<add>
<add> @Override
<add> public Object getValue() {
<add> return iteratorValues[index];
<add> }
<add>
<add> @Override
<add> public Object setValue(Object value) {
<add> throw new UnsupportedOperationException(
<add> "Can't set a value while iterating over a ReadableNativeMap");
<add> }
<add> };
<add> }
<add> };
<add> }
<add>
<add> private ReadableMapKeySetIterator createExperimentalKeySetIterator() {
<add> if (mKeys == null) {
<add> mKeys = Assertions.assertNotNull(importKeys());
<add> }
<add> final String[] iteratorKeys = mKeys;
<add> return new ReadableMapKeySetIterator() {
<add> int currentIndex = 0;
<add>
<add> @Override
<add> public boolean hasNextKey() {
<add> return currentIndex < iteratorKeys.length;
<add> }
<add>
<add> @Override
<add> public String nextKey() {
<add> return iteratorKeys[currentIndex++];
<add> }
<add> };
<add> }
<add>
<ide> private native Object[] importTypes();
<ide>
<ide> @Override
<ide> public int getInt(@NonNull String name) {
<ide>
<ide> @Override
<ide> public @NonNull Iterator<Map.Entry<String, Object>> getEntryIterator() {
<del> return getLocalMap().entrySet().iterator();
<add> return ReactFeatureFlags.enableExperimentalReadableNativeMapIterator
<add> ? createExperimentalIterator()
<add> : getLocalMap().entrySet().iterator();
<ide> }
<ide>
<ide> @Override
<ide> public @NonNull ReadableMapKeySetIterator keySetIterator() {
<del> return new ReadableNativeMapKeySetIterator(this);
<add> return ReactFeatureFlags.enableExperimentalReadableNativeMapIterator
<add> ? createExperimentalKeySetIterator()
<add> : new ReadableNativeMapKeySetIterator(this);
<ide> }
<ide>
<ide> @Override
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public class ReactFeatureFlags {
<ide> * we verify the fix is correct in production
<ide> */
<ide> public static boolean enableStartSurfaceRaceConditionFix = false;
<add>
<add> /** Enables the usage of an experimental optimized iterator for ReadableNativeMaps. */
<add> public static boolean enableExperimentalReadableNativeMapIterator = false;
<ide> } | 2 |
Text | Text | add a troubleshooting guide | 54ff1f97b8588d0baf6131df2b18e4194fd3e272 | <ide><path>docs/guides/troubleshooting.md
<add> Troubleshooting
<add>
<add>## Problems with media formats
<add>
<add>### Choosing a video format
<add>#### I want to have a single source and don't care about live/adaptive streaming:
<add>Most browsers now play MP4 with h264 video. If you want to have a single source, and neither live streaming
<add>nor adaptive streaming is a consideration, MP4 is a good choice.
<add>
<add>#### I need adaptive streaming or live streaming
<add>Use HLS with [videojs-contrib-hls][hls] or
<add>Use Dash with [videojs-contrib-dash][dash].
<add>HLS is more convenient as mobile browsers have native support.
<add>
<add>### Make sure you are using formats that video.js can play:
<add>* Does your browser/OS support the type of media that you are trying to play?
<add>* Do you have a video.js plugin that will add support for a media format to video.js? For Example:
<add> * [videojs-youtube][youtube]
<add> * [videojs-contrib-hls][hls]
<add> * [videojs-contrib-dash][dash]
<add>* Verify that you are using the correct [mime-type/content-type][media-types] for your videos.
<add> This is used to determine if video.js can play a certain type of media.
<add>
<add>### Make sure that the codec for that is being used in the file container is supported:
<add>* MP4 in browsers typically only supports h264 video and MP3 or AAC audio
<add>* Some low end phones save video in 3GP format but give it an MP4 extension. These files will not play.
<add>
<add>### If you are using Flash videos:
<add>* Make sure that Flash is installed
<add>* Make sure the Flash tech is included with video.js (in `video.js >= v6.0.0` it won't be, see [videojs-flash][flash])
<add>* Flash media include RTMP streams and FLV format media.
<add>* SWF is not a media format
<add>
<add>## Problems when hosting media
<add>* Your server must support byte-range requests as Chrome and Safari rely on them:
<add> * Most servers support this by default.
<add> * If you are proxying the media files via a server side script (PHP), this script must implement ranges. PHP does not do this by default.
<add> * The impact of not doing this ranges from seeking being broken to no playback at all (on iOS).
<add>* Your server must return the correct [mime-type/content-type][media-types] for the media being sent.
<add>* Your server must implement [CORS (cross-origin resource)][cors] headers if:
<add> * You are using [videojs-contrib-hls][hls], [videojs-contrib-dash][dash] and your media is served from a different domain than your page.
<add> * You are using [text tracks][text-tracks] (captions, subtitles, etc.) and they are being served from a different domain than your page.
<add>
<add>## Problems with Fullscreen
<add>* If your player is in an iframe, the parent iframes must have the following attributes for fullscreen to be allowed:
<add> * `allowfullscreen`
<add> * `webkitallowfullscreen`
<add> * `mozallowfullscreen`
<add>
<add>## Problems with playback
<add>* Make sure that the media host supports byte-range requests, this could be breaking playback. See [Problems when Hosting media][hosting-media] for more info.
<add>* If your media is taking a long time to start playback or the entire mediadownloads before playback:
<add> * It is likely that metadata for the media has not been included at the start of the media. In MP4 terms this is called
<add> the "moov atom". Many encoders are configured to do this by default, others may require you to choose
<add> a "fast start" or "optimize for streaming" option.
<add>
<add>## video.js Errors
<add>### vdata123456 errors
<add>This error is thrown when an element that is associated with a component is removed
<add>from the DOM but the event handlers associated with the element are not removed. This
<add>is almost always due to event listeners not being disposed when dispose is called on
<add>a component.
<add>
<add>To fix this issue please make sure that all event listeners are cleaned up on dispose.
<add>
<add><!-- same-page -->
<add>[hosting-problems]: #problems-when-hosting-media
<add>
<add><!-- guides -->
<add>[text-tracks]: /docs/guides/text-tracks.md
<add>
<add><!-- official projects -->
<add>[hls]: https://github.com/videojs/videojs-contrib-hls
<add>[dash]: https://github.com/videojs/videojs-contrib-dash
<add>[youtube]: https://github.com/videojs/videojs-youtube
<add>[flash]: https://github.com/videojs/videojs-flash
<add>
<add><!-- External links -->
<add>[media-types]: http://www.iana.org/assignments/media-types/media-types.xhtml#video
<add>[cors]: http://enable-cors.org/ | 1 |
Javascript | Javascript | support an empty context | c0686c443016a0757bb1f1ec2196b183af38aee9 | <ide><path>lib/ContextModule.js
<ide> ContextModule.prototype.build = function(options, compilation, resolver, fs, cal
<ide> var addon = this.addon;
<ide> this.resolveDependencies(fs, this.context, this.recursive, this.regExp, function(err, dependencies) {
<ide> if(err) return callback(err);
<del> dependencies.forEach(function(dep) {
<del> dep.userRequest = dep.request;
<del> dep.request = addon + dep.userRequest;
<del> });
<add> if(dependencies) {
<add> dependencies.forEach(function(dep) {
<add> dep.userRequest = dep.request;
<add> dep.request = addon + dep.userRequest;
<add> });
<add> }
<ide> this.dependencies = dependencies;
<ide> callback();
<ide> }.bind(this));
<ide> };
<ide>
<ide> ContextModule.prototype.source = function(dependencyTemplates, outputOptions, requestShortener) {
<del> if(this.dependencies.length > 0) {
<add> if(this.dependencies && this.dependencies.length > 0) {
<ide> var map = {};
<ide> this.dependencies.slice().sort(function(a,b) {
<ide> if(a.userRequest === b.userRequest) return 0;
<ide> ContextModule.prototype.source = function(dependencyTemplates, outputOptions, re
<ide> "function webpackContext(req) {\n",
<ide> "\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
<ide> "}\n",
<del> "webpackContext.resolve = webpackContext;\n",
<ide> "webpackContext.keys = function() { return []; };\n",
<del> "module.exports = webpackContext;\n"
<add> "webpackContext.resolve = webpackContext;\n",
<add> "module.exports = webpackContext;\n",
<add> "webpackContext.id = "+this.id+";\n",
<ide> ];
<ide> }
<ide> if(this.useSourceMap) {
<ide><path>test/cases/context/issue-524/index.js
<add>it("should support an empty context", function() {
<add> var c = require.context(".", true, /^nothing$/);
<add> c.id.should.be.type("number");
<add> (function() {
<add> c.resolve("");
<add> }).should.throw();
<add> (function() {
<add> c("");
<add> }).should.throw();
<add> c.keys().should.be.eql([]);
<add>});
<ide>\ No newline at end of file | 2 |
Go | Go | update the unit tests to reflect the new api | ff95f2b0ecf54fdfeffa1aa008e22cb5c7ec59d6 | <ide><path>commands_test.go
<ide> func TestAttachDisconnect(t *testing.T) {
<ide>
<ide> srv := &Server{runtime: runtime}
<ide>
<del> container, err := runtime.Create(
<add> container, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Memory: 33554432,
<ide><path>container_test.go
<ide> func TestIdFormat(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container1, err := runtime.Create(
<add> container1, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/sh", "-c", "echo hello world"},
<ide> func TestMultipleAttachRestart(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(
<add> container, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/sh", "-c",
<ide> func TestDiff(t *testing.T) {
<ide> }
<ide> defer nuke(runtime)
<ide>
<add> builder := NewBuilder(runtime)
<add>
<ide> // Create a container and remove a file
<del> container1, err := runtime.Create(
<add> container1, err := builder.Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/rm", "/etc/passwd"},
<ide> func TestDiff(t *testing.T) {
<ide> }
<ide>
<ide> // Create a new container from the commited image
<del> container2, err := runtime.Create(
<add> container2, err := builder.Create(
<ide> &Config{
<ide> Image: img.Id,
<ide> Cmd: []string{"cat", "/etc/passwd"},
<ide> func TestCommitRun(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container1, err := runtime.Create(
<add>
<add> builder := NewBuilder(runtime)
<add>
<add> container1, err := builder.Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/sh", "-c", "echo hello > /world"},
<ide> func TestCommitRun(t *testing.T) {
<ide>
<ide> // FIXME: Make a TestCommit that stops here and check docker.root/layers/img.id/world
<ide>
<del> container2, err := runtime.Create(
<add> container2, err := builder.Create(
<ide> &Config{
<ide> Image: img.Id,
<ide> Cmd: []string{"cat", "/world"},
<ide> func TestStart(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(
<add> container, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Memory: 33554432,
<ide> func TestRun(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(
<add> container, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> func TestOutput(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(
<add> container, err := NewBuilder(runtime).Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"echo", "-n", "foobar"},
<ide> func TestKillDifferentUser(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"tail", "-f", "/etc/resolv.conf"},
<ide> User: "daemon",
<ide> func TestKill(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat", "/dev/zero"},
<ide> },
<ide> func TestExitCode(t *testing.T) {
<ide> }
<ide> defer nuke(runtime)
<ide>
<del> trueContainer, err := runtime.Create(&Config{
<add> builder := NewBuilder(runtime)
<add>
<add> trueContainer, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/true", ""},
<ide> })
<ide> func TestExitCode(t *testing.T) {
<ide> t.Errorf("Unexpected exit code %d (expected 0)", trueContainer.State.ExitCode)
<ide> }
<ide>
<del> falseContainer, err := runtime.Create(&Config{
<add> falseContainer, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/false", ""},
<ide> })
<ide> func TestRestart(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"echo", "-n", "foobar"},
<ide> },
<ide> func TestRestartStdin(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat"},
<ide>
<ide> func TestUser(t *testing.T) {
<ide> }
<ide> defer nuke(runtime)
<ide>
<add> builder := NewBuilder(runtime)
<add>
<ide> // Default user must be root
<del> container, err := runtime.Create(&Config{
<add> container, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"id"},
<ide> },
<ide> func TestUser(t *testing.T) {
<ide> }
<ide>
<ide> // Set a username
<del> container, err = runtime.Create(&Config{
<add> container, err = builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"id"},
<ide>
<ide> func TestUser(t *testing.T) {
<ide> }
<ide>
<ide> // Set a UID
<del> container, err = runtime.Create(&Config{
<add> container, err = builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"id"},
<ide>
<ide> func TestUser(t *testing.T) {
<ide> }
<ide>
<ide> // Set a different user by uid
<del> container, err = runtime.Create(&Config{
<add> container, err = builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"id"},
<ide>
<ide> func TestUser(t *testing.T) {
<ide> }
<ide>
<ide> // Set a different user by username
<del> container, err = runtime.Create(&Config{
<add> container, err = builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"id"},
<ide>
<ide> func TestMultipleContainers(t *testing.T) {
<ide> }
<ide> defer nuke(runtime)
<ide>
<del> container1, err := runtime.Create(&Config{
<add> builder := NewBuilder(runtime)
<add>
<add> container1, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat", "/dev/zero"},
<ide> },
<ide> func TestMultipleContainers(t *testing.T) {
<ide> }
<ide> defer runtime.Destroy(container1)
<ide>
<del> container2, err := runtime.Create(&Config{
<add> container2, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat", "/dev/zero"},
<ide> },
<ide> func TestStdin(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat"},
<ide>
<ide> func TestTty(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"cat"},
<ide>
<ide> func TestEnv(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/usr/bin/env"},
<ide> },
<ide> func TestLXCConfig(t *testing.T) {
<ide> memMin := 33554432
<ide> memMax := 536870912
<ide> mem := memMin + rand.Intn(memMax-memMin)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"/bin/true"},
<ide>
<ide> func BenchmarkRunSequencial(b *testing.B) {
<ide> }
<ide> defer nuke(runtime)
<ide> for i := 0; i < b.N; i++ {
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"echo", "-n", "foo"},
<ide> },
<ide> func BenchmarkRunParallel(b *testing.B) {
<ide> complete := make(chan error)
<ide> tasks = append(tasks, complete)
<ide> go func(i int, complete chan error) {
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"echo", "-n", "foo"},
<ide> },
<ide><path>runtime_test.go
<ide> func TestRuntimeCreate(t *testing.T) {
<ide> if len(runtime.List()) != 0 {
<ide> t.Errorf("Expected 0 containers, %v found", len(runtime.List()))
<ide> }
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestDestroy(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestGet(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer nuke(runtime)
<del> container1, err := runtime.Create(&Config{
<add>
<add> builder := NewBuilder(runtime)
<add>
<add> container1, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestGet(t *testing.T) {
<ide> }
<ide> defer runtime.Destroy(container1)
<ide>
<del> container2, err := runtime.Create(&Config{
<add> container2, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestGet(t *testing.T) {
<ide> }
<ide> defer runtime.Destroy(container2)
<ide>
<del> container3, err := runtime.Create(&Config{
<add> container3, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestAllocatePortLocalhost(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> container, err := runtime.Create(&Config{
<add> container, err := NewBuilder(runtime).Create(&Config{
<ide> Image: GetTestImage(runtime).Id,
<ide> Cmd: []string{"sh", "-c", "echo well hello there | nc -l -p 5555"},
<ide> PortSpecs: []string{"5555"},
<ide> func TestRestore(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> builder := NewBuilder(runtime1)
<add>
<ide> // Create a container with one instance of docker
<del> container1, err := runtime1.Create(&Config{
<add> container1, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime1).Id,
<ide> Cmd: []string{"ls", "-al"},
<ide> },
<ide> func TestRestore(t *testing.T) {
<ide> defer runtime1.Destroy(container1)
<ide>
<ide> // Create a second container meant to be killed
<del> container2, err := runtime1.Create(&Config{
<add> container2, err := builder.Create(&Config{
<ide> Image: GetTestImage(runtime1).Id,
<ide> Cmd: []string{"/bin/cat"},
<ide> OpenStdin: true, | 3 |
Ruby | Ruby | remove debug output | d3e2a98136385197f52f6f979378efed6cdad202 | <ide><path>Library/Homebrew/livecheck/strategy/page_match.rb
<ide> def self.match?(url)
<ide> def self.page_matches(url, regex, &block)
<ide> page = Strategy.page_contents(url)
<ide>
<del> odebug "Page Contents", page
<del>
<ide> if block
<ide> data = { page: page }
<ide> case (value = block.call(data)) | 1 |
Javascript | Javascript | fix console warning in legacyimmutableobject | 335e91df7146739dcc287b638e29b068f1451bbe | <ide><path>src/utils/LegacyImmutableObject.js
<ide> if (__DEV__) {
<ide> }
<ide> Object.freeze(object); // First freeze the object.
<ide> for (var prop in object) {
<del> var field = object[prop];
<del> if (object.hasOwnProperty(prop) && shouldRecurseFreeze(field)) {
<del> deepFreeze(field);
<add> if (object.hasOwnProperty(prop)) {
<add> var field = object[prop];
<add> if (shouldRecurseFreeze(field)) {
<add> deepFreeze(field);
<add> }
<ide> }
<ide> }
<ide> }; | 1 |
Javascript | Javascript | simplify regex in eslint config | 16a25afebb501b32b2ee63fc27e2fbf3d3bd8932 | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> line: {
<ide> // Ignore all lines that have less characters than 20 and all lines that
<ide> // start with something that looks like a variable name or code.
<del> // eslint-disable-next-line max-len
<del> ignorePattern: '.{0,20}$|[a-z]+ ?[0-9A-Z_.(/=:[#-]|std|http|ssh|ftp|(let|var|const) [a-z_A-Z0-9]+ =|[b-z] |[a-z]*[0-9].* ',
<add> ignorePattern: '.{0,20}$|[a-z]+ ?[0-9A-Z_.(/=:[#-]|std|http|ssh|ftp',
<ide> ignoreInlineComments: true,
<ide> ignoreConsecutiveComments: true,
<ide> },
<ide><path>test/parallel/test-fs-readv-promises.js
<ide> const allocateEmptyBuffers = (combinedLength) => {
<ide> const filename = getFileName();
<ide> await fs.writeFile(filename, exptectedBuff);
<ide> const handle = await fs.open(filename, 'r');
<del> // const buffer = Buffer.from(expected);
<ide> const bufferArr = allocateEmptyBuffers(exptectedBuff.length);
<ide> const expectedLength = exptectedBuff.length;
<ide>
<ide> const allocateEmptyBuffers = (combinedLength) => {
<ide> const filename = getFileName();
<ide> await fs.writeFile(filename, exptectedBuff);
<ide> const handle = await fs.open(filename, 'r');
<del> // const buffer = Buffer.from(expected);
<ide> const bufferArr = allocateEmptyBuffers(exptectedBuff.length);
<ide> const expectedLength = exptectedBuff.length;
<ide> | 2 |
PHP | PHP | apply fixes from styleci | 9717c195fa4ab1edb489041b82563c28d7edb52a | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Carbon;
<ide> use Illuminate\Support\Facades\Date;
<del>use Illuminate\Support\Stringable;
<ide> use Illuminate\Support\Reflector;
<add>use Illuminate\Support\Stringable;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Psr\Http\Client\ClientExceptionInterface;
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Facades\Auth;
<ide> use Illuminate\Support\Facades\View;
<del>use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Illuminate\Support\Reflector;
<add>use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Illuminate\Support\ViewErrorBag;
<ide> use Illuminate\Validation\ValidationException;
<ide> use InvalidArgumentException; | 2 |
Ruby | Ruby | fix tests on ruby 2.0.0 | 1c1f65430046fa0041acc898d8d6f5377f20806e | <ide><path>actionpack/lib/action_view/routing_url_for.rb
<ide> def _routes_context #:nodoc:
<ide> protected :_routes_context
<ide>
<ide> def optimize_routes_generation? #:nodoc:
<del> controller.respond_to?(:optimize_routes_generation?) ?
<add> controller.respond_to?(:optimize_routes_generation?, true) ?
<ide> controller.optimize_routes_generation? : super
<ide> end
<ide> protected :optimize_routes_generation? | 1 |
Javascript | Javascript | use shorter weekdaysmin in italian | 40d24da3345a3aa72b8ef2854fdd19fddcbe1aed | <ide><path>lang/it.js
<ide> monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),
<ide> weekdays : "Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),
<ide> weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),
<del> weekdaysMin : "Do_Lu_Ma_Me_Gi_Ve_Sa".split("_"),
<add> weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"),
<ide> longDateFormat : {
<ide> LT : "HH:mm",
<ide> L : "DD/MM/YYYY",
<ide><path>min/lang-all.min.js
<ide> // moment.js language configuration
<ide> // language : catalan (ca)
<ide> // author : Juan G. Hurtado : https://github.com/juanghurtado
<del>(function(){var a={months:"Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"),monthsShort:"Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"),weekdays:"Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"),weekdaysShort:"Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[avui a "+(this.hours()!==1?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(this.hours()!==1?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(this.hours()!==1?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(this.hours()!==1?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(this.hours()!==1?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ca",a)})(),function(){var a={months:"кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"),monthsShort:"кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кç_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ",LLL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT",LLLL:"dddd, YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ĕнер] LT [сехетре]",nextWeek:"[Çитес] dddd LT [сехетре]",lastWeek:"[Иртнĕ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:"%sран",past:"%s каялла",s:"пĕр-ик çеккунт",m:"пĕр минут",mm:"%d минут",h:"пĕр сехет",hh:"%d сехет",d:"пĕр кун",dd:"%d кун",M:"пĕр уйăх",MM:"%d уйăх",y:"пĕр çул",yy:"%d çул"},ordinal:function(a){return"-мĕш"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("cv",a)}(),function(){var a={months:"Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Maj_Jun_Jul_Aug_Sep_Okt_Nov_Dec".split("_"),weekdays:"Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag".split("_"),weekdaysShort:"Søn_Man_Tir_Ons_Tor_Fre_Lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd D. MMMM, YYYY h:mm A"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"minut",mm:"%d minutter",h:"time",hh:"%d timer",d:"dag",dd:"%d dage",M:"månede",MM:"%d måneder",y:"år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("da",a)}(),function(){var a={months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm U\\hr",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY LT",LLLL:"dddd, D. MMMM YYYY LT"},calendar:{sameDay:"[Heute um] LT",sameElse:"L",nextDay:"[Morgen um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gestern um] LT",lastWeek:"[letzten] dddd [um] LT"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:"einer Minute",mm:"%d Minuten",h:"einer Stunde",hh:"%d Stunden",d:"einem Tag",dd:"%d Tagen",M:"einem Monat",MM:"%d Monaten",y:"einem Jahr",yy:"%d Jahren"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("de",a)}(),function(){var a={months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("en-gb",a)}(),function(){var a={months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_"),weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoy a la"+(this.hours()!==1?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(this.hours()!==1?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(this.hours()!==1?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(this.hours()!==1?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(this.hours()!==1?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("es",a)}(),function(){var a={months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"Ig_Al_Ar_Az_Og_Ol_Lr".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"YYYYko MMMMren D[a]",LLL:"YYYYko MMMMren D[a] LT",LLLL:"dddd, YYYYko MMMMren D[a] LT"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("eu",a)}(),function(){function c(a,b,c,e){var f="";switch(c){case"s":return e?"muutaman sekunnin":"muutama sekunti";case"m":return e?"minuutin":"minuutti";case"mm":f=e?"minuutin":"minuuttia";break;case"h":return e?"tunnin":"tunti";case"hh":f=e?"tunnin":"tuntia";break;case"d":return e?"päivän":"päivä";case"dd":f=e?"päivän":"päivää";break;case"M":return e?"kuukauden":"kuukausi";case"MM":f=e?"kuukauden":"kuukautta";break;case"y":return e?"vuoden":"vuosi";case"yy":f=e?"vuoden":"vuotta"}return f=d(a,e)+" "+f,f}function d(c,d){return c<10?d?b[c]:a[c]:c}var a=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän"],b=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",a[7],a[8],a[9]],e={months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tam_hel_maa_huh_tou_kes_hei_elo_syy_lok_mar_jou".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"Su_Ma_Ti_Ke_To_Pe_La".split("_"),longDateFormat:{LT:"HH.mm",L:"DD.MM.YYYY",LL:"Do MMMMt\\a YYYY",LLL:"Do MMMMt\\a YYYY, klo LT",LLLL:"dddd, Do MMMMt\\a YYYY, klo LT"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:c,m:c,mm:c,h:c,hh:c,d:c,dd:c,M:c,MM:c,y:c,yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=e),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fi",e)}(),function(){var a={months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"D_L_Ma_Me_J_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"une année",yy:"%d années"},ordinal:function(a){return a===1?"er":"ème"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fr",a)}(),function(){var a={months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Octubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoxe "+(this.hours()!==1?"ás":"a")+"] LT"},nextDay:function(){return"[mañá "+(this.hours()!==1?"ás":"a")+"] LT"},nextWeek:function(){return"dddd ["+(this.hours()!==1?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(this.hours()!==1?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(this.hours()!==1?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fai %s",s:"uns segundo",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("gl",a)}(),function(){var a=function(a){return a%100==11?!0:a%10==1?!1:!0},b=function(b,c,d,e){var f=b+" ";switch(d){case"s":return c||e?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return c?"mínúta":"mínútu";case"mm":return a(b)?f+(c||e?"mínútur":"mínútum"):c?f+"mínúta":f+"mínútu";case"hh":return a(b)?f+(c||e?"klukkustundir":"klukkustundum"):f+"klukkustund";case"d":return c?"dagur":e?"dag":"degi";case"dd":return a(b)?c?f+"dagar":f+(e?"daga":"dögum"):c?f+"dagur":f+(e?"dag":"degi");case"M":return c?"mánuður":e?"mánuð":"mánuði";case"MM":return a(b)?c?f+"mánuðir":f+(e?"mánuði":"mánuðum"):c?f+"mánuður":f+(e?"mánuð":"mánuði");case"y":return c||e?"ár":"ári";case"yy":return a(b)?f+(c||e?"ár":"árum"):f+(c||e?"ár":"ári")}},c={months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY kl. LT",LLLL:"dddd, D. MMMM YYYY kl. LT"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:b,m:b,mm:b,h:"klukkustund",hh:b,d:b,dd:b,M:b,MM:b,y:b,yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("is",c)}(),function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"Do_Lu_Ma_Me_Gi_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)}(),function(){var a={months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah:mm",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 LT",LLLL:"YYYY年M月D日 dddd LT"},meridiem:function(a,b,c){return a<12?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("jp",a)}(),function(){var a={months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 mm분",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 LT",LLLL:"YYYY년 MMMM D일 dddd LT"},meridiem:function(a,b,c){return a<12?"오전":"오후"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinal:function(a){return"일"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("kr",a)}(),function(){var a={months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[I dag klokken] LT",nextDay:"[I morgen klokken] LT",nextWeek:"dddd [klokken] LT",lastDay:"[I går klokken] LT",lastWeek:"[Forrige] dddd [klokken] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nb",a)}(),function(){var a={months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._mei._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Vandaag om] LT",nextDay:"[Morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinal:function(a){return a===1||a===8||a>=20?"ste":"de"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nl",a)}(),function(){var a=function(a){return a%10<5&&a%10>1&&~~(a/10)!==1},b=function(b,c,d){var e=b+" ";switch(d){case"m":return c?"minuta":"minutę";case"mm":return e+(a(b)?"minuty":"minut");case"h":return c?"godzina":"godzinę";case"hh":return e+(a(b)?"godziny":"godzin");case"MM":return e+(a(b)?"miesiące":"miesięcy");case"yy":return e+(a(b)?"lata":"lat")}},c={months:"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"),monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:"[W zeszły/łą] dddd [o] LT",sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:b,mm:b,h:b,hh:b,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:b,y:"rok",yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pl",c)}(),function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)}(),function(){var a=[function(a){return a%10===1&&a%100!==11},function(a){return a%10>=2&&a%10<=4&&a%10%1===0&&(a%100<12||a%100>14)},function(a){return a%10===0||a%10>=5&&a%10<=9&&a%10%1===0||a%100>=11&&a%100<=14&&a%100%1===0},function(a){return!0}],b=function(b,c){var d=b.split("_"),e=Math.min(a.length,d.length),f=-1;while(++f<e)if(a[f](c))return d[f];return d[e-1]},c=function(a,c,d){var e={mm:"минута_минуты_минут_минуты",hh:"час_часа_часов_часа",dd:"день_дня_дней_дня",MM:"месяц_месяца_месяцев_месяца",yy:"год_года_лет_года"};return d==="m"?c?"минута":"минуту":a+" "+b(e[d],+a)},d={months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),weekdaysShort:"вск_пнд_втр_срд_чтв_птн_суб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return this.day()===2?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(){switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:c,mm:c,h:"час",hh:c,d:"день",dd:c,M:"месяц",MM:c,y:"год",yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=d),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ru",d)}(),function(){var a={months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"Sö_Må_Ti_On_To_Fr_Lö".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Idag klockan] LT",nextDay:"[Imorgon klockan] LT",lastDay:"[Igår klockan] LT",nextWeek:"dddd [klockan] LT",lastWeek:"[Förra] dddd[en klockan] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sen",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"e":b===1?"a":b===2?"a":b===3?"e":"e"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("sv",a)}(),function(){var a={months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("tr",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-cn",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-tw",a)}();
<ide>\ No newline at end of file
<add>(function(){var a={months:"Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"),monthsShort:"Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"),weekdays:"Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"),weekdaysShort:"Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[avui a "+(this.hours()!==1?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(this.hours()!==1?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(this.hours()!==1?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(this.hours()!==1?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(this.hours()!==1?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ca",a)})(),function(){var a={months:"кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"),monthsShort:"кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кç_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ",LLL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT",LLLL:"dddd, YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ĕнер] LT [сехетре]",nextWeek:"[Çитес] dddd LT [сехетре]",lastWeek:"[Иртнĕ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:"%sран",past:"%s каялла",s:"пĕр-ик çеккунт",m:"пĕр минут",mm:"%d минут",h:"пĕр сехет",hh:"%d сехет",d:"пĕр кун",dd:"%d кун",M:"пĕр уйăх",MM:"%d уйăх",y:"пĕр çул",yy:"%d çул"},ordinal:function(a){return"-мĕш"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("cv",a)}(),function(){var a={months:"Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Maj_Jun_Jul_Aug_Sep_Okt_Nov_Dec".split("_"),weekdays:"Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag".split("_"),weekdaysShort:"Søn_Man_Tir_Ons_Tor_Fre_Lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd D. MMMM, YYYY h:mm A"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"minut",mm:"%d minutter",h:"time",hh:"%d timer",d:"dag",dd:"%d dage",M:"månede",MM:"%d måneder",y:"år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("da",a)}(),function(){var a={months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm U\\hr",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY LT",LLLL:"dddd, D. MMMM YYYY LT"},calendar:{sameDay:"[Heute um] LT",sameElse:"L",nextDay:"[Morgen um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gestern um] LT",lastWeek:"[letzten] dddd [um] LT"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:"einer Minute",mm:"%d Minuten",h:"einer Stunde",hh:"%d Stunden",d:"einem Tag",dd:"%d Tagen",M:"einem Monat",MM:"%d Monaten",y:"einem Jahr",yy:"%d Jahren"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("de",a)}(),function(){var a={months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("en-gb",a)}(),function(){var a={months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_"),weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoy a la"+(this.hours()!==1?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(this.hours()!==1?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(this.hours()!==1?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(this.hours()!==1?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(this.hours()!==1?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("es",a)}(),function(){var a={months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"Ig_Al_Ar_Az_Og_Ol_Lr".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"YYYYko MMMMren D[a]",LLL:"YYYYko MMMMren D[a] LT",LLLL:"dddd, YYYYko MMMMren D[a] LT"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("eu",a)}(),function(){function c(a,b,c,e){var f="";switch(c){case"s":return e?"muutaman sekunnin":"muutama sekunti";case"m":return e?"minuutin":"minuutti";case"mm":f=e?"minuutin":"minuuttia";break;case"h":return e?"tunnin":"tunti";case"hh":f=e?"tunnin":"tuntia";break;case"d":return e?"päivän":"päivä";case"dd":f=e?"päivän":"päivää";break;case"M":return e?"kuukauden":"kuukausi";case"MM":f=e?"kuukauden":"kuukautta";break;case"y":return e?"vuoden":"vuosi";case"yy":f=e?"vuoden":"vuotta"}return f=d(a,e)+" "+f,f}function d(c,d){return c<10?d?b[c]:a[c]:c}var a=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän"],b=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",a[7],a[8],a[9]],e={months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tam_hel_maa_huh_tou_kes_hei_elo_syy_lok_mar_jou".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"Su_Ma_Ti_Ke_To_Pe_La".split("_"),longDateFormat:{LT:"HH.mm",L:"DD.MM.YYYY",LL:"Do MMMMt\\a YYYY",LLL:"Do MMMMt\\a YYYY, klo LT",LLLL:"dddd, Do MMMMt\\a YYYY, klo LT"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:c,m:c,mm:c,h:c,hh:c,d:c,dd:c,M:c,MM:c,y:c,yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=e),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fi",e)}(),function(){var a={months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"D_L_Ma_Me_J_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"une année",yy:"%d années"},ordinal:function(a){return a===1?"er":"ème"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fr",a)}(),function(){var a={months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Octubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoxe "+(this.hours()!==1?"ás":"a")+"] LT"},nextDay:function(){return"[mañá "+(this.hours()!==1?"ás":"a")+"] LT"},nextWeek:function(){return"dddd ["+(this.hours()!==1?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(this.hours()!==1?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(this.hours()!==1?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fai %s",s:"uns segundo",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("gl",a)}(),function(){var a=function(a){return a%100==11?!0:a%10==1?!1:!0},b=function(b,c,d,e){var f=b+" ";switch(d){case"s":return c||e?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return c?"mínúta":"mínútu";case"mm":return a(b)?f+(c||e?"mínútur":"mínútum"):c?f+"mínúta":f+"mínútu";case"hh":return a(b)?f+(c||e?"klukkustundir":"klukkustundum"):f+"klukkustund";case"d":return c?"dagur":e?"dag":"degi";case"dd":return a(b)?c?f+"dagar":f+(e?"daga":"dögum"):c?f+"dagur":f+(e?"dag":"degi");case"M":return c?"mánuður":e?"mánuð":"mánuði";case"MM":return a(b)?c?f+"mánuðir":f+(e?"mánuði":"mánuðum"):c?f+"mánuður":f+(e?"mánuð":"mánuði");case"y":return c||e?"ár":"ári";case"yy":return a(b)?f+(c||e?"ár":"árum"):f+(c||e?"ár":"ári")}},c={months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY kl. LT",LLLL:"dddd, D. MMMM YYYY kl. LT"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:b,m:b,mm:b,h:"klukkustund",hh:b,d:b,dd:b,M:b,MM:b,y:b,yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("is",c)}(),function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)}(),function(){var a={months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah:mm",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 LT",LLLL:"YYYY年M月D日 dddd LT"},meridiem:function(a,b,c){return a<12?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("jp",a)}(),function(){var a={months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 mm분",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 LT",LLLL:"YYYY년 MMMM D일 dddd LT"},meridiem:function(a,b,c){return a<12?"오전":"오후"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinal:function(a){return"일"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("kr",a)}(),function(){var a={months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[I dag klokken] LT",nextDay:"[I morgen klokken] LT",nextWeek:"dddd [klokken] LT",lastDay:"[I går klokken] LT",lastWeek:"[Forrige] dddd [klokken] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nb",a)}(),function(){var a={months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._mei._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Vandaag om] LT",nextDay:"[Morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinal:function(a){return a===1||a===8||a>=20?"ste":"de"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nl",a)}(),function(){var a=function(a){return a%10<5&&a%10>1&&~~(a/10)!==1},b=function(b,c,d){var e=b+" ";switch(d){case"m":return c?"minuta":"minutę";case"mm":return e+(a(b)?"minuty":"minut");case"h":return c?"godzina":"godzinę";case"hh":return e+(a(b)?"godziny":"godzin");case"MM":return e+(a(b)?"miesiące":"miesięcy");case"yy":return e+(a(b)?"lata":"lat")}},c={months:"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"),monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:"[W zeszły/łą] dddd [o] LT",sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:b,mm:b,h:b,hh:b,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:b,y:"rok",yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pl",c)}(),function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)}(),function(){var a=[function(a){return a%10===1&&a%100!==11},function(a){return a%10>=2&&a%10<=4&&a%10%1===0&&(a%100<12||a%100>14)},function(a){return a%10===0||a%10>=5&&a%10<=9&&a%10%1===0||a%100>=11&&a%100<=14&&a%100%1===0},function(a){return!0}],b=function(b,c){var d=b.split("_"),e=Math.min(a.length,d.length),f=-1;while(++f<e)if(a[f](c))return d[f];return d[e-1]},c=function(a,c,d){var e={mm:"минута_минуты_минут_минуты",hh:"час_часа_часов_часа",dd:"день_дня_дней_дня",MM:"месяц_месяца_месяцев_месяца",yy:"год_года_лет_года"};return d==="m"?c?"минута":"минуту":a+" "+b(e[d],+a)},d={months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),weekdaysShort:"вск_пнд_втр_срд_чтв_птн_суб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return this.day()===2?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(){switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:c,mm:c,h:"час",hh:c,d:"день",dd:c,M:"месяц",MM:c,y:"год",yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=d),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ru",d)}(),function(){var a={months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"Sö_Må_Ti_On_To_Fr_Lö".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Idag klockan] LT",nextDay:"[Imorgon klockan] LT",lastDay:"[Igår klockan] LT",nextWeek:"dddd [klockan] LT",lastWeek:"[Förra] dddd[en klockan] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sen",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"e":b===1?"a":b===2?"a":b===3?"e":"e"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("sv",a)}(),function(){var a={months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("tr",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-cn",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-tw",a)}();
<ide>\ No newline at end of file
<ide><path>min/lang/it.js
<ide> // moment.js language configuration
<ide> // language : italian (it)
<ide> // author : Lorenzo : https://github.com/aliem
<del>(function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"Do_Lu_Ma_Me_Gi_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)})();
<ide>\ No newline at end of file
<add>(function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)})();
<ide>\ No newline at end of file
<ide><path>test/lang/it.js
<ide> exports["lang:it"] = {
<ide> ['M Mo MM MMMM MMM', '2 2º 02 Febbraio Feb'],
<ide> ['YYYY YY', '2010 10'],
<ide> ['D Do DD', '14 14º 14'],
<del> ['d do dddd ddd dd', '0 0º Domenica Dom Do'],
<add> ['d do dddd ddd dd', '0 0º Domenica Dom D'],
<ide> ['DDD DDDo DDDD', '45 45º 045'],
<ide> ['w wo ww', '8 8º 08'],
<ide> ['h hh', '3 03'],
<ide> exports["lang:it"] = {
<ide> "format week" : function(test) {
<ide> test.expect(7);
<ide> moment.lang('it');
<del> var expected = 'Domenica Dom Do_Lunedi Lun Lu_Martedi Mar Ma_Mercoledi Mer Me_Giovedi Gio Gi_Venerdi Ven Ve_Sabato Sab Sa'.split("_");
<add> var expected = 'Domenica Dom D_Lunedi Lun L_Martedi Mar Ma_Mercoledi Mer Me_Giovedi Gio G_Venerdi Ven V_Sabato Sab S'.split("_");
<ide> var i;
<ide> for (i = 0; i < expected.length; i++) {
<ide> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); | 4 |
Javascript | Javascript | remove incorrect statement | 02aef572a58a11776ac3e60bd4f9c9b92f96d054 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
<ide> * @name angular.mock.dump
<ide> * @description
<ide> *
<del> * *NOTE*: this is not an injectable instance, just a globally available function.
<add> * *NOTE*: This is not an injectable instance, just a globally available function.
<ide> *
<del> * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
<del> * debugging.
<del> *
<del> * This method is also available on window, where it can be used to display objects on debug
<del> * console.
<add> * Method for serializing common angular objects (scope, elements, etc..) into strings.
<add> * It is useful for logging objects to the console when debugging.
<ide> *
<ide> * @param {*} object - any object to turn into string.
<ide> * @return {string} a serialized string of the argument | 1 |
Text | Text | add changelog entry for | 3a7e321246a8d1a4058b4c0ad5205cfc141e0cfd | <ide><path>railties/CHANGELOG.md
<add>* Make `config.log_level` work with custom loggers.
<add>
<add> *Max Shytikov*
<add>
<ide> * Changed stylesheet load order in the stylesheet manifest generator.
<ide> Fixes #11639.
<ide> | 1 |
Ruby | Ruby | fix the documentation method | ed0b080cb37a420194b56a7029017ce4a1e8b408 | <ide><path>activemodel/lib/active_model/dirty.rb
<ide> module ActiveModel
<ide> # Reset the changes:
<ide> #
<ide> # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
<del> # person.reload
<add> # person.reload!
<ide> # person.previous_changes # => {}
<ide> #
<ide> # Assigning the same value leaves the attribute unchanged: | 1 |
Javascript | Javascript | expand test coverage for util.deprecate | fe8297ca92874770880e09e052c94f6ece5b2939 | <ide><path>test/parallel/test-util-deprecate-invalid-code.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const util = require('util');
<add>
<add>[1, true, false, null, {}].forEach((notString) => {
<add> common.expectsError(() => util.deprecate(() => {}, 'message', notString), {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "code" argument must be of type string'
<add> });
<add>}); | 1 |
PHP | PHP | fix bound parameters in sub-queries not working | 8a5d65cebe66deee250b887a69a8e8040254f5da | <ide><path>src/Database/QueryCompiler.php
<ide> public function compile(Query $query, ValueBinder $generator)
<ide> $this->_sqlCompiler($sql, $query, $generator),
<ide> $this->{'_' . $type . 'Parts'}
<ide> );
<add>
<add> // Propagate bound parameters from sub-queries
<add> if ($query->valueBinder() !== $generator) {
<add> foreach ($query->valueBinder()->bindings() as $binding) {
<add> $generator->bind(':' . $binding['placeholder'], $binding['value'], $binding['type']);
<add> }
<add> }
<ide> return $sql;
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testCountWithContain()
<ide> $this->assertEquals(2, $count);
<ide> }
<ide>
<add> /**
<add> * Tests that getting the count of a query with bind is correct
<add> *
<add> * @see https://github.com/cakephp/cakephp/issues/8466
<add> * @return void
<add> */
<add> public function testCountWithBind()
<add> {
<add> $table = TableRegistry::get('Articles');
<add> $query = $table
<add> ->find()
<add> ->select(['Articles.title', 'Articles.id'])
<add> ->where("Articles.title LIKE :val")
<add> ->group('Articles.id')
<add> ->bind(':val', '%Second%');
<add> $count = $query->count();
<add> $this->assertEquals(1, $count);
<add> }
<add>
<add> /**
<add> * Tests that bind in subqueries works.
<add> *
<add> * @return void
<add> */
<add> public function testSubqueryBind()
<add> {
<add> $table = TableRegistry::get('Articles');
<add> $sub = $table->find()
<add> ->select(['Articles.id'])
<add> ->where("Articles.title LIKE :val")
<add> ->bind(':val', 'Second %');
<add>
<add> $query = $table
<add> ->find()
<add> ->select(['Articles.title'])
<add> ->where(["Articles.id NOT IN" => $sub]);
<add> $result = $query->toArray();
<add> $this->assertCount(2, $result);
<add> $this->assertEquals('First Article', $result[0]->title);
<add> $this->assertEquals('Third Article', $result[1]->title);
<add> }
<add>
<ide> /**
<ide> * Test that deep containments don't generate empty entities for
<ide> * intermediary relations. | 2 |
Text | Text | fix typo on examples/pytorch/question-answering | 3db2e8f92bd768053d0e4303914772a50a6f48ff | <ide><path>examples/pytorch/question-answering/README.md
<ide> and reply to the questions asked. Then
<ide> accelerate test
<ide> ```
<ide>
<del>that will check everything is ready for training. Finally, you cna launch training with
<add>that will check everything is ready for training. Finally, you can launch training with
<ide>
<ide> ```bash
<ide> accelerate launch run_qa_no_trainer.py \
<ide> This command is the same and will work for:
<ide> - a distributed training with several GPUs (single or multi node)
<ide> - a training on TPUs
<ide>
<del>Note that this library is in alpha release so your feedback is more than welcome if you encounter any problem using it.
<ide>\ No newline at end of file
<add>Note that this library is in alpha release so your feedback is more than welcome if you encounter any problem using it. | 1 |
Ruby | Ruby | modify code to load spdx data once | ff1016b72997c3f6f33d39d48b335c08c734df24 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide>
<ide> # Check style in a single batch run up front for performance
<ide> style_results = Style.check_style_json(style_files, options) if style_files
<del>
<add> # load licenses
<add> path = File.join(File.dirname(__FILE__),"spdx.json")
<add> spdx_ids = JSON.load( File.open(File.expand_path(path)))
<ide> new_formula_problem_lines = []
<ide> audit_formulae.sort.each do |f|
<ide> only = only_cops ? ["style"] : args.only
<ide> def audit
<ide> git: git,
<ide> only: only,
<ide> except: args.except,
<add> spdx_ids: spdx_ids
<ide> }
<ide> options[:style_offenses] = style_results.file_offenses(f.path) if style_results
<ide> options[:display_cop_names] = args.display_cop_names?
<ide> def initialize(formula, options = {})
<ide> @new_formula_problems = []
<ide> @text = FormulaText.new(formula.path)
<ide> @specs = %w[stable devel head].map { |s| formula.send(s) }.compact
<add> @spdx_ids = options[:spdx_ids]
<ide> end
<ide>
<ide> def audit_style
<ide> def audit_formula_name
<ide> ].freeze
<ide>
<ide> def audit_licenses
<del> path = File.join(File.dirname(__FILE__),"spdx.json")
<del> file = File.open(File.expand_path(path))
<del> valid_licenses = JSON.load(file)
<ide> unless formula.license.nil?
<del> if valid_licenses.key?(formula.license)
<add> if @spdx_ids.key?(formula.license)
<ide> return unless @online
<ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}, false)
<ide> return if user.nil? | 1 |
Text | Text | add another example using http-server | 6f09b6546399cb9d39284fba8231aea76b9aecd5 | <ide><path>threejs/lessons/threejs-setup.md
<ide> Once you've done that type
<ide>
<ide> http-server path/to/folder/where/you/unzipped/files
<ide>
<add>Or if you're like me
<add>
<add> cd path/to/folder/where/you/unzipped/files
<add> http-server
<add>
<ide> It should print something like
<ide>
<ide> {{{image url="resources/http-server-response.png" }}} | 1 |
Javascript | Javascript | fix delete in concatenated module | 51b6e9c4d7a2555c99c7c8c30327d56fa4232a4e | <ide><path>lib/ConcatenationScope.js
<ide> class ConcatenationScope {
<ide> const exportData = ids
<ide> ? Buffer.from(JSON.stringify(ids), "utf-8").toString("hex")
<ide> : "ns";
<del> return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${asiSafeFlag}__`;
<add> // a "._" is appended to allow "delete ...", which would cause a SyntaxError in strict mode
<add> return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${asiSafeFlag}__._`;
<ide> }
<ide>
<ide> /**
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> );
<ide> const r = reference.identifier.range;
<ide> const source = info.source;
<del> source.replace(r[0], r[1] - 1, finalName);
<add> // range is extended by 2 chars to cover the appended "._"
<add> source.replace(r[0], r[1] + 1, finalName);
<ide> }
<ide> }
<ide> }
<ide><path>test/cases/scope-hoisting/delete-issue-10831/index.js
<add>import { object } from "./module";
<add>
<add>it("should allow to delete a imported property", () => {
<add> expect(object).toEqual({ property: true });
<add> delete object.property;
<add> expect(object).toEqual({});
<add>});
<ide><path>test/cases/scope-hoisting/delete-issue-10831/module.js
<add>export const object = { property: true }; | 4 |
Javascript | Javascript | update refs on remount | ebb324390785799b9e570360f86a6cf3d2646637 | <ide><path>Libraries/Renderer/implementations/ReactFabric-dev.fb.js
<ide> function updateReducer(reducer, initialArg, init) {
<ide> }
<ide>
<ide> hook.memoizedState = newState;
<del> // Don't persist the state accumulated from the render phase updates to
<add> // Don't persist the state accumlated from the render phase updates to
<ide> // the base state unless the queue is empty.
<ide> // TODO: Not sure if this is the desired semantics, but it's what we
<ide> // do for gDSFP. I can't remember why.
<ide> function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
<ide> newWorkInProgress.index = oldWorkInProgress.index;
<ide> newWorkInProgress.sibling = oldWorkInProgress.sibling;
<ide> newWorkInProgress.return = oldWorkInProgress.return;
<add> newWorkInProgress.ref = oldWorkInProgress.ref;
<ide>
<ide> // Replace the child/sibling pointers above it.
<ide> if (oldWorkInProgress === returnFiber.child) {
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> }
<ide>
<ide> if (nextDidTimeout && !prevDidTimeout) {
<del> // If this subtree is running in concurrent mode we can suspend,
<add> // If this subtreee is running in concurrent mode we can suspend,
<ide> // otherwise we won't suspend.
<ide> // TODO: This will still suspend a synchronous tree if anything
<ide> // in the concurrent tree already suspended during this render.
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if not prevDidTimeout.
<ide> if (nextDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children.
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if these values are non equal, i.e. it changed.
<ide> if (nextDidTimeout || prevDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children. In mutation mode, we also need the flag to
<ide> // *unhide* children that were previously hidden, so check if the
<ide> // is currently timed out, too.
<ide> function throwException(
<ide> sourceFiber.tag = IncompleteClassComponent;
<ide> } else {
<ide> // When we try rendering again, we should not reuse the current fiber,
<del> // since it's known to be in an inconsistent state. Use a force update to
<add> // since it's known to be in an inconsistent state. Use a force updte to
<ide> // prevent a bail out.
<ide> var update = createUpdate(Sync);
<ide> update.tag = ForceUpdate;
<ide> function scheduleUpdateOnFiber(fiber, expirationTime) {
<ide> // Flush the synchronous work now, wnless we're already working or inside
<ide> // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
<ide> // scheduleCallbackForFiber to preserve the ability to schedule a callback
<del> // without immediately flushing it. We only do this for user-initiated
<add> // without immediately flushing it. We only do this for user-initated
<ide> // updates, to preserve historical behavior of sync mode.
<ide> flushImmediateQueue();
<ide> }
<ide> function renderRoot(root, expirationTime, isSync) {
<ide> if (!isSync) {
<ide> // If we're rendering asynchronously, it's possible the error was
<ide> // caused by tearing due to a mutation during an event. Try rendering
<del> // one more time without yielding to events.
<add> // one more time without yiedling to events.
<ide> prepareFreshStack(root, expirationTime);
<ide> scheduleCallback(
<ide> ImmediatePriority,
<ide><path>Libraries/Renderer/implementations/ReactFabric-dev.js
<ide> function updateReducer(reducer, initialArg, init) {
<ide> }
<ide>
<ide> hook.memoizedState = newState;
<del> // Don't persist the state accumulated from the render phase updates to
<add> // Don't persist the state accumlated from the render phase updates to
<ide> // the base state unless the queue is empty.
<ide> // TODO: Not sure if this is the desired semantics, but it's what we
<ide> // do for gDSFP. I can't remember why.
<ide> function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
<ide> newWorkInProgress.index = oldWorkInProgress.index;
<ide> newWorkInProgress.sibling = oldWorkInProgress.sibling;
<ide> newWorkInProgress.return = oldWorkInProgress.return;
<add> newWorkInProgress.ref = oldWorkInProgress.ref;
<ide>
<ide> // Replace the child/sibling pointers above it.
<ide> if (oldWorkInProgress === returnFiber.child) {
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> }
<ide>
<ide> if (nextDidTimeout && !prevDidTimeout) {
<del> // If this subtree is running in concurrent mode we can suspend,
<add> // If this subtreee is running in concurrent mode we can suspend,
<ide> // otherwise we won't suspend.
<ide> // TODO: This will still suspend a synchronous tree if anything
<ide> // in the concurrent tree already suspended during this render.
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if not prevDidTimeout.
<ide> if (nextDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children.
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if these values are non equal, i.e. it changed.
<ide> if (nextDidTimeout || prevDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children. In mutation mode, we also need the flag to
<ide> // *unhide* children that were previously hidden, so check if the
<ide> // is currently timed out, too.
<ide> function throwException(
<ide> sourceFiber.tag = IncompleteClassComponent;
<ide> } else {
<ide> // When we try rendering again, we should not reuse the current fiber,
<del> // since it's known to be in an inconsistent state. Use a force update to
<add> // since it's known to be in an inconsistent state. Use a force updte to
<ide> // prevent a bail out.
<ide> var update = createUpdate(Sync);
<ide> update.tag = ForceUpdate;
<ide> function scheduleUpdateOnFiber(fiber, expirationTime) {
<ide> // Flush the synchronous work now, wnless we're already working or inside
<ide> // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
<ide> // scheduleCallbackForFiber to preserve the ability to schedule a callback
<del> // without immediately flushing it. We only do this for user-initiated
<add> // without immediately flushing it. We only do this for user-initated
<ide> // updates, to preserve historical behavior of sync mode.
<ide> flushImmediateQueue();
<ide> }
<ide> function renderRoot(root, expirationTime, isSync) {
<ide> if (!isSync) {
<ide> // If we're rendering asynchronously, it's possible the error was
<ide> // caused by tearing due to a mutation during an event. Try rendering
<del> // one more time without yielding to events.
<add> // one more time without yiedling to events.
<ide> prepareFreshStack(root, expirationTime);
<ide> scheduleCallback(
<ide> ImmediatePriority,
<ide><path>Libraries/Renderer/implementations/ReactNativeRenderer-dev.fb.js
<ide> function updateReducer(reducer, initialArg, init) {
<ide> }
<ide>
<ide> hook.memoizedState = newState;
<del> // Don't persist the state accumulated from the render phase updates to
<add> // Don't persist the state accumlated from the render phase updates to
<ide> // the base state unless the queue is empty.
<ide> // TODO: Not sure if this is the desired semantics, but it's what we
<ide> // do for gDSFP. I can't remember why.
<ide> function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
<ide> newWorkInProgress.index = oldWorkInProgress.index;
<ide> newWorkInProgress.sibling = oldWorkInProgress.sibling;
<ide> newWorkInProgress.return = oldWorkInProgress.return;
<add> newWorkInProgress.ref = oldWorkInProgress.ref;
<ide>
<ide> // Replace the child/sibling pointers above it.
<ide> if (oldWorkInProgress === returnFiber.child) {
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> }
<ide>
<ide> if (nextDidTimeout && !prevDidTimeout) {
<del> // If this subtree is running in concurrent mode we can suspend,
<add> // If this subtreee is running in concurrent mode we can suspend,
<ide> // otherwise we won't suspend.
<ide> // TODO: This will still suspend a synchronous tree if anything
<ide> // in the concurrent tree already suspended during this render.
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if not prevDidTimeout.
<ide> if (nextDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children.
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if these values are non equal, i.e. it changed.
<ide> if (nextDidTimeout || prevDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children. In mutation mode, we also need the flag to
<ide> // *unhide* children that were previously hidden, so check if the
<ide> // is currently timed out, too.
<ide> function throwException(
<ide> sourceFiber.tag = IncompleteClassComponent;
<ide> } else {
<ide> // When we try rendering again, we should not reuse the current fiber,
<del> // since it's known to be in an inconsistent state. Use a force update to
<add> // since it's known to be in an inconsistent state. Use a force updte to
<ide> // prevent a bail out.
<ide> var update = createUpdate(Sync);
<ide> update.tag = ForceUpdate;
<ide> function scheduleUpdateOnFiber(fiber, expirationTime) {
<ide> // Flush the synchronous work now, wnless we're already working or inside
<ide> // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
<ide> // scheduleCallbackForFiber to preserve the ability to schedule a callback
<del> // without immediately flushing it. We only do this for user-initiated
<add> // without immediately flushing it. We only do this for user-initated
<ide> // updates, to preserve historical behavior of sync mode.
<ide> flushImmediateQueue();
<ide> }
<ide> function renderRoot(root, expirationTime, isSync) {
<ide> if (!isSync) {
<ide> // If we're rendering asynchronously, it's possible the error was
<ide> // caused by tearing due to a mutation during an event. Try rendering
<del> // one more time without yielding to events.
<add> // one more time without yiedling to events.
<ide> prepareFreshStack(root, expirationTime);
<ide> scheduleCallback(
<ide> ImmediatePriority,
<ide><path>Libraries/Renderer/implementations/ReactNativeRenderer-dev.js
<ide> function updateReducer(reducer, initialArg, init) {
<ide> }
<ide>
<ide> hook.memoizedState = newState;
<del> // Don't persist the state accumulated from the render phase updates to
<add> // Don't persist the state accumlated from the render phase updates to
<ide> // the base state unless the queue is empty.
<ide> // TODO: Not sure if this is the desired semantics, but it's what we
<ide> // do for gDSFP. I can't remember why.
<ide> function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
<ide> newWorkInProgress.index = oldWorkInProgress.index;
<ide> newWorkInProgress.sibling = oldWorkInProgress.sibling;
<ide> newWorkInProgress.return = oldWorkInProgress.return;
<add> newWorkInProgress.ref = oldWorkInProgress.ref;
<ide>
<ide> // Replace the child/sibling pointers above it.
<ide> if (oldWorkInProgress === returnFiber.child) {
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> }
<ide>
<ide> if (nextDidTimeout && !prevDidTimeout) {
<del> // If this subtree is running in concurrent mode we can suspend,
<add> // If this subtreee is running in concurrent mode we can suspend,
<ide> // otherwise we won't suspend.
<ide> // TODO: This will still suspend a synchronous tree if anything
<ide> // in the concurrent tree already suspended during this render.
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if not prevDidTimeout.
<ide> if (nextDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children.
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> function completeWork(current, workInProgress, renderExpirationTime) {
<ide> // TODO: Only schedule updates if these values are non equal, i.e. it changed.
<ide> if (nextDidTimeout || prevDidTimeout) {
<ide> // If this boundary just timed out, schedule an effect to attach a
<del> // retry listener to the promise. This flag is also used to hide the
<add> // retry listener to the proimse. This flag is also used to hide the
<ide> // primary children. In mutation mode, we also need the flag to
<ide> // *unhide* children that were previously hidden, so check if the
<ide> // is currently timed out, too.
<ide> function throwException(
<ide> sourceFiber.tag = IncompleteClassComponent;
<ide> } else {
<ide> // When we try rendering again, we should not reuse the current fiber,
<del> // since it's known to be in an inconsistent state. Use a force update to
<add> // since it's known to be in an inconsistent state. Use a force updte to
<ide> // prevent a bail out.
<ide> var update = createUpdate(Sync);
<ide> update.tag = ForceUpdate;
<ide> function scheduleUpdateOnFiber(fiber, expirationTime) {
<ide> // Flush the synchronous work now, wnless we're already working or inside
<ide> // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
<ide> // scheduleCallbackForFiber to preserve the ability to schedule a callback
<del> // without immediately flushing it. We only do this for user-initiated
<add> // without immediately flushing it. We only do this for user-initated
<ide> // updates, to preserve historical behavior of sync mode.
<ide> flushImmediateQueue();
<ide> }
<ide> function renderRoot(root, expirationTime, isSync) {
<ide> if (!isSync) {
<ide> // If we're rendering asynchronously, it's possible the error was
<ide> // caused by tearing due to a mutation during an event. Try rendering
<del> // one more time without yielding to events.
<add> // one more time without yiedling to events.
<ide> prepareFreshStack(root, expirationTime);
<ide> scheduleCallback(
<ide> ImmediatePriority, | 4 |
Go | Go | fix race in os sandbox sharing | 967917c8b4082aafe1834a5f79067cb179eec383 | <ide><path>libnetwork/controller.go
<ide> type controller struct {
<ide> unWatchCh chan *endpoint
<ide> svcDb map[string]svcMap
<ide> nmap map[string]*netWatch
<add> defOsSbox osl.Sandbox
<add> sboxOnce sync.Once
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S
<ide> config: containerConfig{},
<ide> controller: c,
<ide> }
<del> // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
<del> var peerSb Sandbox
<del> c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
<del> if peerSb != nil {
<del> sb.osSbox = peerSb.(*sandbox).osSbox
<del> }
<ide>
<ide> heap.Init(&sb.endpoints)
<ide>
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S
<ide> return nil, err
<ide> }
<ide>
<del> c.Lock()
<add> if sb.config.useDefaultSandBox {
<add> c.sboxOnce.Do(func() {
<add> c.defOsSbox, err = osl.NewSandbox(sb.Key(), false)
<add> })
<add>
<add> if err != nil {
<add> c.sboxOnce = sync.Once{}
<add> return nil, fmt.Errorf("failed to create default sandbox: %v", err)
<add> }
<add>
<add> sb.osSbox = c.defOsSbox
<add> }
<add>
<ide> if sb.osSbox == nil && !sb.config.useExternalKey {
<ide> if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
<del> c.Unlock()
<ide> return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
<ide> }
<ide> }
<ide>
<add> c.Lock()
<ide> c.sandboxes[sb.id] = sb
<ide> c.Unlock()
<ide> defer func() {
<ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) Delete() error {
<ide> // likely not required any more. Drop it.
<ide> etchosts.Drop(sb.config.hostsPath)
<ide>
<del> if sb.osSbox != nil {
<add> if sb.osSbox != nil && !sb.config.useDefaultSandBox {
<ide> sb.osSbox.Destroy()
<ide> }
<ide> | 2 |
Go | Go | use fewer modprobes | 074eca1d796d0863a8c71d4707f6d8767fd19fa9 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func xfsSupported() error {
<ide> return err // error text is descriptive enough
<ide> }
<ide>
<del> // Check if kernel supports xfs filesystem or not.
<del> exec.Command("modprobe", "xfs").Run()
<add> mountTarget, err := ioutil.TempDir("", "supportsXFS")
<add> if err != nil {
<add> return errors.Wrapf(err, "error checking for xfs support")
<add> }
<add>
<add> /* The mounting will fail--after the module has been loaded.*/
<add> defer os.RemoveAll(mountTarget)
<add> unix.Mount("none", mountTarget, "xfs", 0, "")
<ide>
<ide> f, err := os.Open("/proc/filesystems")
<ide> if err != nil {
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<del> "os/exec"
<ide> "path"
<ide> "path/filepath"
<ide> "strconv"
<ide> func parseOptions(options []string) (*overlayOptions, error) {
<ide> }
<ide>
<ide> func supportsOverlay() error {
<del> // We can try to modprobe overlay first before looking at
<del> // proc/filesystems for when overlay is supported
<del> exec.Command("modprobe", "overlay").Run()
<add> // Access overlay filesystem so that Linux loads it (if possible).
<add> mountTarget, err := ioutil.TempDir("", "supportsOverlay")
<add> if err != nil {
<add> logrus.WithError(err).WithField("storage-driver", "overlay2").Error("could not create temporary directory, so assuming that 'overlay' is not supported")
<add> return graphdriver.ErrNotSupported
<add> }
<add> /* The mounting will fail--after the module has been loaded.*/
<add> defer os.RemoveAll(mountTarget)
<add> unix.Mount("overlay", mountTarget, "overlay", 0, "")
<ide>
<ide> f, err := os.Open("/proc/filesystems")
<ide> if err != nil {
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<del> "os/exec"
<ide> "path"
<ide> "path/filepath"
<ide> "strconv"
<ide> func parseOptions(options []string) (*overlayOptions, error) {
<ide> }
<ide>
<ide> func supportsOverlay() error {
<del> // We can try to modprobe overlay first before looking at
<del> // proc/filesystems for when overlay is supported
<del> exec.Command("modprobe", "overlay").Run()
<add> // Access overlay filesystem so that Linux loads it (if possible).
<add> mountTarget, err := ioutil.TempDir("", "supportsOverlay2")
<add> if err != nil {
<add> logrus.WithError(err).WithField("storage-driver", "overlay2").Error("could not create temporary directory, so assuming that 'overlay' is not supported")
<add> return graphdriver.ErrNotSupported
<add> }
<add> /* The mounting will fail--after the module has been loaded.*/
<add> defer os.RemoveAll(mountTarget)
<add> unix.Mount("overlay", mountTarget, "overlay", 0, "")
<ide>
<ide> f, err := os.Open("/proc/filesystems")
<ide> if err != nil { | 3 |
Java | Java | fix typo in behaviorsubject.java | 84736107209babc762ddd4394115afbe65a961c8 | <ide><path>src/main/java/io/reactivex/rxjava3/subjects/BehaviorSubject.java
<ide> *
<ide> * TestObserver<Integer> to1 = observable.test();
<ide> *
<del> * observable.onNext(1);
<add> * subject.onNext(1);
<ide> * // this will "clear" the cache
<del> * observable.onNext(EMPTY);
<add> * subject.onNext(EMPTY);
<ide> *
<ide> * TestObserver<Integer> to2 = observable.test();
<ide> * | 1 |
Go | Go | avoid undefined ansi escape codes | b08b437acc3bf52bd2c3435e632ed09f3312e489 | <ide><path>pkg/jsonmessage/jsonmessage.go
<ide> func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr,
<ide> if isTerminal {
<ide> fmt.Fprintf(out, "\n")
<ide> }
<del> } else {
<del> diff = len(ids) - line
<ide> }
<del> if isTerminal {
<del> // NOTE: this appears to be necessary even if
<del> // diff == 0.
<del> // <ESC>[{diff}A = move cursor up diff rows
<add> diff = len(ids) - line
<add> if isTerminal && diff > 0 {
<ide> fmt.Fprintf(out, "%c[%dA", 27, diff)
<ide> }
<ide> } else {
<ide> func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr,
<ide> ids = make(map[string]int)
<ide> }
<ide> err := jm.Display(out, isTerminal)
<del> if jm.ID != "" && isTerminal {
<del> // NOTE: this appears to be necessary even if
<del> // diff == 0.
<del> // <ESC>[{diff}B = move cursor down diff rows
<add> if jm.ID != "" && isTerminal && diff > 0 {
<ide> fmt.Fprintf(out, "%c[%dB", 27, diff)
<ide> }
<ide> if err != nil {
<ide><path>pkg/jsonmessage/jsonmessage_test.go
<ide> func TestDisplayJSONMessagesStream(t *testing.T) {
<ide> // Without progress, with ID
<ide> "{ \"id\": \"ID\",\"status\": \"status\" }": {
<ide> "ID: status\n",
<del> fmt.Sprintf("ID: status\n%c[%dB", 27, 0),
<add> fmt.Sprintf("ID: status\n"),
<ide> },
<ide> // With progress
<ide> "{ \"id\": \"ID\", \"status\": \"status\", \"progress\": \"ProgressMessage\" }": {
<ide> "ID: status ProgressMessage",
<del> fmt.Sprintf("\n%c[%dAID: status ProgressMessage%c[%dB", 27, 0, 27, 0),
<add> fmt.Sprintf("\n%c[%dAID: status ProgressMessage%c[%dB", 27, 1, 27, 1),
<ide> },
<ide> // With progressDetail
<ide> "{ \"id\": \"ID\", \"status\": \"status\", \"progressDetail\": { \"Current\": 1} }": {
<ide> "", // progressbar is disabled in non-terminal
<del> fmt.Sprintf("\n%c[%dA%c[2K\rID: status 1 B\r%c[%dB", 27, 0, 27, 27, 0),
<add> fmt.Sprintf("\n%c[%dA%c[2K\rID: status 1 B\r%c[%dB", 27, 1, 27, 27, 1),
<ide> },
<ide> }
<ide> for jsonMessage, expectedMessages := range messages { | 2 |
Javascript | Javascript | parse interpolate and imagemask for images | 47f0326eee80dfd00006bf5a4ca12ce0d81efcf4 | <ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> this.save();
<ide>
<ide> // TODO cache rendered images?
<del> var w = image.dict.get("Width");
<del> var h = image.dict.get("Height");
<add>
<add> var dict = image.dict;
<add> var w = dict.get("Width") || dict.get("W");
<add> var h = dict.get("Height") || dict.get("H");
<add>
<add> if (w < 1 || h < 1)
<add> error("Invalid image width or height");
<add>
<add> var interpolate = dict.get("Interpolate") || dict.get("I");
<add> if (!IsBool(interpolate))
<add> interpolate = false;
<add> var imageMask = dict.get("ImageMask") || dict.get("IM");
<add> if (!IsBool(imageMask))
<add> imageMask = false;
<add>
<ide> var tmpCanvas = document.createElement("canvas");
<ide> tmpCanvas.width = w;
<ide> tmpCanvas.height = h; | 1 |
Ruby | Ruby | suppress a warning on ruby 2.1+ | 61dd796f255290b24f965d885e31ae433a4811ce | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def install_symlink_p src, new_basename=src
<ide> protected :install_symlink_p
<ide>
<ide> # we assume this pathname object is a file obviously
<add> alias_method :old_write, :write if method_defined?(:write)
<ide> def write content
<ide> raise "Will not overwrite #{to_s}" if exist?
<ide> dirname.mkpath | 1 |
Javascript | Javascript | name anonymous functions in colorspace.js | 8f3448e9a8cea057b775a00678d5758bf4fe42e1 | <ide><path>src/colorspace.js
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> constructor.prototype = {
<ide> // Input: array of size numComps representing color component values
<ide> // Output: array of rgb values, each value ranging from [0.1]
<del> getRgb: function cs_getRgb(color) {
<add> getRgb: function colorSpaceGetRgb(color) {
<ide> error('Should not call ColorSpace.getRgb: ' + color);
<ide> },
<ide> // Input: Uint8Array of component values, each value scaled to [0,255]
<ide> // Output: Uint8Array of rgb values, each value scaled to [0,255]
<del> getRgbBuffer: function cs_getRgbBuffer(input) {
<add> getRgbBuffer: function colorSpaceGetRgbBuffer(input) {
<ide> error('Should not call ColorSpace.getRgbBuffer: ' + input);
<ide> }
<ide> };
<ide>
<del> constructor.parse = function colorspace_parse(cs, xref, res) {
<add> constructor.parse = function colorSpaceParse(cs, xref, res) {
<ide> var IR = constructor.parseToIR(cs, xref, res, true);
<ide> if (IR instanceof SeparationCS)
<ide> return IR;
<ide>
<ide> return constructor.fromIR(IR);
<ide> };
<ide>
<del> constructor.fromIR = function(IR) {
<add> constructor.fromIR = function colorSpaceFromIR(IR) {
<ide> var name;
<ide> if (isArray(IR)) {
<ide> name = IR[0];
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> return null;
<ide> }
<ide>
<del> constructor.parseToIR = function colorspace_parse(cs, xref, res, parseOnly) {
<add> constructor.parseToIR = function colorSpaceParseToIR(cs, xref, res,
<add> parseOnly) {
<ide> if (isName(cs)) {
<ide> var colorSpaces = xref.fetchIfRef(res.get('ColorSpace'));
<ide> if (isDict(colorSpaces)) { | 1 |
PHP | PHP | fix key handling | 84765753ee164e7b0978021c4d42711011aed340 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> protected function prepareCookiesForRequest()
<ide> }
<ide>
<ide> return collect($this->defaultCookies)->map(function ($value, $key) {
<del> return encrypt(CookieValuePrefix::create($key, base64_decode(substr(config('app.key'), 7))).$value, false);
<add> return encrypt(CookieValuePrefix::create($key, app('encrypter')->getKey()).$value, false);
<ide> })->merge($this->unencryptedCookies)->all();
<ide> }
<ide> | 1 |
Text | Text | remove changes from 1.5.4 | 0d7f1ed428f19e7f1376b8d04173f7c1641afda4 | <ide><path>CHANGELOG.md
<del><a name="1.5.4"></a>
<del># 1.5.4 graduated-sophistry (2016-04-14)
<del>
<del>
<del>## Bug Fixes
<del>
<del>- **$compile:**
<del> - do not use `noop()` as controller for multiple components
<del> ([4c8aeefb](https://github.com/angular/angular.js/commit/4c8aeefb624de7436ad95f3cd525405e0c3f493e),
<del> [#14391](https://github.com/angular/angular.js/issues/14391), [#14402](https://github.com/angular/angular.js/issues/14402))
<del> - still trigger `$onChanges` even if the inner value already matches the new value
<del> ([d9448dcb](https://github.com/angular/angular.js/commit/d9448dcb9f901ceb04deda1d5f3d5aac8442a718),
<del> [#14406](https://github.com/angular/angular.js/issues/14406))
<del> - handle boolean attributes in `@` bindings
<del> ([499e1b2a](https://github.com/angular/angular.js/commit/499e1b2adf27f32d671123f8dceadb3df2ad84a9),
<del> [#14070](https://github.com/angular/angular.js/issues/14070))
<del> - don't throw if controller is named
<del> ([e72990dc](https://github.com/angular/angular.js/commit/e72990dc3714c8b847185ddb64fd5fd00e5cceab))
<del> - ensure that `$onChanges` hook is called correctly
<del> ([0ad2b708](https://github.com/angular/angular.js/commit/0ad2b70862d49ecc4355a16d767c0ca9358ecc3e),
<del> [#14355](https://github.com/angular/angular.js/issues/14355), [#14359](https://github.com/angular/angular.js/issues/14359))
<del>- **$injector:** ensure functions with overridden `toString()` are annotated properly
<del> ([d384834f](https://github.com/angular/angular.js/commit/d384834fdee140a716298bd065f304f8fba4725e),
<del> [#14361](https://github.com/angular/angular.js/issues/14361))
<del>- **ngAnimate:**
<del> - remove event listeners only after all listeners have been called
<del> ([79604f46](https://github.com/angular/angular.js/commit/79604f462899c118a99d610995083ff82d38aa35),
<del> [#14321](https://github.com/angular/angular.js/issues/14321))
<del> - fire callbacks when document is hidden
<del> ([c7a92d2a](https://github.com/angular/angular.js/commit/c7a92d2a9a436dddd65de721c9837a93e915d939),
<del> [#14120](https://github.com/angular/angular.js/issues/14120))
<del> - fire callbacks in the correct order for certain skipped animations
<del> ([90da3059](https://github.com/angular/angular.js/commit/90da3059cecfefaecf136b01cd87aee6775a8778))
<del>- **ngClass:** fix watching of an array expression containing an object
<del> ([f975d8d4](https://github.com/angular/angular.js/commit/f975d8d4481e0b8cdba553f0e5ad9ec1688adae8),
<del> [#14405](https://github.com/angular/angular.js/issues/14405))
<del>- **ngMock:** fix collecting stack trace in `inject()` on IE10+, PhantomJS
<del> ([e9c718a4](https://github.com/angular/angular.js/commit/e9c718a465d28b9f2691e3acab944f7c31aa9fb6),
<del> [#13591](https://github.com/angular/angular.js/issues/13591), [#13592](https://github.com/angular/angular.js/issues/13592), [#13593](https://github.com/angular/angular.js/issues/13593))
<del>- **ngOptions:** set select value when model matches disabled option
<del> ([832eba5f](https://github.com/angular/angular.js/commit/832eba5fc952312e6b99127123e6e75bdf729006),
<del> [#12756](https://github.com/angular/angular.js/issues/12756))
<del>
<del>
<del>## Features
<del>
<del>- **$compile:**
<del> - put custom annotations on DDO
<del> ([f338e96c](https://github.com/angular/angular.js/commit/f338e96ccc739efc4b24022eae406c3d5451d422),
<del> [#14369](https://github.com/angular/angular.js/issues/14369), [#14279](https://github.com/angular/angular.js/issues/14279), [#14284](https://github.com/angular/angular.js/issues/14284))
<del> - add `isFirstChange()` method to onChanges object
<del> ([8d43d8b8](https://github.com/angular/angular.js/commit/8d43d8b8e7aacf97ddb9aa48bff25db57249cdd5),
<del> [#14318](https://github.com/angular/angular.js/issues/14318), [#14323](https://github.com/angular/angular.js/issues/14323))
<del>- **$componentController:** provide isolated scope if none is passed (#14425)
<del> ([33f817b9](https://github.com/angular/angular.js/commit/33f817b99cb20e566b381e7202235fe99b4a742a),
<del> [#14425](https://github.com/angular/angular.js/issues/14425))
<del>- **$http:**
<del> - support handling additional XHR events
<del> ([01b18450](https://github.com/angular/angular.js/commit/01b18450882da9bb9c903d43c0daddbc03c2c35d) and
<del> [56c861c9](https://github.com/angular/angular.js/commit/56c861c9e114c45790865e5635eaae8d32eb649a),
<del> [#14367](https://github.com/angular/angular.js/issues/14367), [#11547](https://github.com/angular/angular.js/issues/11547), [#1934](https://github.com/angular/angular.js/issues/1934))
<del>- **$parse:** add the ability to define the identifier characters
<del> ([3e7fa191](https://github.com/angular/angular.js/commit/3e7fa19197c54a764225ad27c0c0bf72263daa8d))
<del>- **ngAnimate:** let $animate.off() remove all listeners for an element
<del> ([bf6cb8ab](https://github.com/angular/angular.js/commit/bf6cb8ab0d157083a1ed55743e3fffe728daa6f3))
<del>- **ngAria:** add support for aria-readonly based on ngReadonly
<del> ([ec0baadc](https://github.com/angular/angular.js/commit/ec0baadcb68a4fa8da27d76b7e6a4e0840acd7fa),
<del> [#14140](https://github.com/angular/angular.js/issues/14140), [#14077](https://github.com/angular/angular.js/issues/14077))
<del>- **ngParseExt:** new ngParseExt module
<del> ([d08f5c69](https://github.com/angular/angular.js/commit/d08f5c698624f6243685b16f2d458cb9a980ebde))
<ide>
<ide>
<del>## Performance Improvements
<del>
<del>- **$compile:** use createMap() for directive bindings to allow fast `forEach`
<del> ([c115b37c](https://github.com/angular/angular.js/commit/c115b37c336f3a5936187279057b29c76078caf2),
<del> [#12529](https://github.com/angular/angular.js/issues/12529))
<del>- **ngOptions:** use `documentFragment` to populate `select` options
<del> ([6a4124d0](https://github.com/angular/angular.js/commit/6a4124d0fb17cd7fc0e8bf5a1ca4d785a1d11c1c),
<del> [#13607](https://github.com/angular/angular.js/issues/13607), [#13239](https://github.com/angular/angular.js/issues/13239), [#12076](https://github.com/angular/angular.js/issues/12076))
<del>
<add><a name="1.5.4"></a>
<add># 1.5.4 graduated-sophistry (2016-04-14)
<ide>
<add>This was a partially published release that you should ignore.
<ide>
<ide> <a name="1.5.3"></a>
<ide> # 1.5.3 diplohaplontic-meiosis (2016-03-25) | 1 |
Python | Python | update version to 2.0.16 | 48b1bc44d38d0cc7f94dfd43bbc1b1dad39dbbe4 | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy'
<del>__version__ = '2.0.16.dev0'
<add>__version__ = '2.0.16'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI'
<ide> __email__ = 'contact@explosion.ai'
<ide> __license__ = 'MIT'
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
<ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json' | 1 |
Text | Text | add reference to guide for n-api additions | 5cccc5545b0edfa41062497d2bd06a90dff027cd | <ide><path>COLLABORATOR_GUIDE.md
<ide> - [When Breaking Changes Actually Break Things](#when-breaking-changes-actually-break-things)
<ide> - [Reverting commits](#reverting-commits)
<ide> - [Introducing New Modules](#introducing-new-modules)
<add> - [Additions to N-API](#additions-to-n-api)
<ide> - [Deprecations](#deprecations)
<ide> - [Involving the TSC](#involving-the-tsc)
<ide> * [Landing Pull Requests](#landing-pull-requests)
<ide> For new modules that involve significant effort, non-trivial additions to
<ide> Node.js or significant new capabilities, an [Enhancement Proposal][] is
<ide> recommended but not required.
<ide>
<add>### Additions to N-API
<add>
<add>N-API provides an ABI stable API that we will have to support in future
<add>versions without the usual option to modify or remove existing APIs on
<add>SemVer boundaries. Therefore, additions need to be managed carefully.
<add>
<add>This
<add>[guide](https://github.com/nodejs/node/blob/master/doc/guides/adding-new-napi-api.md)
<add>outlines the requirements and principles that we should follow when
<add>approving and landing new N-API APIs (any additions to `node_api.h` and
<add>`node_api_types.h`).
<add>
<ide> ### Deprecations
<ide>
<ide> [_Deprecation_][] is "the discouragement of use of some … feature … or practice, | 1 |
Text | Text | remove note about es6 since node 6 is stable | 6078afcc0590e5df0511278906a73bb494f8c066 | <ide><path>docs/recipes/ServerRendering.md
<ide> function renderFullPage(html, preloadedState) {
<ide> }
<ide> ```
<ide>
<del>>##### Note on String Interpolation Syntax
<del>
<del>>In the example above, we use ES6 [template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings) syntax. It lets us write multiline strings and interpolate values, but it requires ES6 support. If you'd like to write your Node code using ES6, check out [Babel require hook](https://babeljs.io/docs/usage/require/) documentation. Or you can just keep writing ES5 code.
<del>
<ide> ## The Client Side
<ide>
<ide> The client side is very straightforward. All we need to do is grab the initial state from `window.__PRELOADED_STATE__`, and pass it to our [`createStore()`](../api/createStore.md) function as the initial state. | 1 |
Go | Go | fix handling of remote "git@" notation | 913eb99fdcd26a4106250bd40dfe8b9c18564b23 | <ide><path>builder/remotecontext/git/gitutils.go
<ide> import (
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<add>type gitRepo struct {
<add> remote string
<add> ref string
<add> subdir string
<add>}
<add>
<ide> // Clone clones a repository into a newly created directory which
<ide> // will be under "docker-build-git"
<ide> func Clone(remoteURL string) (string, error) {
<del> if !urlutil.IsGitTransport(remoteURL) {
<del> remoteURL = "https://" + remoteURL
<del> }
<del> root, err := ioutil.TempDir("", "docker-build-git")
<add> repo, err := parseRemoteURL(remoteURL)
<add>
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide>
<del> u, err := url.Parse(remoteURL)
<add> fetch := fetchArgs(repo.remote, repo.ref)
<add>
<add> root, err := ioutil.TempDir("", "docker-build-git")
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func Clone(remoteURL string) (string, error) {
<ide> return "", errors.Wrapf(err, "failed to init repo at %s: %s", root, out)
<ide> }
<ide>
<del> ref, subdir := getRefAndSubdir(u.Fragment)
<del> fetch := fetchArgs(u, ref)
<del>
<del> u.Fragment = ""
<del>
<ide> // Add origin remote for compatibility with previous implementation that
<ide> // used "git clone" and also to make sure local refs are created for branches
<del> if out, err := gitWithinDir(root, "remote", "add", "origin", u.String()); err != nil {
<del> return "", errors.Wrapf(err, "failed add origin repo at %s: %s", u.String(), out)
<add> if out, err := gitWithinDir(root, "remote", "add", "origin", repo.remote); err != nil {
<add> return "", errors.Wrapf(err, "failed add origin repo at %s: %s", repo.remote, out)
<ide> }
<ide>
<ide> if output, err := gitWithinDir(root, fetch...); err != nil {
<ide> return "", errors.Wrapf(err, "error fetching: %s", output)
<ide> }
<ide>
<del> return checkoutGit(root, ref, subdir)
<add> return checkoutGit(root, repo.ref, repo.subdir)
<add>}
<add>
<add>func parseRemoteURL(remoteURL string) (gitRepo, error) {
<add> repo := gitRepo{}
<add>
<add> if !urlutil.IsGitTransport(remoteURL) {
<add> remoteURL = "https://" + remoteURL
<add> }
<add>
<add> var fragment string
<add> if strings.HasPrefix(remoteURL, "git@") {
<add> // git@.. is not an URL, so cannot be parsed as URL
<add> parts := strings.SplitN(remoteURL, "#", 2)
<add>
<add> repo.remote = parts[0]
<add> if len(parts) == 2 {
<add> fragment = parts[1]
<add> }
<add> repo.ref, repo.subdir = getRefAndSubdir(fragment)
<add> } else {
<add> u, err := url.Parse(remoteURL)
<add> if err != nil {
<add> return repo, err
<add> }
<add>
<add> repo.ref, repo.subdir = getRefAndSubdir(u.Fragment)
<add> u.Fragment = ""
<add> repo.remote = u.String()
<add> }
<add> return repo, nil
<ide> }
<ide>
<ide> func getRefAndSubdir(fragment string) (ref string, subdir string) {
<ide> func getRefAndSubdir(fragment string) (ref string, subdir string) {
<ide> return
<ide> }
<ide>
<del>func fetchArgs(remoteURL *url.URL, ref string) []string {
<add>func fetchArgs(remoteURL string, ref string) []string {
<ide> args := []string{"fetch", "--recurse-submodules=yes"}
<ide> shallow := true
<ide>
<del> if strings.HasPrefix(remoteURL.Scheme, "http") {
<add> if urlutil.IsURL(remoteURL) {
<ide> res, err := http.Head(fmt.Sprintf("%s/info/refs?service=git-upload-pack", remoteURL))
<ide> if err != nil || res.Header.Get("Content-Type") != "application/x-git-upload-pack-advertisement" {
<ide> shallow = false
<ide><path>builder/remotecontext/git/gitutils_test.go
<ide> import (
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide>
<add>func TestParseRemoteURL(t *testing.T) {
<add> dir, err := parseRemoteURL("git://github.com/user/repo.git")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "master", ""}, dir)
<add>
<add> dir, err = parseRemoteURL("git://github.com/user/repo.git#mybranch:mydir/mysubdir/")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
<add>
<add> dir, err = parseRemoteURL("https://github.com/user/repo.git")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "master", ""}, dir)
<add>
<add> dir, err = parseRemoteURL("https://github.com/user/repo.git#mybranch:mydir/mysubdir/")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
<add>
<add> dir, err = parseRemoteURL("git@github.com:user/repo.git")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "master", ""}, dir)
<add>
<add> dir, err = parseRemoteURL("git@github.com:user/repo.git#mybranch:mydir/mysubdir/")
<add> require.NoError(t, err)
<add> assert.NotEmpty(t, dir)
<add> assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
<add>}
<add>
<ide> func TestCloneArgsSmartHttp(t *testing.T) {
<ide> mux := http.NewServeMux()
<ide> server := httptest.NewServer(mux)
<ide> func TestCloneArgsSmartHttp(t *testing.T) {
<ide> w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
<ide> })
<ide>
<del> args := fetchArgs(serverURL, "master")
<add> args := fetchArgs(serverURL.String(), "master")
<ide> exp := []string{"fetch", "--recurse-submodules=yes", "--depth", "1", "origin", "master"}
<ide> assert.Equal(t, exp, args)
<ide> }
<ide> func TestCloneArgsDumbHttp(t *testing.T) {
<ide> w.Header().Set("Content-Type", "text/plain")
<ide> })
<ide>
<del> args := fetchArgs(serverURL, "master")
<add> args := fetchArgs(serverURL.String(), "master")
<ide> exp := []string{"fetch", "--recurse-submodules=yes", "origin", "master"}
<ide> assert.Equal(t, exp, args)
<ide> }
<ide>
<ide> func TestCloneArgsGit(t *testing.T) {
<del> u, _ := url.Parse("git://github.com/docker/docker")
<del> args := fetchArgs(u, "master")
<add> args := fetchArgs("git://github.com/docker/docker", "master")
<ide> exp := []string{"fetch", "--recurse-submodules=yes", "--depth", "1", "origin", "master"}
<ide> assert.Equal(t, exp, args)
<ide> } | 2 |
Javascript | Javascript | stop pageconfig plugin from running on non-pages | 41cb3b3bc0639df06d33797725244ba8a1cf76de | <ide><path>packages/next/build/webpack/loaders/next-babel-loader.js
<ide> module.exports = babelLoader.custom(babel => {
<ide> customOptions: { isServer, asyncToPromises }
<ide> }
<ide> ) {
<add> const { cwd } = cfg.options
<ide> const filename = this.resourcePath
<ide> const options = Object.assign({}, cfg.options)
<add> const isPageFile = filename.startsWith(join(cwd, 'pages'))
<add>
<ide> if (cfg.hasFilesystemConfig()) {
<ide> for (const file of [cfg.babelrc, cfg.config]) {
<ide> // We only log for client compilation otherwise there will be double output
<ide> module.exports = babelLoader.custom(babel => {
<ide> options.presets = [...options.presets, presetItem]
<ide> }
<ide>
<del> if (!isServer) {
<add> if (!isServer && isPageFile) {
<ide> const pageConfigPlugin = babel.createConfigItem(
<ide> [require('../../babel/plugins/next-page-config')],
<ide> { type: 'plugin' }
<ide><path>test/integration/page-config/config/index.js
<add>export const config = 'world'
<ide><path>test/integration/page-config/pages/index.js
<add>import { config as hello } from '../something'
<add>import { config as world } from '../config'
<add>
<add>export default () => (
<add> <p>
<add> {hello} {world}
<add> </p>
<add>)
<ide><path>test/integration/page-config/something.js
<add>export const config = 'hello'
<ide><path>test/integration/page-config/test/index.test.js
<add>/* eslint-env jest */
<add>/* global jasmine */
<add>import { join } from 'path'
<add>import { nextBuild } from 'next-test-utils'
<add>
<add>const appDir = join(__dirname, '..')
<add>jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
<add>
<add>describe('Page Config', () => {
<add> it('builds without error when export const config is used outside page', async () => {
<add> const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
<add> expect(stderr).not.toMatch(/Failed to compile\./)
<add> })
<add>}) | 5 |
PHP | PHP | fix typo and update 2nd example comment for filter | 0bea2fb0b6eaf04133b75032ffb84f70c0fcd41d | <ide><path>application/routes.php
<ide> |
<ide> | Next, attach the filter to a route:
<ide> |
<del>| Router::register('GET /', array('before' => 'filter', function()
<add>| Route::get('/', array('before' => 'filter', function()
<ide> | {
<ide> | return 'Hello World!';
<ide> | })); | 1 |
Text | Text | add directory structure in writing-tests.md | 59b5d77b920aac08aab79df3e2d1969ba804b745 | <ide><path>doc/guides/writing-tests.md
<ide> Add tests when:
<ide> - Fixing regressions and bugs.
<ide> - Expanding test coverage.
<ide>
<add>## Test directory structure
<add>
<add>See [directory structure overview][] for outline of existing test & locations.
<add>When deciding on whether to expand an existing test file or create a new one,
<add>consider going through the files related to the subsystem.
<add>For example, look for `test-streams` when writing a test for `lib/streams.js`.
<add>
<ide> ## Test structure
<ide>
<ide> Let's analyze this basic test from the Node.js test suite:
<ide> will depend on what is being tested if this is required or not.
<ide> [all maintained branches]: https://github.com/nodejs/lts
<ide> [node.green]: http://node.green/
<ide> [test fixture]: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests
<add>[directory structure overview]: https://github.com/nodejs/node/blob/master/test/README.md#test-directories | 1 |
Javascript | Javascript | fix version number generation | b94109a244270d65bd865032117c421fc1e71227 | <ide><path>broccoli/version.js
<ide> module.exports.VERSION = (() => {
<ide>
<ide> let packageVersion = require('../package.json').version;
<ide> let sha = info.sha || '';
<del> let prefix = `${packageVersion}-${(process.env.BUILD_TYPE || info.branch)}`;
<add> let suffix = process.env.BUILD_TYPE || info.branch;
<add> let metadata = sha.slice(0, 8);
<ide>
<del> return `${prefix}+${sha.slice(0, 8)}`;
<add> return `${packageVersion}${suffix ? '-' + suffix : ''}+${metadata}`;
<ide> })(); | 1 |
Javascript | Javascript | add comment about techniques to gltf2loader | 0d40bfdac25e852acbae35306e8bda347dfb489b | <ide><path>examples/js/loaders/GLTF2Loader.js
<ide> THREE.GLTF2Loader = ( function () {
<ide>
<ide> materialType = DeferredShaderMaterial;
<ide>
<add> // I've left the existing json.techniques code as is so far though
<add> // techniques is moved to extension in glTF 2.0 because
<add> // it seems there still be many models which have techniques under json.
<add> // I'm gonna move the techniques code into GLTFTechniqueWebglExtension
<add> // when glTF 2.0 release is officially announced.
<add>
<ide> var extension = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ];
<ide>
<ide> var techniques = extension !== undefined ? extension.techniques : json.techniques; | 1 |
Go | Go | remove job from `docker kill` | 3cb751906a8a0397dcf57d8fca97c0e9c0c418e8 | <ide><path>api/server/server.go
<ide> import (
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<add> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/version"
<ide> func postContainersKill(eng *engine.Engine, version version.Version, w http.Resp
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> if err := parseForm(r); err != nil {
<add> err := parseForm(r)
<add> if err != nil {
<ide> return err
<ide> }
<del> job := eng.Job("kill", vars["name"])
<del> if sig := r.Form.Get("signal"); sig != "" {
<del> job.Args = append(job.Args, sig)
<add>
<add> var sig uint64
<add> name := vars["name"]
<add>
<add> // If we have a signal, look at it. Otherwise, do nothing
<add> if sigStr := vars["signal"]; sigStr != "" {
<add> // Check if we passed the signal as a number:
<add> // The largest legal signal is 31, so let's parse on 5 bits
<add> sig, err = strconv.ParseUint(sigStr, 10, 5)
<add> if err != nil {
<add> // The signal is not a number, treat it as a string (either like
<add> // "KILL" or like "SIGKILL")
<add> sig = uint64(signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")])
<add> }
<add>
<add> if sig == 0 {
<add> return fmt.Errorf("Invalid signal: %s", sigStr)
<add> }
<ide> }
<del> if err := job.Run(); err != nil {
<add>
<add> if err = getDaemon(eng).ContainerKill(name, sig); err != nil {
<ide> return err
<ide> }
<add>
<ide> w.WriteHeader(http.StatusNoContent)
<ide> return nil
<ide> }
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> "create": daemon.ContainerCreate,
<ide> "export": daemon.ContainerExport,
<ide> "info": daemon.CmdInfo,
<del> "kill": daemon.ContainerKill,
<ide> "logs": daemon.ContainerLogs,
<ide> "pause": daemon.ContainerPause,
<ide> "resize": daemon.ContainerResize,
<ide><path>daemon/kill.go
<ide> package daemon
<ide>
<ide> import (
<ide> "fmt"
<del> "strconv"
<del> "strings"
<ide> "syscall"
<del>
<del> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/signal"
<ide> )
<ide>
<ide> // ContainerKill send signal to the container
<ide> // If no signal is given (sig 0), then Kill with SIGKILL and wait
<ide> // for the container to exit.
<ide> // If a signal is given, then just send it to the container and return.
<del>func (daemon *Daemon) ContainerKill(job *engine.Job) error {
<del> if n := len(job.Args); n < 1 || n > 2 {
<del> return fmt.Errorf("Usage: %s CONTAINER [SIGNAL]", job.Name)
<del> }
<del> var (
<del> name = job.Args[0]
<del> sig uint64
<del> err error
<del> )
<del>
<del> // If we have a signal, look at it. Otherwise, do nothing
<del> if len(job.Args) == 2 && job.Args[1] != "" {
<del> // Check if we passed the signal as a number:
<del> // The largest legal signal is 31, so let's parse on 5 bits
<del> sig, err = strconv.ParseUint(job.Args[1], 10, 5)
<del> if err != nil {
<del> // The signal is not a number, treat it as a string (either like "KILL" or like "SIGKILL")
<del> sig = uint64(signal.SignalMap[strings.TrimPrefix(job.Args[1], "SIG")])
<del> }
<del>
<del> if sig == 0 {
<del> return fmt.Errorf("Invalid signal: %s", job.Args[1])
<del> }
<del> }
<del>
<add>func (daemon *Daemon) ContainerKill(name string, sig uint64) error {
<ide> container, err := daemon.Get(name)
<ide> if err != nil {
<ide> return err
<ide> func (daemon *Daemon) ContainerKill(job *engine.Job) error {
<ide> if err := container.Kill(); err != nil {
<ide> return fmt.Errorf("Cannot kill container %s: %s", name, err)
<ide> }
<del> container.LogEvent("kill")
<ide> } else {
<ide> // Otherwise, just send the requested signal
<ide> if err := container.KillSig(int(sig)); err != nil {
<ide> return fmt.Errorf("Cannot kill container %s: %s", name, err)
<ide> }
<del> // FIXME: Add event for signals
<ide> }
<add> container.LogEvent("kill")
<ide> return nil
<ide> }
<ide><path>integration/server_test.go
<ide> func TestRestartKillWait(t *testing.T) {
<ide> if err := job.Run(); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> job = eng.Job("kill", id)
<del> if err := job.Run(); err != nil {
<add>
<add> if err := runtime.ContainerKill(id, 0); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide><path>integration/utils_test.go
<ide> func containerWaitTimeout(eng *engine.Engine, id string, t Fataler) error {
<ide> }
<ide>
<ide> func containerKill(eng *engine.Engine, id string, t Fataler) {
<del> if err := eng.Job("kill", id).Run(); err != nil {
<add> if err := getDaemon(eng).ContainerKill(id, 0); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> } | 5 |
Text | Text | add a changelog entry for [ci skip] | 7bce826adefadfa43335eb0f19f8f1746596da97 | <ide><path>activerecord/CHANGELOG.md
<add>* Raise `ActiveRecord::RangeError` when values that executed are out of range.
<add>
<add> *Ryuta Kamizono*
<add>
<ide> * Raise `ActiveRecord::NotNullViolation` when a record cannot be inserted
<ide> or updated because it would violate a not null constraint.
<ide> | 1 |
Python | Python | add cross attentions to tfgpt2model | bd21ed4099a05f469912278d4610290d31f26b3b | <ide><path>src/transformers/models/ctrl/modeling_tf_ctrl.py
<ide> def call(
<ide> )
<ide> return outputs
<ide>
<del> # Copied from transformers.models.gpt2.modeling_tf_gpt2.TFGPT2Model.serving_output
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
<ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
<ide> def call(
<ide> attentions=transformer_outputs.attentions,
<ide> )
<ide>
<del> # Copied from transformers.models.gpt2.modeling_tf_gpt2.TFGPT2LMHeadModel.serving_output
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
<ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
<ide><path>src/transformers/models/gpt2/modeling_tf_gpt2.py
<ide>
<ide> from ...activations_tf import get_tf_activation
<ide> from ...file_utils import (
<add> DUMMY_INPUTS,
<ide> ModelOutput,
<ide> add_code_sample_docstrings,
<ide> add_start_docstrings,
<ide> add_start_docstrings_to_model_forward,
<ide> replace_return_docstrings,
<ide> )
<ide> from ...modeling_tf_outputs import (
<del> TFBaseModelOutputWithPast,
<del> TFCausalLMOutputWithPast,
<add> TFBaseModelOutputWithPastAndCrossAttentions,
<add> TFCausalLMOutputWithCrossAttentions,
<ide> TFSequenceClassifierOutputWithPast,
<ide> )
<ide> from ...modeling_tf_utils import (
<ide>
<ide>
<ide> class TFAttention(tf.keras.layers.Layer):
<del> def __init__(self, nx, config, scale=False, **kwargs):
<add> def __init__(self, nx, config, scale=False, is_cross_attention=False, **kwargs):
<ide> super().__init__(**kwargs)
<ide>
<ide> n_state = nx # in Attention: n_state=768 (nx=n_embd)
<ide> def __init__(self, nx, config, scale=False, **kwargs):
<ide> self.scale = scale
<ide> self.output_attentions = config.output_attentions
<ide>
<del> self.c_attn = TFConv1D(n_state * 3, nx, initializer_range=config.initializer_range, name="c_attn")
<add> self.is_cross_attention = is_cross_attention
<add>
<add> if self.is_cross_attention:
<add> self.c_attn = TFConv1D(n_state * 2, nx, initializer_range=config.initializer_range, name="c_attn")
<add> self.q_attn = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name="q_attn")
<add> else:
<add> self.c_attn = TFConv1D(n_state * 3, nx, initializer_range=config.initializer_range, name="c_attn")
<add>
<ide> self.c_proj = TFConv1D(n_state, nx, initializer_range=config.initializer_range, name="c_proj")
<ide> self.attn_dropout = tf.keras.layers.Dropout(config.attn_pdrop)
<ide> self.resid_dropout = tf.keras.layers.Dropout(config.resid_pdrop)
<ide> def _attn(self, q, k, v, attention_mask, head_mask, output_attentions, training=
<ide> dk = tf.cast(shape_list(k)[-1], dtype=w.dtype) # scale attention_scores
<ide> w = w / tf.math.sqrt(dk)
<ide>
<del> # w has shape [batch, heads, dst_sequence, src_sequence], where information flows from src to dst.
<del> _, _, nd, ns = shape_list(w)
<del> b = self.causal_attention_mask(nd, ns, dtype=w.dtype)
<del> b = tf.reshape(b, [1, 1, nd, ns])
<del> w = w * b - 1e4 * (1 - b)
<add> if not self.is_cross_attention:
<add> # if only "normal" attention layer implements causal mask
<add>
<add> # w has shape [batch, heads, dst_sequence, src_sequence], where information flows from src to dst.
<add> _, _, nd, ns = shape_list(w)
<add> b = self.causal_attention_mask(nd, ns, dtype=w.dtype)
<add> b = tf.reshape(b, [1, 1, nd, ns])
<add> w = w * b - 1e4 * (1 - b)
<ide>
<ide> if attention_mask is not None:
<ide> # Apply the attention mask
<ide> def split_heads(self, x):
<ide> x = tf.reshape(x, new_x_shape)
<ide> return tf.transpose(x, (0, 2, 1, 3)) # (batch, head, seq_length, head_features)
<ide>
<del> def call(self, x, layer_past, attention_mask, head_mask, use_cache, output_attentions, training=False):
<del> x = self.c_attn(x)
<del> query, key, value = tf.split(x, 3, axis=2)
<add> def call(
<add> self,
<add> x,
<add> layer_past,
<add> attention_mask,
<add> head_mask,
<add> encoder_hidden_states,
<add> encoder_attention_mask,
<add> use_cache,
<add> output_attentions,
<add> training=False,
<add> ):
<add>
<add> if encoder_hidden_states is not None:
<add> if not hasattr(self, "q_attn"):
<add> raise ValueError(
<add> "If class is used as cross attention, the weights `q_attn` have to be defined. "
<add> "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
<add> )
<add>
<add> query = self.q_attn(x)
<add> kv_out = self.c_attn(encoder_hidden_states)
<add> key, value = tf.split(kv_out, 2, axis=2)
<add> attention_mask = encoder_attention_mask
<add> else:
<add> x = self.c_attn(x)
<add> query, key, value = tf.split(x, 3, axis=2)
<add>
<ide> query = self.split_heads(query)
<ide> key = self.split_heads(key)
<ide> value = self.split_heads(value)
<ide> def __init__(self, config, scale=False, **kwargs):
<ide> self.ln_1 = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_epsilon, name="ln_1")
<ide> self.attn = TFAttention(nx, config, scale, name="attn")
<ide> self.ln_2 = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_epsilon, name="ln_2")
<add>
<add> if config.add_cross_attention:
<add>
<add> self.crossattention = TFAttention(nx, config, scale, name="crossattention", is_cross_attention=True)
<add> self.ln_cross_attn = tf.keras.layers.LayerNormalization(
<add> epsilon=config.layer_norm_epsilon, name="ln_cross_attn"
<add> )
<add>
<ide> self.mlp = TFMLP(inner_dim, config, name="mlp")
<ide>
<del> def call(self, x, layer_past, attention_mask, head_mask, use_cache, output_attentions, training=False):
<add> def call(
<add> self,
<add> x,
<add> layer_past,
<add> attention_mask,
<add> head_mask,
<add> encoder_hidden_states,
<add> encoder_attention_mask,
<add> use_cache,
<add> output_attentions,
<add> training=False,
<add> ):
<ide> a = self.ln_1(x)
<ide> output_attn = self.attn(
<del> a, layer_past, attention_mask, head_mask, use_cache, output_attentions, training=training
<add> a,
<add> layer_past=layer_past,
<add> attention_mask=attention_mask,
<add> head_mask=head_mask,
<add> encoder_hidden_states=None,
<add> encoder_attention_mask=None,
<add> use_cache=use_cache,
<add> output_attentions=output_attentions,
<add> training=training,
<ide> )
<ide> a = output_attn[0] # output_attn: a, present, (attentions)
<add> outputs = output_attn[1:]
<ide> x = x + a
<ide>
<add> # Cross-Attention Block
<add> if encoder_hidden_states is not None:
<add> # add one self-attention block for cross-attention
<add> if not hasattr(self, "crossattention"):
<add> raise ValueError(
<add> f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
<add> "cross-attention layers by setting `config.add_cross_attention=True`"
<add> )
<add>
<add> ca = self.ln_cross_attn(x)
<add> output_cross_attn = self.crossattention(
<add> ca,
<add> layer_past=None,
<add> attention_mask=attention_mask,
<add> head_mask=head_mask,
<add> encoder_hidden_states=encoder_hidden_states,
<add> encoder_attention_mask=encoder_attention_mask,
<add> use_cache=False,
<add> output_attentions=output_attentions,
<add> training=training,
<add> )
<add> ca = output_cross_attn[0] # output_attn: a, present, (cross_attentions)
<add> x = x + ca
<add> outputs = outputs + output_cross_attn[2:] # add cross attentions if we output attention weights
<add>
<ide> m = self.ln_2(x)
<ide> m = self.mlp(m, training=training)
<ide> x = x + m
<ide>
<del> outputs = [x] + output_attn[1:]
<del> return outputs # x, present, (attentions)
<add> outputs = [x] + outputs
<add> return outputs # x, present, (attentions, cross_attentions)
<ide>
<ide>
<ide> @keras_serializable
<ide> def call(
<ide> position_ids=None,
<ide> head_mask=None,
<ide> inputs_embeds=None,
<add> encoder_hidden_states=None,
<add> encoder_attention_mask=None,
<ide> use_cache=None,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<ide> def call(
<ide> position_ids=position_ids,
<ide> head_mask=head_mask,
<ide> inputs_embeds=inputs_embeds,
<add> encoder_hidden_states=encoder_hidden_states,
<add> encoder_attention_mask=encoder_attention_mask,
<ide> use_cache=use_cache,
<ide> output_attentions=output_attentions,
<ide> output_hidden_states=output_hidden_states,
<ide> def call(
<ide> tf.subtract(one_cst, inputs["attention_mask"]), tf.constant(-10000.0)
<ide> )
<ide>
<add> # Copied from `modeling_tf_t5.py` with -1e9 -> -10000
<add> if self.config.add_cross_attention and inputs["encoder_attention_mask"] is not None:
<add> # If a 2D ou 3D attention mask is provided for the cross-attention
<add> # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
<add> # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
<add> inputs["encoder_attention_mask"] = tf.cast(
<add> inputs["encoder_attention_mask"], dtype=inputs["encoder_hidden_states"].dtype
<add> )
<add> num_dims_encoder_attention_mask = len(shape_list(inputs["encoder_attention_mask"]))
<add> if num_dims_encoder_attention_mask == 3:
<add> encoder_extended_attention_mask = inputs["encoder_attention_mask"][:, None, :, :]
<add> if num_dims_encoder_attention_mask == 2:
<add> encoder_extended_attention_mask = inputs["encoder_attention_mask"][:, None, None, :]
<add>
<add> # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
<add> # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
<add> # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
<add> # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
<add>
<add> encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
<add> else:
<add> encoder_extended_attention_mask = None
<add>
<add> inputs["encoder_attention_mask"] = encoder_extended_attention_mask
<add>
<ide> # Prepare head mask if needed
<ide> # 1.0 in head_mask indicate we keep the head
<ide> # attention_probs has shape bsz x n_heads x N x N
<ide> def call(
<ide>
<ide> presents = () if inputs["use_cache"] else None
<ide> all_attentions = () if inputs["output_attentions"] else None
<add> all_cross_attentions = () if inputs["output_attentions"] and self.config.add_cross_attention else None
<ide> all_hidden_states = () if inputs["output_hidden_states"] else None
<ide> for i, (block, layer_past) in enumerate(zip(self.h, inputs["past"])):
<ide> if inputs["output_hidden_states"]:
<ide> def call(
<ide> layer_past,
<ide> inputs["attention_mask"],
<ide> inputs["head_mask"][i],
<add> inputs["encoder_hidden_states"],
<add> inputs["encoder_attention_mask"],
<ide> inputs["use_cache"],
<ide> inputs["output_attentions"],
<ide> training=inputs["training"],
<ide> def call(
<ide>
<ide> if inputs["output_attentions"]:
<ide> all_attentions = all_attentions + (outputs[2],)
<add> if self.config.add_cross_attention and encoder_hidden_states is not None:
<add> all_cross_attentions = all_cross_attentions + (outputs[3],)
<ide>
<ide> hidden_states = self.ln_f(hidden_states)
<ide>
<ide> def call(
<ide> all_attentions = tuple(tf.reshape(t, attention_output_shape) for t in all_attentions)
<ide>
<ide> if not inputs["return_dict"]:
<del> return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
<add> return tuple(
<add> v
<add> for v in [hidden_states, presents, all_hidden_states, all_attentions, all_cross_attentions]
<add> if v is not None
<add> )
<ide>
<del> return TFBaseModelOutputWithPast(
<add> return TFBaseModelOutputWithPastAndCrossAttentions(
<ide> last_hidden_state=hidden_states,
<ide> past_key_values=presents,
<ide> hidden_states=all_hidden_states,
<ide> attentions=all_attentions,
<add> cross_attentions=all_cross_attentions,
<ide> )
<ide>
<ide>
<ide> class TFGPT2PreTrainedModel(TFPreTrainedModel):
<ide> config_class = GPT2Config
<ide> base_model_prefix = "transformer"
<ide> # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
<del> _keys_to_ignore_on_load_unexpected = [r"h.\d+.attn.bias"]
<add> _keys_to_ignore_on_load_unexpected = [r"h.\d+.attn.bias", r"h.\d+.crossattention.bias"]
<add>
<add> @property
<add> def dummy_inputs(self):
<add> """
<add> Dummy inputs to build the network.
<add>
<add> Returns:
<add> :obj:`Dict[str, tf.Tensor]`: The dummy inputs.
<add> """
<add> dummy = {"input_ids": tf.constant(DUMMY_INPUTS)}
<add> # Add `encoder_hidden_states` to make the cross-attention layers' weights initialized
<add> if self.config.add_cross_attention:
<add> batch_size, seq_len = tf.constant(DUMMY_INPUTS).shape
<add> shape = (batch_size, seq_len) + (self.config.hidden_size,)
<add> h = tf.random.uniform(shape=shape)
<add> dummy["encoder_hidden_states"] = h
<add>
<add> return dummy
<ide>
<ide> @tf.function(
<ide> input_signature=[
<ide> def __init__(self, config, *inputs, **kwargs):
<ide> @add_code_sample_docstrings(
<ide> processor_class=_TOKENIZER_FOR_DOC,
<ide> checkpoint=_CHECKPOINT_FOR_DOC,
<del> output_type=TFBaseModelOutputWithPast,
<add> output_type=TFBaseModelOutputWithPastAndCrossAttentions,
<ide> config_class=_CONFIG_FOR_DOC,
<ide> )
<ide> def call(
<ide> def call(
<ide> position_ids=None,
<ide> head_mask=None,
<ide> inputs_embeds=None,
<add> encoder_hidden_states=None,
<add> encoder_attention_mask=None,
<ide> use_cache=None,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<ide> return_dict=None,
<ide> training=False,
<ide> **kwargs,
<ide> ):
<add> r"""
<add> encoder_hidden_states (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<add> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
<add> the model is configured as a decoder.
<add> encoder_attention_mask (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<add> Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
<add> the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
<add>
<add> - 1 for tokens that are **not masked**,
<add> - 0 for tokens that are **masked**.
<add>
<add> past (:obj:`Tuple[Tuple[tf.Tensor]]` of length :obj:`config.n_layers`)
<add> contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
<add> If :obj:`past` are used, the user can optionally input only the last :obj:`decoder_input_ids` (those that
<add> don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` instead of all
<add> :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
<add> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<add> If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
<add> decoding (see :obj:`past`). Set to :obj:`False` during training, :obj:`True` during generation
<add> """
<ide> inputs = input_processing(
<ide> func=self.call,
<ide> config=self.config,
<ide> def call(
<ide> position_ids=position_ids,
<ide> head_mask=head_mask,
<ide> inputs_embeds=inputs_embeds,
<add> encoder_hidden_states=encoder_hidden_states,
<add> encoder_attention_mask=encoder_attention_mask,
<ide> use_cache=use_cache,
<ide> output_attentions=output_attentions,
<ide> output_hidden_states=output_hidden_states,
<ide> def call(
<ide> position_ids=inputs["position_ids"],
<ide> head_mask=inputs["head_mask"],
<ide> inputs_embeds=inputs["inputs_embeds"],
<add> encoder_hidden_states=inputs["encoder_hidden_states"],
<add> encoder_attention_mask=inputs["encoder_attention_mask"],
<ide> use_cache=inputs["use_cache"],
<ide> output_attentions=inputs["output_attentions"],
<ide> output_hidden_states=inputs["output_hidden_states"],
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
<ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
<ide> attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
<add> cross_attns = (
<add> tf.convert_to_tensor(output.cross_attentions)
<add> if self.config.output_attentions
<add> and self.config.add_cross_attention
<add> and output.cross_attentions is not None
<add> else None
<add> )
<ide>
<del> return TFBaseModelOutputWithPast(
<del> last_hidden_state=output.last_hidden_state, past_key_values=pkv, hidden_states=hs, attentions=attns
<add> return TFBaseModelOutputWithPastAndCrossAttentions(
<add> last_hidden_state=output.last_hidden_state,
<add> past_key_values=pkv,
<add> hidden_states=hs,
<add> attentions=attns,
<add> cross_attentions=cross_attns,
<ide> )
<ide>
<ide>
<ide> def prepare_inputs_for_generation(self, inputs, past, **kwargs):
<ide> @add_code_sample_docstrings(
<ide> processor_class=_TOKENIZER_FOR_DOC,
<ide> checkpoint=_CHECKPOINT_FOR_DOC,
<del> output_type=TFCausalLMOutputWithPast,
<add> output_type=TFCausalLMOutputWithCrossAttentions,
<ide> config_class=_CONFIG_FOR_DOC,
<ide> )
<ide> def call(
<ide> def call(
<ide> position_ids=None,
<ide> head_mask=None,
<ide> inputs_embeds=None,
<add> encoder_hidden_states=None,
<add> encoder_attention_mask=None,
<ide> use_cache=None,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<ide> def call(
<ide> **kwargs,
<ide> ):
<ide> r"""
<add> encoder_hidden_states (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
<add> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
<add> the model is configured as a decoder.
<add> encoder_attention_mask (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<add> Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
<add> the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
<add>
<add> - 1 for tokens that are **not masked**,
<add> - 0 for tokens that are **masked**.
<add>
<add> past (:obj:`Tuple[Tuple[tf.Tensor]]` of length :obj:`config.n_layers`)
<add> contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
<add> If :obj:`past` are used, the user can optionally input only the last :obj:`decoder_input_ids` (those that
<add> don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` instead of all
<add> :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
<add> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<add> If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
<add> decoding (see :obj:`past`). Set to :obj:`False` during training, :obj:`True` during generation
<ide> labels (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> Labels for computing the cross entropy classification loss. Indices should be in ``[0, ...,
<ide> config.vocab_size - 1]``.
<ide> def call(
<ide> position_ids=position_ids,
<ide> head_mask=head_mask,
<ide> inputs_embeds=inputs_embeds,
<add> encoder_hidden_states=encoder_hidden_states,
<add> encoder_attention_mask=encoder_attention_mask,
<ide> use_cache=use_cache,
<ide> output_attentions=output_attentions,
<ide> output_hidden_states=output_hidden_states,
<ide> def call(
<ide> position_ids=inputs["position_ids"],
<ide> head_mask=inputs["head_mask"],
<ide> inputs_embeds=inputs["inputs_embeds"],
<add> encoder_hidden_states=inputs["encoder_hidden_states"],
<add> encoder_attention_mask=inputs["encoder_attention_mask"],
<ide> use_cache=inputs["use_cache"],
<ide> output_attentions=inputs["output_attentions"],
<ide> output_hidden_states=inputs["output_hidden_states"],
<ide> def call(
<ide> output = (logits,) + transformer_outputs[1:]
<ide> return ((loss,) + output) if loss is not None else output
<ide>
<del> return TFCausalLMOutputWithPast(
<add> return TFCausalLMOutputWithCrossAttentions(
<ide> loss=loss,
<ide> logits=logits,
<ide> past_key_values=transformer_outputs.past_key_values,
<ide> hidden_states=transformer_outputs.hidden_states,
<ide> attentions=transformer_outputs.attentions,
<add> cross_attentions=transformer_outputs.cross_attentions,
<ide> )
<ide>
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
<ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
<ide> attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
<add> cross_attns = (
<add> tf.convert_to_tensor(output.cross_attentions)
<add> if self.config.output_attentions
<add> and self.config.add_cross_attention
<add> and output.cross_attentions is not None
<add> else None
<add> )
<ide>
<del> return TFCausalLMOutputWithPast(logits=output.logits, past_key_values=pkv, hidden_states=hs, attentions=attns)
<add> return TFCausalLMOutputWithCrossAttentions(
<add> logits=output.logits, past_key_values=pkv, hidden_states=hs, attentions=attns, cross_attentions=cross_attns
<add> )
<ide>
<ide>
<ide> @add_start_docstrings(
<ide> def call(
<ide> tf.reshape(inputs["position_ids"], (-1, seq_length)) if inputs["position_ids"] is not None else None
<ide> )
<ide> transformer_outputs = self.transformer(
<del> flat_input_ids,
<del> inputs["past"],
<del> flat_attention_mask,
<del> flat_token_type_ids,
<del> flat_position_ids,
<del> inputs["head_mask"],
<del> inputs["inputs_embeds"],
<del> inputs["use_cache"],
<del> inputs["output_attentions"],
<del> inputs["output_hidden_states"],
<add> input_ids=flat_input_ids,
<add> past=inputs["past"],
<add> attention_mask=flat_attention_mask,
<add> token_type_ids=flat_token_type_ids,
<add> position_ids=flat_position_ids,
<add> head_mask=inputs["head_mask"],
<add> inputs_embeds=inputs["inputs_embeds"],
<add> encoder_hidden_states=None,
<add> encoder_attention_mask=None,
<add> use_cache=inputs["use_cache"],
<add> output_attentions=inputs["output_attentions"],
<add> output_hidden_states=inputs["output_hidden_states"],
<ide> return_dict=inputs["return_dict"],
<ide> training=inputs["training"],
<ide> )
<ide><path>tests/test_modeling_tf_encoder_decoder.py
<ide>
<ide> from .test_modeling_tf_bert import TFBertModelTester
<ide> from .test_modeling_tf_common import ids_tensor
<add>from .test_modeling_tf_gpt2 import TFGPT2ModelTester
<ide> from .test_modeling_tf_rembert import TFRemBertModelTester
<ide> from .test_modeling_tf_roberta import TFRobertaModelTester
<ide>
<ide> TFBertLMHeadModel,
<ide> TFBertModel,
<ide> TFEncoderDecoderModel,
<add> TFGPT2LMHeadModel,
<ide> TFRemBertForCausalLM,
<ide> TFRemBertModel,
<ide> TFRobertaForCausalLM,
<ide> def test_bert2bert_summarization(self):
<ide>
<ide> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
<ide>
<del> """Not working, because pt checkpoint has `encoder.encoder.layer...` while tf model has `encoder.bert.encoder.layer...`
<add> """Not working, because pt checkpoint has `encoder.encoder.layer...` while tf model has `encoder.bert.encoder.layer...`.
<ide> (For Bert decoder, there is no issue, because `BertModel` is wrapped into `decoder` as `bert`)
<ide> model = TFEncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16", from_pt=True)
<ide> """
<ide> def test_bert2bert_summarization(self):
<ide> self.assertEqual(summary, [EXPECTED_SUMMARY_STUDENTS])
<ide>
<ide>
<add>@require_tf
<add>class TFGPT2EncoderDecoderModelTest(TFEncoderDecoderMixin, unittest.TestCase):
<add> def get_pretrained_model(self):
<add> return TFEncoderDecoderModel.from_encoder_decoder_pretrained("bert-base-cased", "gpt2")
<add>
<add> def get_encoder_decoder_model(self, config, decoder_config):
<add> encoder_model = TFBertModel(config, name="encoder")
<add> decoder_model = TFGPT2LMHeadModel(decoder_config, name="decoder")
<add> return encoder_model, decoder_model
<add>
<add> def prepare_config_and_inputs(self):
<add> model_tester_encoder = TFBertModelTester(self, batch_size=13)
<add> model_tester_decoder = TFGPT2ModelTester(self)
<add> encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs()
<add> decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder()
<add> (
<add> config,
<add> input_ids,
<add> token_type_ids,
<add> attention_mask,
<add> sequence_labels,
<add> token_labels,
<add> choice_labels,
<add> ) = encoder_config_and_inputs
<add> (
<add> decoder_config,
<add> decoder_input_ids,
<add> decoder_attention_mask,
<add> decoder_head_mask,
<add> decoder_token_type_ids,
<add> decoder_sequence_labels,
<add> decoder_token_labels,
<add> decoder_choice_labels,
<add> encoder_hidden_states,
<add> encoder_attention_mask,
<add> ) = decoder_config_and_inputs
<add>
<add> # make sure that cross attention layers are added
<add> decoder_config.add_cross_attention = True
<add> # disable cache for now
<add> decoder_config.use_cache = False
<add> return {
<add> "config": config,
<add> "input_ids": input_ids,
<add> "attention_mask": attention_mask,
<add> "decoder_config": decoder_config,
<add> "decoder_input_ids": decoder_input_ids,
<add> "decoder_token_type_ids": decoder_token_type_ids,
<add> "decoder_attention_mask": decoder_attention_mask,
<add> "decoder_sequence_labels": decoder_sequence_labels,
<add> "decoder_token_labels": decoder_token_labels,
<add> "decoder_choice_labels": decoder_choice_labels,
<add> "encoder_hidden_states": encoder_hidden_states,
<add> "labels": decoder_token_labels,
<add> }
<add>
<add> @slow
<add> @is_pt_tf_cross_test
<add> def test_bert2gpt2_summarization(self):
<add>
<add> from transformers import EncoderDecoderModel
<add>
<add> tokenizer_in = AutoTokenizer.from_pretrained("bert-base-cased")
<add> tokenizer_out = AutoTokenizer.from_pretrained("gpt2")
<add>
<add> """Not working, because pt checkpoint has `encoder.encoder.layer...` while tf model has `encoder.bert.encoder.layer...`.
<add> (For GPT2 decoder, there is no issue)
<add> model = TFEncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16", from_pt=True)
<add> """
<add>
<add> # workaround to load from pt
<add> _model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16")
<add> _model.encoder.save_pretrained("./encoder")
<add> _model.decoder.save_pretrained("./decoder")
<add> model = TFEncoderDecoderModel.from_encoder_decoder_pretrained(
<add> "./encoder", "./decoder", encoder_from_pt=True, decoder_from_pt=True
<add> )
<add> model.config = _model.config
<add>
<add> ARTICLE_STUDENTS = """(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David Boren took it a step further, saying the university's affiliation with the fraternity is permanently done. The news is shocking, but it's not the first time SAE has faced controversy. SAE was founded March 9, 1856, at the University of Alabama, five years before the American Civil War, according to the fraternity website. When the war began, the group had fewer than 400 members, of which "369 went to war for the Confederate States and seven for the Union Army," the website says. The fraternity now boasts more than 200,000 living alumni, along with about 15,000 undergraduates populating 219 chapters and 20 "colonies" seeking full membership at universities. SAE has had to work hard to change recently after a string of member deaths, many blamed on the hazing of new recruits, SAE national President Bradley Cohen wrote in a message on the fraternity's website. The fraternity's website lists more than 130 chapters cited or suspended for "health and safety incidents" since 2010. At least 30 of the incidents involved hazing, and dozens more involved alcohol. However, the list is missing numerous incidents from recent months. Among them, according to various media outlets: Yale University banned the SAEs from campus activities last month after members allegedly tried to interfere with a sexual misconduct investigation connected to an initiation rite. Stanford University in December suspended SAE housing privileges after finding sorority members attending a fraternity function were subjected to graphic sexual content. And Johns Hopkins University in November suspended the fraternity for underage drinking. "The media has labeled us as the 'nation's deadliest fraternity,' " Cohen said. In 2011, for example, a student died while being coerced into excessive alcohol consumption, according to a lawsuit. SAE's previous insurer dumped the fraternity. "As a result, we are paying Lloyd's of London the highest insurance rates in the Greek-letter world," Cohen said. Universities have turned down SAE's attempts to open new chapters, and the fraternity had to close 12 in 18 months over hazing incidents."""
<add> EXPECTED_SUMMARY_STUDENTS = """SAS Alpha Epsilon suspended the students, but university president says it's permanent.\nThe fraternity has had to deal with a string of student deaths since 2010.\nSAS has more than 200,000 members, many of whom are students.\nA student died while being forced into excessive alcohol consumption."""
<add>
<add> input_dict = tokenizer_in(ARTICLE_STUDENTS, return_tensors="tf")
<add> output_ids = model.generate(input_ids=input_dict["input_ids"], max_length=None).numpy().tolist()
<add> summary = tokenizer_out.batch_decode(output_ids, skip_special_tokens=True)
<add>
<add> self.assertEqual(summary, [EXPECTED_SUMMARY_STUDENTS])
<add>
<add>
<ide> @require_tf
<ide> class TFRoBertaEncoderDecoderModelTest(TFEncoderDecoderMixin, unittest.TestCase):
<ide> def get_pretrained_model(self):
<ide><path>tests/test_modeling_tf_gpt2.py
<ide> from transformers.testing_utils import require_tf, slow
<ide>
<ide> from .test_configuration_common import ConfigTester
<del>from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
<add>from .test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
<ide>
<ide>
<ide> if is_tf_available():
<ide> def prepare_config_and_inputs(self):
<ide> choice_labels,
<ide> )
<ide>
<add> def prepare_config_and_inputs_for_decoder(self):
<add> (
<add> config,
<add> input_ids,
<add> input_mask,
<add> head_mask,
<add> token_type_ids,
<add> mc_token_ids,
<add> sequence_labels,
<add> token_labels,
<add> choice_labels,
<add> ) = self.prepare_config_and_inputs()
<add>
<add> encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
<add> encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
<add>
<add> return (
<add> config,
<add> input_ids,
<add> input_mask,
<add> head_mask,
<add> token_type_ids,
<add> sequence_labels,
<add> token_labels,
<add> choice_labels,
<add> encoder_hidden_states,
<add> encoder_attention_mask,
<add> )
<add>
<ide> def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
<ide> model = TFGPT2Model(config=config)
<ide> inputs = { | 4 |
Python | Python | fix lint - 2 | 3ca331b6d8d485311815c56f9f29d15a47dac1be | <ide><path>numpy/f2py/rules.py
<ide> 'cleanupfrompyobj': """\
<ide> \t\tSTRINGFREE(#varname#);
<ide> \t} /*if (f2py_success) of #varname#*/""",
<del> 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE', {l_not(isintent_c): 'STRINGPADN'}],
<add> 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE',
<add> {l_not(isintent_c): 'STRINGPADN'}],
<ide> '_check':isstring,
<ide> '_depend':''
<ide> }, { # Not hidden | 1 |
PHP | PHP | replace incorrect return type | 415c5adba4f6f0f944d3a6d492af4988a4335655 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function freshTimestamp()
<ide> /**
<ide> * Get a fresh timestamp for the model.
<ide> *
<del> * @return DateTime
<add> * @return string
<ide> */
<ide> public function freshTimestampString()
<ide> { | 1 |
Mixed | Javascript | move text helpers and reduce scope of imports | c667a9ef8571d179a552f6013af2cc108f1d2ac5 | <ide><path>docs/getting-started/v3-migration.md
<ide> Animation system was completely rewritten in Chart.js v3. Each property can now
<ide> * `helpers.configMerge`
<ide> * `helpers.indexOf`
<ide> * `helpers.lineTo`
<add>* `helpers.longestText` was moved to the `helpers.canvas` namespace and made private
<ide> * `helpers.max`
<add>* `helpers.measureText` was moved to the `helpers.canvas` namespace and made private
<ide> * `helpers.min`
<ide> * `helpers.nextItem`
<ide> * `helpers.numberOfLabelLines`
<ide><path>src/core/core.scale.js
<ide>
<ide> import defaults from './core.defaults';
<ide> import Element from './core.element';
<del>import helpers from '../helpers';
<add>import {_alignPixel, _measureText} from '../helpers/helpers.canvas';
<add>import {callback as call, each, extend, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core';
<add>import {_factorize, toDegrees, toRadians} from '../helpers/helpers.math';
<add>import {_parseFont, resolve, toPadding} from '../helpers/helpers.options';
<ide> import Ticks from './core.ticks';
<ide>
<del>const alignPixel = helpers.canvas._alignPixel;
<del>const isArray = helpers.isArray;
<del>const isFinite = helpers.isFinite;
<del>const isNullOrUndef = helpers.isNullOrUndef;
<del>const valueOrDefault = helpers.valueOrDefault;
<del>const resolve = helpers.options.resolve;
<del>
<ide> defaults._set('scale', {
<ide> display: true,
<ide> offset: false,
<ide> function getPixelForGridLine(scale, index, offsetGridLines) {
<ide> }
<ide>
<ide> function garbageCollect(caches, length) {
<del> helpers.each(caches, function(cache) {
<add> each(caches, function(cache) {
<ide> var gc = cache.gc;
<ide> var gcLen = gc.length / 2;
<ide> var i;
<ide> function getScaleLabelHeight(options) {
<ide> return 0;
<ide> }
<ide>
<del> const font = helpers.options._parseFont(options);
<del> const padding = helpers.options.toPadding(options.padding);
<add> const font = _parseFont(options);
<add> const padding = toPadding(options.padding);
<ide>
<ide> return font.lineHeight + padding.height;
<ide> }
<ide> function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
<ide> return Math.max(spacing, 1);
<ide> }
<ide>
<del> factors = helpers.math._factorize(evenMajorSpacing);
<add> factors = _factorize(evenMajorSpacing);
<ide> for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
<ide> factor = factors[i];
<ide> if (factor > spacing) {
<ide> class Scale extends Element {
<ide> // Any function can be extended by the scale type
<ide>
<ide> beforeUpdate() {
<del> helpers.callback(this.options.beforeUpdate, [this]);
<add> call(this.options.beforeUpdate, [this]);
<ide> }
<ide>
<ide> /**
<ide> class Scale extends Element {
<ide> // TODO: make maxWidth, maxHeight private
<ide> me.maxWidth = maxWidth;
<ide> me.maxHeight = maxHeight;
<del> me.margins = helpers.extend({
<add> me.margins = extend({
<ide> left: 0,
<ide> right: 0,
<ide> top: 0,
<ide> class Scale extends Element {
<ide> }
<ide>
<ide> afterUpdate() {
<del> helpers.callback(this.options.afterUpdate, [this]);
<add> call(this.options.afterUpdate, [this]);
<ide> }
<ide>
<ide> //
<ide>
<ide> beforeSetDimensions() {
<del> helpers.callback(this.options.beforeSetDimensions, [this]);
<add> call(this.options.beforeSetDimensions, [this]);
<ide> }
<ide> setDimensions() {
<ide> const me = this;
<ide> class Scale extends Element {
<ide> me.paddingBottom = 0;
<ide> }
<ide> afterSetDimensions() {
<del> helpers.callback(this.options.afterSetDimensions, [this]);
<add> call(this.options.afterSetDimensions, [this]);
<ide> }
<ide>
<ide> // Data limits
<ide> beforeDataLimits() {
<del> helpers.callback(this.options.beforeDataLimits, [this]);
<add> call(this.options.beforeDataLimits, [this]);
<ide> }
<ide> determineDataLimits() {}
<ide> afterDataLimits() {
<del> helpers.callback(this.options.afterDataLimits, [this]);
<add> call(this.options.afterDataLimits, [this]);
<ide> }
<ide>
<ide> //
<ide> beforeBuildTicks() {
<del> helpers.callback(this.options.beforeBuildTicks, [this]);
<add> call(this.options.beforeBuildTicks, [this]);
<ide> }
<ide> buildTicks() {}
<ide> afterBuildTicks() {
<del> helpers.callback(this.options.afterBuildTicks, [this]);
<add> call(this.options.afterBuildTicks, [this]);
<ide> }
<ide>
<ide> beforeTickToLabelConversion() {
<del> helpers.callback(this.options.beforeTickToLabelConversion, [this]);
<add> call(this.options.beforeTickToLabelConversion, [this]);
<ide> }
<ide> /**
<ide> * Convert ticks to label strings
<ide> class Scale extends Element {
<ide> let i, ilen, tick;
<ide> for (i = 0, ilen = ticks.length; i < ilen; i++) {
<ide> tick = ticks[i];
<del> tick.label = helpers.callback(tickOpts.callback, [tick.value, i, ticks], me);
<add> tick.label = call(tickOpts.callback, [tick.value, i, ticks], me);
<ide> }
<ide> }
<ide> afterTickToLabelConversion() {
<del> helpers.callback(this.options.afterTickToLabelConversion, [this]);
<add> call(this.options.afterTickToLabelConversion, [this]);
<ide> }
<ide>
<ide> //
<ide>
<ide> beforeCalculateLabelRotation() {
<del> helpers.callback(this.options.beforeCalculateLabelRotation, [this]);
<add> call(this.options.beforeCalculateLabelRotation, [this]);
<ide> }
<ide> calculateLabelRotation() {
<ide> const me = this;
<ide> class Scale extends Element {
<ide> maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
<ide> - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
<ide> maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
<del> labelRotation = helpers.math.toDegrees(Math.min(
<add> labelRotation = toDegrees(Math.min(
<ide> Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
<ide> Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
<ide> ));
<ide> class Scale extends Element {
<ide> me.labelRotation = labelRotation;
<ide> }
<ide> afterCalculateLabelRotation() {
<del> helpers.callback(this.options.afterCalculateLabelRotation, [this]);
<add> call(this.options.afterCalculateLabelRotation, [this]);
<ide> }
<ide>
<ide> //
<ide>
<ide> beforeFit() {
<del> helpers.callback(this.options.beforeFit, [this]);
<add> call(this.options.beforeFit, [this]);
<ide> }
<ide> fit() {
<ide> const me = this;
<ide> class Scale extends Element {
<ide> if (isHorizontal) {
<ide> // A horizontal axis is more constrained by the height.
<ide> const isRotated = me.labelRotation !== 0;
<del> const angleRadians = helpers.math.toRadians(me.labelRotation);
<add> const angleRadians = toRadians(me.labelRotation);
<ide> const cosRotation = Math.cos(angleRadians);
<ide> const sinRotation = Math.sin(angleRadians);
<ide>
<ide> class Scale extends Element {
<ide> }
<ide>
<ide> afterFit() {
<del> helpers.callback(this.options.afterFit, [this]);
<add> call(this.options.afterFit, [this]);
<ide> }
<ide>
<ide> // Shared Methods
<ide> class Scale extends Element {
<ide> width = height = 0;
<ide> // Undefined labels and arrays should not be measured
<ide> if (!isNullOrUndef(label) && !isArray(label)) {
<del> width = helpers.measureText(ctx, cache.data, cache.gc, width, label);
<add> width = _measureText(ctx, cache.data, cache.gc, width, label);
<ide> height = lineHeight;
<ide> } else if (isArray(label)) {
<ide> // if it is an array let's measure each element
<ide> for (j = 0, jlen = label.length; j < jlen; ++j) {
<ide> nestedLabel = label[j];
<ide> // Undefined labels and arrays should not be measured
<ide> if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
<del> width = helpers.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
<add> width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
<ide> height += lineHeight;
<ide> }
<ide> }
<ide> class Scale extends Element {
<ide> if (numMajorIndices > 0) {
<ide> let i, ilen;
<ide> const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
<del> skip(ticks, newTicks, spacing, helpers.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
<add> skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
<ide> for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
<ide> skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
<ide> }
<del> skip(ticks, newTicks, spacing, last, helpers.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
<add> skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
<ide> return newTicks;
<ide> }
<ide> skip(ticks, newTicks, spacing);
<ide> class Scale extends Element {
<ide> const optionTicks = me.options.ticks;
<ide>
<ide> // Calculate space needed by label in axis direction.
<del> const rot = helpers.math.toRadians(me.labelRotation);
<add> const rot = toRadians(me.labelRotation);
<ide> const cos = Math.abs(Math.cos(rot));
<ide> const sin = Math.abs(Math.sin(rot));
<ide>
<ide> class Scale extends Element {
<ide> const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
<ide> const axisHalfWidth = axisWidth / 2;
<ide> const alignBorderValue = function(pixel) {
<del> return alignPixel(chart, pixel, axisWidth);
<add> return _alignPixel(chart, pixel, axisWidth);
<ide> };
<ide> let borderValue, i, tick, lineValue, alignedLineValue;
<ide> let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
<ide> class Scale extends Element {
<ide> } else if (axis === 'x') {
<ide> if (position === 'center') {
<ide> borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2);
<del> } else if (helpers.isObject(position)) {
<add> } else if (isObject(position)) {
<ide> const positionAxisID = Object.keys(position)[0];
<ide> const value = position[positionAxisID];
<ide> borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
<ide> class Scale extends Element {
<ide> } else if (axis === 'y') {
<ide> if (position === 'center') {
<ide> borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
<del> } else if (helpers.isObject(position)) {
<add> } else if (isObject(position)) {
<ide> const positionAxisID = Object.keys(position)[0];
<ide> const value = position[positionAxisID];
<ide> borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
<ide> class Scale extends Element {
<ide> continue;
<ide> }
<ide>
<del> alignedLineValue = alignPixel(chart, lineValue, lineWidth);
<add> alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
<ide>
<ide> if (isHorizontal) {
<ide> tx1 = tx2 = x1 = x2 = alignedLineValue;
<ide> class Scale extends Element {
<ide> const ticks = me.ticks;
<ide> const tickPadding = optionTicks.padding;
<ide> const tl = getTickMarkLength(options.gridLines);
<del> const rotation = -helpers.math.toRadians(me.labelRotation);
<add> const rotation = -toRadians(me.labelRotation);
<ide> const items = [];
<ide> let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
<ide>
<ide> class Scale extends Element {
<ide> } else if (axis === 'x') {
<ide> if (position === 'center') {
<ide> y = ((chartArea.top + chartArea.bottom) / 2) + tl + tickPadding;
<del> } else if (helpers.isObject(position)) {
<add> } else if (isObject(position)) {
<ide> const positionAxisID = Object.keys(position)[0];
<ide> const value = position[positionAxisID];
<ide> y = me.chart.scales[positionAxisID].getPixelForValue(value) + tl + tickPadding;
<ide> class Scale extends Element {
<ide> } else if (axis === 'y') {
<ide> if (position === 'center') {
<ide> x = ((chartArea.left + chartArea.right) / 2) - tl - tickPadding;
<del> } else if (helpers.isObject(position)) {
<add> } else if (isObject(position)) {
<ide> const positionAxisID = Object.keys(position)[0];
<ide> const value = position[positionAxisID];
<ide> x = me.chart.scales[positionAxisID].getPixelForValue(value);
<ide> class Scale extends Element {
<ide> let x1, x2, y1, y2;
<ide>
<ide> if (me.isHorizontal()) {
<del> x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
<del> x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
<add> x1 = _alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
<add> x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
<ide> y1 = y2 = borderValue;
<ide> } else {
<del> y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
<del> y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
<add> y1 = _alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
<add> y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
<ide> x1 = x2 = borderValue;
<ide> }
<ide>
<ide> class Scale extends Element {
<ide> }
<ide>
<ide> const scaleLabelFontColor = valueOrDefault(scaleLabel.fontColor, defaults.fontColor);
<del> const scaleLabelFont = helpers.options._parseFont(scaleLabel);
<del> const scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
<add> const scaleLabelFont = _parseFont(scaleLabel);
<add> const scaleLabelPadding = toPadding(scaleLabel.padding);
<ide> const halfLineHeight = scaleLabelFont.lineHeight / 2;
<ide> const scaleLabelAlign = scaleLabel.align;
<ide> const position = options.position;
<ide> class Scale extends Element {
<ide> tick: me.ticks[index],
<ide> index: index
<ide> };
<del> return helpers.extend(helpers.options._parseFont({
<add> return extend(_parseFont({
<ide> fontFamily: resolve([options.fontFamily], context),
<ide> fontSize: resolve([options.fontSize], context),
<ide> fontStyle: resolve([options.fontStyle], context),
<ide><path>src/core/core.ticks.js
<ide> 'use strict';
<ide>
<del>import helpers from '../helpers';
<del>const math = helpers.math;
<add>import {isArray} from '../helpers/helpers.core';
<add>import {log10} from '../helpers/helpers.math';
<ide>
<ide> /**
<ide> * Namespace to hold static tick generation functions
<ide> export default {
<ide> * @return {string|string[]} the label to display
<ide> */
<ide> values: function(value) {
<del> return helpers.isArray(value) ? value : '' + value;
<add> return isArray(value) ? value : '' + value;
<ide> },
<ide>
<ide> /**
<ide> * Formatter for linear numeric ticks
<ide> * @method Chart.Ticks.formatters.linear
<ide> * @param tickValue {number} the value to be formatted
<ide> * @param index {number} the position of the tickValue parameter in the ticks array
<del> * @param ticks {number[]} the list of ticks being converted
<add> * @param ticks {object[]} the list of ticks being converted
<ide> * @return {string} string representation of the tickValue parameter
<ide> */
<ide> linear: function(tickValue, index, ticks) {
<ide> export default {
<ide> }
<ide> }
<ide>
<del> var logDelta = math.log10(Math.abs(delta));
<add> var logDelta = log10(Math.abs(delta));
<ide> var tickString = '';
<ide>
<ide> if (tickValue !== 0) {
<ide> var maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
<ide> if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
<del> var logTick = math.log10(Math.abs(tickValue));
<add> var logTick = log10(Math.abs(tickValue));
<ide> var numExponential = Math.floor(logTick) - Math.floor(logDelta);
<ide> numExponential = Math.max(Math.min(numExponential, 20), 0);
<ide> tickString = tickValue.toExponential(numExponential);
<ide><path>src/helpers/helpers.canvas.js
<ide> 'use strict';
<ide>
<add>import {isArray} from './helpers.core';
<add>
<ide> const PI = Math.PI;
<ide> const RAD_PER_DEG = PI / 180;
<ide> const DOUBLE_PI = PI * 2;
<ide> const TWO_THIRDS_PI = PI * 2 / 3;
<ide> /**
<ide> * @namespace Chart.helpers.canvas
<ide> */
<add>
<add>/**
<add> * @private
<add> */
<add>export function _measureText(ctx, data, gc, longest, string) {
<add> let textWidth = data[string];
<add> if (!textWidth) {
<add> textWidth = data[string] = ctx.measureText(string).width;
<add> gc.push(string);
<add> }
<add> if (textWidth > longest) {
<add> longest = textWidth;
<add> }
<add> return longest;
<add>}
<add>
<add>/**
<add> * @private
<add> */
<add>export function _longestText(ctx, font, arrayOfThings, cache) {
<add> cache = cache || {};
<add> var data = cache.data = cache.data || {};
<add> var gc = cache.garbageCollect = cache.garbageCollect || [];
<add>
<add> if (cache.font !== font) {
<add> data = cache.data = {};
<add> gc = cache.garbageCollect = [];
<add> cache.font = font;
<add> }
<add>
<add> ctx.font = font;
<add> var longest = 0;
<add> var ilen = arrayOfThings.length;
<add> var i, j, jlen, thing, nestedThing;
<add> for (i = 0; i < ilen; i++) {
<add> thing = arrayOfThings[i];
<add>
<add> // Undefined strings and arrays should not be measured
<add> if (thing !== undefined && thing !== null && isArray(thing) !== true) {
<add> longest = _measureText(ctx, data, gc, longest, thing);
<add> } else if (isArray(thing)) {
<add> // if it is an array lets measure each element
<add> // to do maybe simplify this function a bit so we can do this more recursively?
<add> for (j = 0, jlen = thing.length; j < jlen; j++) {
<add> nestedThing = thing[j];
<add> // Undefined strings and arrays should not be measured
<add> if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
<add> longest = _measureText(ctx, data, gc, longest, nestedThing);
<add> }
<add> }
<add> }
<add> }
<add>
<add> var gcLen = gc.length / 2;
<add> if (gcLen > arrayOfThings.length) {
<add> for (i = 0; i < gcLen; i++) {
<add> delete data[gc[i]];
<add> }
<add> gc.splice(0, gcLen);
<add> }
<add> return longest;
<add>}
<add>
<ide> /**
<ide> * Returns the aligned pixel value to avoid anti-aliasing blur
<ide> * @param {Chart} chart - The chart instance.
<ide><path>src/helpers/index.js
<ide> const colorHelper = !color ?
<ide> return color(value);
<ide> };
<ide>
<del>function measureText(ctx, data, gc, longest, string) {
<del> var textWidth = data[string];
<del> if (!textWidth) {
<del> textWidth = data[string] = ctx.measureText(string).width;
<del> gc.push(string);
<del> }
<del> if (textWidth > longest) {
<del> longest = textWidth;
<del> }
<del> return longest;
<del>}
<del>
<ide> export default {
<ide> ...coreHelpers,
<ide> canvas,
<ide> export default {
<ide> fontString: function(pixelSize, fontStyle, fontFamily) {
<ide> return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
<ide> },
<del> longestText: function(ctx, font, arrayOfThings, cache) {
<del> cache = cache || {};
<del> var data = cache.data = cache.data || {};
<del> var gc = cache.garbageCollect = cache.garbageCollect || [];
<del>
<del> if (cache.font !== font) {
<del> data = cache.data = {};
<del> gc = cache.garbageCollect = [];
<del> cache.font = font;
<del> }
<del>
<del> ctx.font = font;
<del> var longest = 0;
<del> var ilen = arrayOfThings.length;
<del> var i, j, jlen, thing, nestedThing;
<del> for (i = 0; i < ilen; i++) {
<del> thing = arrayOfThings[i];
<del>
<del> // Undefined strings and arrays should not be measured
<del> if (thing !== undefined && thing !== null && coreHelpers.isArray(thing) !== true) {
<del> longest = measureText(ctx, data, gc, longest, thing);
<del> } else if (coreHelpers.isArray(thing)) {
<del> // if it is an array lets measure each element
<del> // to do maybe simplify this function a bit so we can do this more recursively?
<del> for (j = 0, jlen = thing.length; j < jlen; j++) {
<del> nestedThing = thing[j];
<del> // Undefined strings and arrays should not be measured
<del> if (nestedThing !== undefined && nestedThing !== null && !coreHelpers.isArray(nestedThing)) {
<del> longest = measureText(ctx, data, gc, longest, nestedThing);
<del> }
<del> }
<del> }
<del> }
<del>
<del> var gcLen = gc.length / 2;
<del> if (gcLen > arrayOfThings.length) {
<del> for (i = 0; i < gcLen; i++) {
<del> delete data[gc[i]];
<del> }
<del> gc.splice(0, gcLen);
<del> }
<del> return longest;
<del> },
<del> measureText,
<ide> color: colorHelper,
<ide> getHoverColor: function(colorValue) {
<ide> return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
<ide><path>src/scales/scale.radialLinear.js
<ide>
<ide> import defaults from '../core/core.defaults';
<ide> import helpers from '../helpers/index';
<add>import {_longestText} from '../helpers/helpers.canvas';
<ide> import {isNumber, toDegrees, toRadians, _normalizeAngle} from '../helpers/helpers.math';
<ide> import LinearScaleBase from './scale.linearbase';
<ide> import Ticks from '../core/core.ticks';
<ide> function getTickBackdropHeight(opts) {
<ide> function measureLabelSize(ctx, lineHeight, label) {
<ide> if (helpers.isArray(label)) {
<ide> return {
<del> w: helpers.longestText(ctx, ctx.font, label),
<add> w: _longestText(ctx, ctx.font, label),
<ide> h: label.length * lineHeight
<ide> };
<ide> }
<ide><path>test/specs/core.helpers.tests.js
<ide> describe('Core helper tests', function() {
<ide> expect(helpers.uid()).toBe(uid + 3);
<ide> });
<ide>
<del> it('should return the width of the longest text in an Array and 2D Array', function() {
<del> var context = window.createMockContext();
<del> var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
<del> var arrayOfThings1D = ['FooBar', 'Bar'];
<del> var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
<del>
<del>
<del> // Regardless 'FooBar' is the longest label it should return (characters * 10)
<del> expect(helpers.longestText(context, font, arrayOfThings1D, {})).toEqual(60);
<del> expect(helpers.longestText(context, font, arrayOfThings2D, {})).toEqual(80);
<del> // We check to make sure we made the right calls to the canvas.
<del> expect(context.getCalls()).toEqual([{
<del> name: 'measureText',
<del> args: ['FooBar']
<del> }, {
<del> name: 'measureText',
<del> args: ['Bar']
<del> }, {
<del> name: 'measureText',
<del> args: ['FooBar_1']
<del> }, {
<del> name: 'measureText',
<del> args: ['Bar_2']
<del> }, {
<del> name: 'measureText',
<del> args: ['Foo_1']
<del> }]);
<del> });
<del>
<del> it('compare text with current longest and update', function() {
<del> var context = window.createMockContext();
<del> var data = {};
<del> var gc = [];
<del> var longest = 70;
<del>
<del> expect(helpers.measureText(context, data, gc, longest, 'foobar')).toEqual(70);
<del> expect(helpers.measureText(context, data, gc, longest, 'foobar_')).toEqual(70);
<del> expect(helpers.measureText(context, data, gc, longest, 'foobar_1')).toEqual(80);
<del> // We check to make sure we made the right calls to the canvas.
<del> expect(context.getCalls()).toEqual([{
<del> name: 'measureText',
<del> args: ['foobar']
<del> }, {
<del> name: 'measureText',
<del> args: ['foobar_']
<del> }, {
<del> name: 'measureText',
<del> args: ['foobar_1']
<del> }]);
<del> });
<del>
<ide> describe('Color helper', function() {
<ide> function isColorInstance(obj) {
<ide> return typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, 'values') && Object.prototype.hasOwnProperty.call(obj.values, 'rgb');
<ide><path>test/specs/helpers.canvas.tests.js
<ide> describe('Chart.helpers.canvas', function() {
<ide> expect(isPointInArea({x: 0, y: 256.5}, area)).toBe(false);
<ide> });
<ide> });
<add>
<add> it('should return the width of the longest text in an Array and 2D Array', function() {
<add> var context = window.createMockContext();
<add> var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
<add> var arrayOfThings1D = ['FooBar', 'Bar'];
<add> var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
<add>
<add>
<add> // Regardless 'FooBar' is the longest label it should return (characters * 10)
<add> expect(helpers.canvas._longestText(context, font, arrayOfThings1D, {})).toEqual(60);
<add> expect(helpers.canvas._longestText(context, font, arrayOfThings2D, {})).toEqual(80);
<add> // We check to make sure we made the right calls to the canvas.
<add> expect(context.getCalls()).toEqual([{
<add> name: 'measureText',
<add> args: ['FooBar']
<add> }, {
<add> name: 'measureText',
<add> args: ['Bar']
<add> }, {
<add> name: 'measureText',
<add> args: ['FooBar_1']
<add> }, {
<add> name: 'measureText',
<add> args: ['Bar_2']
<add> }, {
<add> name: 'measureText',
<add> args: ['Foo_1']
<add> }]);
<add> });
<add>
<add> it('compare text with current longest and update', function() {
<add> var context = window.createMockContext();
<add> var data = {};
<add> var gc = [];
<add> var longest = 70;
<add>
<add> expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar')).toEqual(70);
<add> expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar_')).toEqual(70);
<add> expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar_1')).toEqual(80);
<add> // We check to make sure we made the right calls to the canvas.
<add> expect(context.getCalls()).toEqual([{
<add> name: 'measureText',
<add> args: ['foobar']
<add> }, {
<add> name: 'measureText',
<add> args: ['foobar_']
<add> }, {
<add> name: 'measureText',
<add> args: ['foobar_1']
<add> }]);
<add> });
<ide> }); | 8 |
Javascript | Javascript | update geteventkey tests to use public api | 51c101fc48088b9c1a379fbec41ffaebf3212972 | <ide><path>packages/react-dom/src/events/__tests__/getEventKey-test.js
<ide>
<ide> 'use strict';
<ide>
<del>// TODO: can we express this test with only public API?
<del>var getEventKey = require('../getEventKey').default;
<del>
<ide> describe('getEventKey', () => {
<add> var React;
<add> var ReactDOM;
<add>
<add> beforeEach(() => {
<add> React = require('react');
<add> ReactDOM = require('react-dom');
<add> });
<add>
<ide> describe('when key is implemented in a browser', () => {
<ide> describe('when key is not normalized', () => {
<ide> it('returns a normalized value', () => {
<del> var nativeEvent = new KeyboardEvent('keypress', {key: 'Del'});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('Delete');
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyDown={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keydown', {
<add> key: 'Del',
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('Delete');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide>
<ide> describe('when key is normalized', () => {
<ide> it('returns a key', () => {
<del> var nativeEvent = new KeyboardEvent('keypress', {key: 'f'});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('f');
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyDown={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keydown', {
<add> key: 'f',
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('f');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide> });
<ide>
<ide> describe('when key is not implemented in a browser', () => {
<ide> describe('when event type is keypress', () => {
<ide> describe('when charCode is 13', () => {
<del> it("returns 'Enter'", () => {
<del> var nativeEvent = new KeyboardEvent('keypress', {charCode: 13});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('Enter');
<add> it('returns "Enter"', () => {
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyPress={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keypress', {
<add> charCode: 13,
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('Enter');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide>
<ide> describe('when charCode is not 13', () => {
<ide> it('returns a string from a charCode', () => {
<del> var nativeEvent = new KeyboardEvent('keypress', {charCode: 65});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('A');
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyPress={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keypress', {
<add> charCode: 65,
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('A');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide> });
<ide>
<ide> describe('when event type is keydown or keyup', () => {
<ide> describe('when keyCode is recognized', () => {
<ide> it('returns a translated key', () => {
<del> var nativeEvent = new KeyboardEvent('keydown', {keyCode: 45});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('Insert');
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyDown={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keydown', {
<add> keyCode: 45,
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('Insert');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide>
<ide> describe('when keyCode is not recognized', () => {
<ide> it('returns Unidentified', () => {
<del> var nativeEvent = new KeyboardEvent('keydown', {keyCode: 1337});
<del>
<del> expect(getEventKey(nativeEvent)).toBe('Unidentified');
<add> let key = null;
<add> class Comp extends React.Component {
<add> render() {
<add> return <input onKeyDown={e => (key = e.key)} />;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Comp />, container);
<add> document.body.appendChild(container);
<add>
<add> var nativeEvent = new KeyboardEvent('keydown', {
<add> keyCode: 1337,
<add> bubbles: true,
<add> cancelable: true,
<add> });
<add> container.firstChild.dispatchEvent(nativeEvent);
<add> expect(key).toBe('Unidentified');
<add> document.body.removeChild(container);
<ide> });
<ide> });
<ide> });
<del>
<del> describe('when event type is unknown', () => {
<del> it('returns an empty string', () => {
<del> var nativeEvent = new KeyboardEvent('keysmack');
<del>
<del> expect(getEventKey(nativeEvent)).toBe('');
<del> });
<del> });
<ide> });
<ide> });
<ide><path>packages/react-dom/src/events/getEventKey.js
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<ide> */
<ide>
<ide> import getEventCharCode from './getEventCharCode';
<ide> var normalizeKey = {
<ide> * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
<ide> */
<ide> var translateToKey = {
<del> 8: 'Backspace',
<del> 9: 'Tab',
<del> 12: 'Clear',
<del> 13: 'Enter',
<del> 16: 'Shift',
<del> 17: 'Control',
<del> 18: 'Alt',
<del> 19: 'Pause',
<del> 20: 'CapsLock',
<del> 27: 'Escape',
<del> 32: ' ',
<del> 33: 'PageUp',
<del> 34: 'PageDown',
<del> 35: 'End',
<del> 36: 'Home',
<del> 37: 'ArrowLeft',
<del> 38: 'ArrowUp',
<del> 39: 'ArrowRight',
<del> 40: 'ArrowDown',
<del> 45: 'Insert',
<del> 46: 'Delete',
<del> 112: 'F1',
<del> 113: 'F2',
<del> 114: 'F3',
<del> 115: 'F4',
<del> 116: 'F5',
<del> 117: 'F6',
<del> 118: 'F7',
<del> 119: 'F8',
<del> 120: 'F9',
<del> 121: 'F10',
<del> 122: 'F11',
<del> 123: 'F12',
<del> 144: 'NumLock',
<del> 145: 'ScrollLock',
<del> 224: 'Meta',
<add> '8': 'Backspace',
<add> '9': 'Tab',
<add> '12': 'Clear',
<add> '13': 'Enter',
<add> '16': 'Shift',
<add> '17': 'Control',
<add> '18': 'Alt',
<add> '19': 'Pause',
<add> '20': 'CapsLock',
<add> '27': 'Escape',
<add> '32': ' ',
<add> '33': 'PageUp',
<add> '34': 'PageDown',
<add> '35': 'End',
<add> '36': 'Home',
<add> '37': 'ArrowLeft',
<add> '38': 'ArrowUp',
<add> '39': 'ArrowRight',
<add> '40': 'ArrowDown',
<add> '45': 'Insert',
<add> '46': 'Delete',
<add> '112': 'F1',
<add> '113': 'F2',
<add> '114': 'F3',
<add> '115': 'F4',
<add> '116': 'F5',
<add> '117': 'F6',
<add> '118': 'F7',
<add> '119': 'F8',
<add> '120': 'F9',
<add> '121': 'F10',
<add> '122': 'F11',
<add> '123': 'F12',
<add> '144': 'NumLock',
<add> '145': 'ScrollLock',
<add> '224': 'Meta',
<ide> };
<ide>
<ide> /**
<ide> * @param {object} nativeEvent Native browser event.
<ide> * @return {string} Normalized `key` property.
<ide> */
<del>function getEventKey(nativeEvent) {
<add>function getEventKey(nativeEvent: KeyboardEvent): string {
<ide> if (nativeEvent.key) {
<ide> // Normalize inconsistent values reported by browsers due to
<ide> // implementations of a working draft specification. | 2 |
Ruby | Ruby | show homebrew ruby for all system (#492) | fe3915237ef0c530ce1260cf7d2d0ca0d9d0eed1 | <ide><path>Library/Homebrew/extend/os/mac/system_config.rb
<ide> def describe_xquartz
<ide> "#{MacOS::XQuartz.version} => #{describe_path(MacOS::XQuartz.prefix)}"
<ide> end
<ide>
<del> def describe_system_ruby
<del> s = ""
<del> case RUBY_VERSION
<del> when /^1\.[89]/, /^2\.0/
<del> s << "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
<del> else
<del> s << RUBY_VERSION
<del> end
<add> def describe_homebrew_ruby
<add> s = describe_homebrew_ruby_version
<ide>
<ide> if RUBY_PATH.to_s !~ %r{^/System/Library/Frameworks/Ruby.framework/Versions/[12]\.[089]/usr/bin/ruby}
<ide> s << " => #{RUBY_PATH}"
<ide> def describe_system_ruby
<ide>
<ide> def dump_verbose_config(f = $stdout)
<ide> dump_generic_verbose_config(f)
<del> f.puts "System Ruby: #{describe_system_ruby}"
<ide> f.puts "OS X: #{MacOS.full_version}-#{kernel}"
<ide> f.puts "Xcode: #{xcode ? xcode : "N/A"}"
<ide> f.puts "CLT: #{clt ? clt : "N/A"}"
<ide><path>Library/Homebrew/system_config.rb
<ide> def describe_ruby
<ide> end
<ide> end
<ide>
<add> def describe_homebrew_ruby_version
<add> case RUBY_VERSION
<add> when /^1\.[89]/, /^2\.0/
<add> "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
<add> else
<add> RUBY_VERSION
<add> end
<add> end
<add>
<add> def describe_homebrew_ruby
<add> "#{describe_homebrew_ruby_version} => #{RUBY_PATH}"
<add> end
<add>
<ide> def hardware
<ide> return if Hardware::CPU.type == :dunno
<ide> "CPU: #{Hardware.cores_as_words}-core #{Hardware::CPU.bits}-bit #{Hardware::CPU.family}"
<ide> def dump_verbose_config(f = $stdout)
<ide> f.puts "HOMEBREW_CELLAR: #{HOMEBREW_CELLAR}"
<ide> f.puts "HOMEBREW_BOTTLE_DOMAIN: #{BottleSpecification::DEFAULT_DOMAIN}"
<ide> f.puts hardware if hardware
<add> f.puts "Homebrew Ruby: #{describe_homebrew_ruby}"
<ide> f.puts "GCC-4.0: build #{gcc_40}" if gcc_40
<ide> f.puts "GCC-4.2: build #{gcc_42}" if gcc_42
<ide> f.puts "Clang: #{clang ? "#{clang} build #{clang_build}" : "N/A"}" | 2 |
Go | Go | remove redundant log in pkg/pidfile/pidfile.go | 60e5c273cfde9fac1ac09ebcc666977232115f65 | <ide><path>pkg/pidfile/pidfile.go
<ide> package pidfile
<ide> import (
<ide> "fmt"
<ide> "io/ioutil"
<del> "log"
<ide> "os"
<ide> "path/filepath"
<ide> "strconv"
<ide> func New(path string) (*PidFile, error) {
<ide>
<ide> func (file PidFile) Remove() error {
<ide> if err := os.Remove(file.path); err != nil {
<del> log.Printf("Error removing %s: %s", file.path, err)
<ide> return err
<ide> }
<ide> return nil | 1 |
PHP | PHP | use str method rather than helper | c26b755d2794fe9f7a8a76ffae620b852394382e | <ide><path>src/Illuminate/Database/QueryException.php
<ide> namespace Illuminate\Database;
<ide>
<ide> use PDOException;
<add>use Illuminate\Support\Str;
<ide>
<ide> class QueryException extends PDOException
<ide> {
<ide> public function __construct($sql, array $bindings, $previous)
<ide> */
<ide> protected function formatMessage($sql, $bindings, $previous)
<ide> {
<del> return $previous->getMessage().' (SQL: '.str_replace_array('?', $bindings, $sql).')';
<add> return $previous->getMessage().' (SQL: '.Str::replaceArray('?', $bindings, $sql).')';
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | remove undocumented magic features for iis | fe809cd85d9281018036f4e0a3bb5329d8a51f4d | <ide><path>lib/Cake/basics.php
<ide> function env($key) {
<ide> }
<ide>
<ide> switch ($key) {
<del> case 'SCRIPT_FILENAME':
<del> if (defined('SERVER_IIS') && SERVER_IIS === true) {
<del> return str_replace('\\\\', '\\', env('PATH_TRANSLATED'));
<del> }
<del> break;
<ide> case 'DOCUMENT_ROOT':
<ide> $name = env('SCRIPT_NAME');
<ide> $filename = env('SCRIPT_FILENAME'); | 1 |
Mixed | Ruby | fix some typos | ea5daeb2e407d004cf134d47fe8ac28d24fb0a00 | <ide><path>activesupport/lib/active_support/notifications/instrumenter.rb
<ide>
<ide> module ActiveSupport
<ide> module Notifications
<del> # Instrumentors are stored in a thread local.
<add> # Instrumenters are stored in a thread local.
<ide> class Instrumenter
<ide> attr_reader :id
<ide>
<ide><path>guides/source/active_support_instrumentation.md
<ide> ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*a
<ide> end
<ide> ```
<ide>
<del>Most times you only care about the data itself. Here is a shortuct to just get the data.
<add>Most times you only care about the data itself. Here is a shortcut to just get the data.
<ide>
<ide> ```ruby
<ide> ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args| | 2 |
Mixed | Javascript | enable arbitrary rotation of datapoints | 0ddd0ee16b98bad17756a6b98b2460a04fac9056 | <ide><path>docs/charts/bubble.md
<ide> The bubble chart allows a number of properties to be specified for each dataset.
<ide> | [`hitRadius`](#interactions) | `Number` | Yes | Yes | `1`
<ide> | [`label`](#labeling) | `String` | - | - | `undefined`
<ide> | [`pointStyle`](#styling) | `String` | Yes | Yes | `circle`
<add>| [`rotation`](#styling) | `Number` | Yes | Yes | `0`
<ide> | [`radius`](#styling) | `Number` | Yes | Yes | `3`
<ide>
<ide> ### Labeling
<ide> The style of each bubble can be controlled with the following properties:
<ide> | `borderColor` | bubble border color
<ide> | `borderWidth` | bubble border width (in pixels)
<ide> | `pointStyle` | bubble [shape style](../configuration/elements#point-styles)
<add>| `rotation` | bubble rotation (in degrees)
<ide> | `radius` | bubble radius (in pixels)
<ide>
<ide> All these values, if `undefined`, fallback to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
<ide><path>docs/charts/line.md
<ide> All point* properties can be specified as an array. If these are set to an array
<ide> | `pointBorderWidth` | `Number/Number[]` | The width of the point border in pixels.
<ide> | `pointRadius` | `Number/Number[]` | The radius of the point shape. If set to 0, the point is not rendered.
<ide> | `pointStyle` | `String/String[]/Image/Image[]` | Style of the point. [more...](../configuration/elements#point-styles)
<add>| `pointRotation` | `Number/Number[]` | The rotation of the point in degrees.
<ide> | `pointHitRadius` | `Number/Number[]` | The pixel size of the non-displayed point that reacts to mouse events.
<ide> | `pointHoverBackgroundColor` | `Color/Color[]` | Point background color when hovered.
<ide> | `pointHoverBorderColor` | `Color/Color[]` | Point border color when hovered.
<ide><path>docs/charts/radar.md
<ide> All point* properties can be specified as an array. If these are set to an array
<ide> | `pointBorderColor` | `Color/Color[]` | The border color for points.
<ide> | `pointBorderWidth` | `Number/Number[]` | The width of the point border in pixels.
<ide> | `pointRadius` | `Number/Number[]` | The radius of the point shape. If set to 0, the point is not rendered.
<add>| `pointRotation` | `Number/Number[]` | The rotation of the point in degrees.
<ide> | `pointStyle` | `String/String[]/Image/Image[]` | Style of the point. [more...](#pointstyle)
<ide> | `pointHitRadius` | `Number/Number[]` | The pixel size of the non-displayed point that reacts to mouse events.
<ide> | `pointHoverBackgroundColor` | `Color/Color[]` | Point background color when hovered.
<ide><path>docs/configuration/elements.md
<ide> Global point options: `Chart.defaults.global.elements.point`
<ide> | -----| ---- | --------| -----------
<ide> | `radius` | `Number` | `3` | Point radius.
<ide> | [`pointStyle`](#point-styles) | `String` | `circle` | Point style.
<add>| `rotation` | `Number` | `0` | Point rotation (in degrees).
<ide> | `backgroundColor` | `Color` | `'rgba(0,0,0,0.1)'` | Point fill color.
<ide> | `borderWidth` | `Number` | `1` | Point stroke width.
<ide> | `borderColor` | `Color` | `'rgba(0,0,0,0.1)'` | Point stroke color.
<ide><path>src/controllers/controller.bubble.js
<ide> module.exports = function(Chart) {
<ide> borderWidth: options.borderWidth,
<ide> hitRadius: options.hitRadius,
<ide> pointStyle: options.pointStyle,
<add> rotation: options.rotation,
<ide> radius: reset ? 0 : options.radius,
<ide> skip: custom.skip || isNaN(x) || isNaN(y),
<ide> x: x,
<ide> module.exports = function(Chart) {
<ide> 'hoverBorderWidth',
<ide> 'hoverRadius',
<ide> 'hitRadius',
<del> 'pointStyle'
<add> 'pointStyle',
<add> 'rotation'
<ide> ];
<ide>
<ide> for (i = 0, ilen = keys.length; i < ilen; ++i) {
<ide> module.exports = function(Chart) {
<ide> dataset.radius,
<ide> options.radius
<ide> ], context, index);
<del>
<ide> return values;
<ide> }
<ide> });
<ide><path>src/controllers/controller.line.js
<ide> module.exports = function(Chart) {
<ide> return borderWidth;
<ide> },
<ide>
<add> getPointRotation: function(point, index) {
<add> var pointRotation = this.chart.options.elements.point.rotation;
<add> var dataset = this.getDataset();
<add> var custom = point.custom || {};
<add>
<add> if (!isNaN(custom.rotation)) {
<add> pointRotation = custom.rotation;
<add> } else if (!isNaN(dataset.pointRotation) || helpers.isArray(dataset.pointRotation)) {
<add> pointRotation = helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointRotation);
<add> }
<add> return pointRotation;
<add> },
<add>
<ide> updateElement: function(point, index, reset) {
<ide> var me = this;
<ide> var meta = me.getMeta();
<ide> module.exports = function(Chart) {
<ide> // Appearance
<ide> radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
<ide> pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
<add> rotation: me.getPointRotation(point, index),
<ide> backgroundColor: me.getPointBackgroundColor(point, index),
<ide> borderColor: me.getPointBorderColor(point, index),
<ide> borderWidth: me.getPointBorderWidth(point, index),
<ide><path>src/controllers/controller.radar.js
<ide> module.exports = function(Chart) {
<ide> borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
<ide> borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
<ide> pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
<add> rotation: custom.rotation ? custom.rotation : helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointElementOptions.rotation),
<ide>
<ide> // Tooltip
<ide> hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)
<ide><path>src/elements/element.point.js
<ide> module.exports = Element.extend({
<ide> var model = this._model;
<ide> var ctx = this._chart.ctx;
<ide> var pointStyle = vm.pointStyle;
<add> var rotation = vm.rotation;
<ide> var radius = vm.radius;
<ide> var x = vm.x;
<ide> var y = vm.y;
<ide> module.exports = Element.extend({
<ide> ctx.strokeStyle = vm.borderColor || defaultColor;
<ide> ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
<ide> ctx.fillStyle = vm.backgroundColor || defaultColor;
<del> helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y);
<add> helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
<ide> }
<ide> }
<ide> });
<ide><path>src/helpers/helpers.canvas.js
<ide> var exports = module.exports = {
<ide> }
<ide> },
<ide>
<del> drawPoint: function(ctx, style, radius, x, y) {
<add> drawPoint: function(ctx, style, radius, x, y, rotation) {
<ide> var type, edgeLength, xOffset, yOffset, height, size;
<add> rotation = rotation || 0;
<ide>
<ide> if (style && typeof style === 'object') {
<ide> type = style.toString();
<ide> var exports = module.exports = {
<ide> return;
<ide> }
<ide>
<add> ctx.save();
<add> ctx.translate(x, y);
<add> ctx.rotate(rotation * Math.PI / 180);
<add>
<ide> switch (style) {
<ide> // Default includes circle
<ide> default:
<ide> ctx.beginPath();
<del> ctx.arc(x, y, radius, 0, Math.PI * 2);
<add> ctx.arc(0, 0, radius, 0, Math.PI * 2);
<ide> ctx.closePath();
<ide> ctx.fill();
<ide> break;
<ide> case 'triangle':
<ide> ctx.beginPath();
<ide> edgeLength = 3 * radius / Math.sqrt(3);
<ide> height = edgeLength * Math.sqrt(3) / 2;
<del> ctx.moveTo(x - edgeLength / 2, y + height / 3);
<del> ctx.lineTo(x + edgeLength / 2, y + height / 3);
<del> ctx.lineTo(x, y - 2 * height / 3);
<add> ctx.moveTo(-edgeLength / 2, height / 3);
<add> ctx.lineTo(edgeLength / 2, height / 3);
<add> ctx.lineTo(0, -2 * height / 3);
<ide> ctx.closePath();
<ide> ctx.fill();
<ide> break;
<ide> case 'rect':
<ide> size = 1 / Math.SQRT2 * radius;
<ide> ctx.beginPath();
<del> ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
<del> ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
<add> ctx.fillRect(-size, -size, 2 * size, 2 * size);
<add> ctx.strokeRect(-size, -size, 2 * size, 2 * size);
<ide> break;
<ide> case 'rectRounded':
<ide> var offset = radius / Math.SQRT2;
<del> var leftX = x - offset;
<del> var topY = y - offset;
<add> var leftX = -offset;
<add> var topY = -offset;
<ide> var sideSize = Math.SQRT2 * radius;
<ide> ctx.beginPath();
<ide>
<ide> var exports = module.exports = {
<ide> case 'rectRot':
<ide> size = 1 / Math.SQRT2 * radius;
<ide> ctx.beginPath();
<del> ctx.moveTo(x - size, y);
<del> ctx.lineTo(x, y + size);
<del> ctx.lineTo(x + size, y);
<del> ctx.lineTo(x, y - size);
<add> ctx.moveTo(-size, 0);
<add> ctx.lineTo(0, size);
<add> ctx.lineTo(size, 0);
<add> ctx.lineTo(0, -size);
<ide> ctx.closePath();
<ide> ctx.fill();
<ide> break;
<ide> case 'cross':
<ide> ctx.beginPath();
<del> ctx.moveTo(x, y + radius);
<del> ctx.lineTo(x, y - radius);
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<add> ctx.moveTo(0, radius);
<add> ctx.lineTo(0, -radius);
<add> ctx.moveTo(-radius, 0);
<add> ctx.lineTo(radius, 0);
<ide> ctx.closePath();
<ide> break;
<ide> case 'crossRot':
<ide> ctx.beginPath();
<ide> xOffset = Math.cos(Math.PI / 4) * radius;
<ide> yOffset = Math.sin(Math.PI / 4) * radius;
<del> ctx.moveTo(x - xOffset, y - yOffset);
<del> ctx.lineTo(x + xOffset, y + yOffset);
<del> ctx.moveTo(x - xOffset, y + yOffset);
<del> ctx.lineTo(x + xOffset, y - yOffset);
<add> ctx.moveTo(-xOffset, -yOffset);
<add> ctx.lineTo(xOffset, yOffset);
<add> ctx.moveTo(-xOffset, yOffset);
<add> ctx.lineTo(xOffset, -yOffset);
<ide> ctx.closePath();
<ide> break;
<ide> case 'star':
<ide> ctx.beginPath();
<del> ctx.moveTo(x, y + radius);
<del> ctx.lineTo(x, y - radius);
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<add> ctx.moveTo(0, radius);
<add> ctx.lineTo(0, -radius);
<add> ctx.moveTo(-radius, 0);
<add> ctx.lineTo(radius, 0);
<ide> xOffset = Math.cos(Math.PI / 4) * radius;
<ide> yOffset = Math.sin(Math.PI / 4) * radius;
<del> ctx.moveTo(x - xOffset, y - yOffset);
<del> ctx.lineTo(x + xOffset, y + yOffset);
<del> ctx.moveTo(x - xOffset, y + yOffset);
<del> ctx.lineTo(x + xOffset, y - yOffset);
<add> ctx.moveTo(-xOffset, -yOffset);
<add> ctx.lineTo(xOffset, yOffset);
<add> ctx.moveTo(-xOffset, yOffset);
<add> ctx.lineTo(xOffset, -yOffset);
<ide> ctx.closePath();
<ide> break;
<ide> case 'line':
<ide> ctx.beginPath();
<del> ctx.moveTo(x - radius, y);
<del> ctx.lineTo(x + radius, y);
<add> ctx.moveTo(-radius, 0);
<add> ctx.lineTo(radius, 0);
<ide> ctx.closePath();
<ide> break;
<ide> case 'dash':
<ide> ctx.beginPath();
<del> ctx.moveTo(x, y);
<del> ctx.lineTo(x + radius, y);
<add> ctx.moveTo(0, 0);
<add> ctx.lineTo(radius, 0);
<ide> ctx.closePath();
<ide> break;
<ide> }
<ide>
<ide> ctx.stroke();
<add> ctx.restore();
<ide> },
<ide>
<ide> clipArea: function(ctx, area) {
<ide><path>test/specs/element.point.tests.js
<ide> describe('Point element tests', function() {
<ide> point._view = {
<ide> radius: 2,
<ide> pointStyle: 'circle',
<add> rotation: 25,
<ide> hitRadius: 3,
<ide> borderColor: 'rgba(1, 2, 3, 1)',
<ide> borderWidth: 6,
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'arc',
<del> args: [10, 15, 2, 0, 2 * Math.PI]
<add> args: [0, 0, 2, 0, 2 * Math.PI]
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - 3 * 2 / Math.sqrt(3) / 2, 15 + 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3]
<add> args: [0 - 3 * 2 / Math.sqrt(3) / 2, 0 + 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + 3 * 2 / Math.sqrt(3) / 2, 15 + 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3],
<add> args: [0 + 3 * 2 / Math.sqrt(3) / 2, 0 + 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10, 15 - 2 * 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3],
<add> args: [0, 0 - 2 * 3 * 2 / Math.sqrt(3) * Math.sqrt(3) / 2 / 3],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'fillRect',
<del> args: [10 - 1 / Math.SQRT2 * 2, 15 - 1 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2]
<add> args: [0 - 1 / Math.SQRT2 * 2, 0 - 1 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2]
<ide> }, {
<ide> name: 'strokeRect',
<del> args: [10 - 1 / Math.SQRT2 * 2, 15 - 1 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2]
<add> args: [0 - 1 / Math.SQRT2 * 2, 0 - 1 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2, 2 / Math.SQRT2 * 2]
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> var drawRoundedRectangleSpy = jasmine.createSpy('drawRoundedRectangle');
<ide> describe('Point element tests', function() {
<ide>
<ide> expect(drawRoundedRectangleSpy).toHaveBeenCalledWith(
<ide> mockContext,
<del> 10 - offset,
<del> 15 - offset,
<add> 0 - offset,
<add> 0 - offset,
<ide> Math.SQRT2 * 2,
<ide> Math.SQRT2 * 2,
<ide> 2 * 0.425
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - 1 / Math.SQRT2 * 2, 15]
<add> args: [0 - 1 / Math.SQRT2 * 2, 0]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10, 15 + 1 / Math.SQRT2 * 2]
<add> args: [0, 0 + 1 / Math.SQRT2 * 2]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + 1 / Math.SQRT2 * 2, 15],
<add> args: [0 + 1 / Math.SQRT2 * 2, 0],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10, 15 - 1 / Math.SQRT2 * 2],
<add> args: [0, 0 - 1 / Math.SQRT2 * 2],
<ide> }, {
<ide> name: 'closePath',
<ide> args: []
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10, 17]
<add> args: [0, 2]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10, 13],
<add> args: [0, -2],
<ide> }, {
<ide> name: 'moveTo',
<del> args: [8, 15],
<add> args: [-2, 0],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [12, 15],
<add> args: [2, 0],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - Math.cos(Math.PI / 4) * 2, 15 - Math.sin(Math.PI / 4) * 2]
<add> args: [0 - Math.cos(Math.PI / 4) * 2, 0 - Math.sin(Math.PI / 4) * 2]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + Math.cos(Math.PI / 4) * 2, 15 + Math.sin(Math.PI / 4) * 2],
<add> args: [0 + Math.cos(Math.PI / 4) * 2, 0 + Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - Math.cos(Math.PI / 4) * 2, 15 + Math.sin(Math.PI / 4) * 2],
<add> args: [0 - Math.cos(Math.PI / 4) * 2, 0 + Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + Math.cos(Math.PI / 4) * 2, 15 - Math.sin(Math.PI / 4) * 2],
<add> args: [0 + Math.cos(Math.PI / 4) * 2, 0 - Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10, 17]
<add> args: [0, 2]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10, 13],
<add> args: [0, -2],
<ide> }, {
<ide> name: 'moveTo',
<del> args: [8, 15],
<add> args: [-2, 0],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [12, 15],
<add> args: [2, 0],
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - Math.cos(Math.PI / 4) * 2, 15 - Math.sin(Math.PI / 4) * 2]
<add> args: [0 - Math.cos(Math.PI / 4) * 2, 0 - Math.sin(Math.PI / 4) * 2]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + Math.cos(Math.PI / 4) * 2, 15 + Math.sin(Math.PI / 4) * 2],
<add> args: [0 + Math.cos(Math.PI / 4) * 2, 0 + Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10 - Math.cos(Math.PI / 4) * 2, 15 + Math.sin(Math.PI / 4) * 2],
<add> args: [0 - Math.cos(Math.PI / 4) * 2, 0 + Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'lineTo',
<del> args: [10 + Math.cos(Math.PI / 4) * 2, 15 - Math.sin(Math.PI / 4) * 2],
<add> args: [0 + Math.cos(Math.PI / 4) * 2, 0 - Math.sin(Math.PI / 4) * 2],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [8, 15]
<add> args: [-2, 0]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [12, 15],
<add> args: [2, 0],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> mockContext.resetCalls();
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0, 255, 0)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [25 * Math.PI / 180]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'moveTo',
<del> args: [10, 15]
<add> args: [0, 0]
<ide> }, {
<ide> name: 'lineTo',
<del> args: [12, 15],
<add> args: [2, 0],
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide>
<ide> });
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'setFillStyle',
<ide> args: ['rgba(0,0,0,0.1)']
<add> }, {
<add> name: 'save',
<add> args: []
<add> }, {
<add> name: 'translate',
<add> args: [10, 15]
<add> }, {
<add> name: 'rotate',
<add> args: [0]
<ide> }, {
<ide> name: 'beginPath',
<ide> args: []
<ide> }, {
<ide> name: 'arc',
<del> args: [10, 15, 2, 0, 2 * Math.PI]
<add> args: [0, 0, 2, 0, 2 * Math.PI]
<ide> }, {
<ide> name: 'closePath',
<ide> args: [],
<ide> describe('Point element tests', function() {
<ide> }, {
<ide> name: 'stroke',
<ide> args: []
<add> }, {
<add> name: 'restore',
<add> args: []
<ide> }]);
<ide> });
<ide> | 10 |
Python | Python | move django.contrib.auth import out of compat | d6a8e020219a5c1a543b2b1c68de58ac03386b1d | <ide><path>rest_framework/compat.py
<ide> import django
<ide> from django.apps import apps
<ide> from django.conf import settings
<del>from django.contrib.auth import views
<ide> from django.core.exceptions import ImproperlyConfigured, ValidationError
<ide> from django.core.validators import \
<ide> MaxLengthValidator as DjangoMaxLengthValidator
<ide> def authenticate(request=None, **credentials):
<ide> else:
<ide> return authenticate(request=request, **credentials)
<ide>
<del>if django.VERSION < (1, 11):
<del> login = views.login
<del> login_kwargs = {'template_name': 'rest_framework/login.html'}
<del> logout = views.logout
<del>else:
<del> login = views.LoginView.as_view(template_name='rest_framework/login.html')
<del> login_kwargs = {}
<del> logout = views.LogoutView.as_view()
<ide><path>rest_framework/urls.py
<ide> """
<ide> from __future__ import unicode_literals
<ide>
<add>import django
<ide> from django.conf.urls import url
<add>from django.contrib.auth import views
<add>
<add>if django.VERSION < (1, 11):
<add> login = views.login
<add> login_kwargs = {'template_name': 'rest_framework/login.html'}
<add> logout = views.logout
<add>else:
<add> login = views.LoginView.as_view(template_name='rest_framework/login.html')
<add> login_kwargs = {}
<add> logout = views.LogoutView.as_view()
<ide>
<del>from rest_framework.compat import login, login_kwargs, logout
<ide>
<ide> app_name = 'rest_framework'
<ide> urlpatterns = [ | 2 |
Ruby | Ruby | use path attribute instead of reconstructing it | 22e3e6c1e6050b00799384c35dc2c232da421748 | <ide><path>Library/Homebrew/cmd/versions.rb
<ide> def pretty_relative_path
<ide> if Pathname.pwd == repository
<ide> entry_name
<ide> else
<del> repository/"#{entry_name}"
<add> path
<ide> end
<ide> end
<ide> | 1 |
Go | Go | implement deferred deletion functionality | d929589c1fc4538dcd1b2a7a3dc7d4afbdfa72fd | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> type devInfo struct {
<ide> Size uint64 `json:"size"`
<ide> TransactionID uint64 `json:"transaction_id"`
<ide> Initialized bool `json:"initialized"`
<add> Deleted bool `json:"deleted"`
<ide> devices *DeviceSet
<ide>
<ide> mountCount int
<ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo)
<ide> hash = ""
<ide> }
<ide>
<add> // Include deleted devices also as cleanup delete device logic
<add> // will go through it and see if there are any deleted devices.
<ide> if _, err := devices.lookupDevice(hash); err != nil {
<ide> return fmt.Errorf("Error looking up device %s:%v", hash, err)
<ide> }
<ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64, trans
<ide> return info, nil
<ide> }
<ide>
<del>func (devices *DeviceSet) activateDeviceIfNeeded(info *devInfo) error {
<add>func (devices *DeviceSet) activateDeviceIfNeeded(info *devInfo, ignoreDeleted bool) error {
<ide> logrus.Debugf("activateDeviceIfNeeded(%v)", info.Hash)
<ide>
<add> if info.Deleted && !ignoreDeleted {
<add> return fmt.Errorf("devmapper: Can't activate device %v as it is marked for deletion", info.Hash)
<add> }
<add>
<ide> // Make sure deferred removal on device is canceled, if one was
<ide> // scheduled.
<ide> if err := devices.cancelDeferredRemoval(info); err != nil {
<ide> func (devices *DeviceSet) migrateOldMetaData() error {
<ide> return nil
<ide> }
<ide>
<add>// Cleanup deleted devices. It assumes that all the devices have been
<add>// loaded in the hash table. Should be called with devices.Lock() held.
<add>// Will drop the lock for device deletion and return with lock acquired.
<add>func (devices *DeviceSet) cleanupDeletedDevices() error {
<add> var deletedDevices []*devInfo
<add>
<add> for _, info := range devices.Devices {
<add> if !info.Deleted {
<add> continue
<add> }
<add> logrus.Debugf("devmapper: Found deleted device %s.", info.Hash)
<add> deletedDevices = append(deletedDevices, info)
<add> }
<add>
<add> // Delete the deleted devices. DeleteDevice() first takes the info lock
<add> // and then devices.Lock(). So drop it to avoid deadlock.
<add> devices.Unlock()
<add> defer devices.Lock()
<add>
<add> for _, info := range deletedDevices {
<add> // This will again try deferred deletion.
<add> if err := devices.DeleteDevice(info.Hash, false); err != nil {
<add> logrus.Warnf("devmapper: Deletion of device %s, device_id=%v failed:%v", info.Hash, info.DeviceID, err)
<add> }
<add> }
<add>
<add> return nil
<add>}
<add>
<ide> func (devices *DeviceSet) initMetaData() error {
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide> func (devices *DeviceSet) initMetaData() error {
<ide> if err := devices.processPendingTransaction(); err != nil {
<ide> return err
<ide> }
<add>
<add> if err := devices.cleanupDeletedDevices(); err != nil {
<add> return err
<add> }
<add>
<ide> return nil
<ide> }
<ide>
<ide> func (devices *DeviceSet) verifyBaseDeviceUUID(baseInfo *devInfo) error {
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide>
<del> if err := devices.activateDeviceIfNeeded(baseInfo); err != nil {
<add> if err := devices.activateDeviceIfNeeded(baseInfo, false); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) saveBaseDeviceUUID(baseInfo *devInfo) error {
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide>
<del> if err := devices.activateDeviceIfNeeded(baseInfo); err != nil {
<add> if err := devices.activateDeviceIfNeeded(baseInfo, false); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) createBaseImage() error {
<ide>
<ide> logrus.Debugf("Creating filesystem on base device-mapper thin volume")
<ide>
<del> if err := devices.activateDeviceIfNeeded(info); err != nil {
<add> if err := devices.activateDeviceIfNeeded(info, false); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> // fresh.
<ide>
<ide> if oldInfo != nil {
<del> if oldInfo.Initialized {
<add> if oldInfo.Initialized && !oldInfo.Deleted {
<ide> if err := devices.setupVerifyBaseImageUUID(oldInfo); err != nil {
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> }
<ide>
<ide> logrus.Debugf("Removing uninitialized base image")
<del> if err := devices.DeleteDevice(""); err != nil {
<add> // If previous base device is in deferred delete state,
<add> // that needs to be cleaned up first. So don't try
<add> // deferred deletion.
<add> if err := devices.DeleteDevice("", true); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error {
<ide> logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s)", hash, baseHash)
<ide> defer logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash)
<ide>
<add> // If a deleted device exists, return error.
<ide> baseInfo, err := devices.lookupDeviceWithLock(baseHash)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<add> if baseInfo.Deleted {
<add> return fmt.Errorf("devmapper: Base device %v has been marked for deferred deletion", baseInfo.Hash)
<add> }
<add>
<ide> baseInfo.lock.Lock()
<ide> defer baseInfo.lock.Unlock()
<ide>
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide>
<add> // Also include deleted devices in case hash of new device is
<add> // same as one of the deleted devices.
<ide> if info, _ := devices.lookupDevice(hash); info != nil {
<del> return fmt.Errorf("device %s already exists", hash)
<add> return fmt.Errorf("device %s already exists. Deleted=%v", hash, info.Deleted)
<ide> }
<ide>
<ide> if err := devices.createRegisterSnapDevice(hash, baseInfo); err != nil {
<ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error {
<ide> return nil
<ide> }
<ide>
<add>func (devices *DeviceSet) markForDeferredDeletion(info *devInfo) error {
<add> // If device is already in deleted state, there is nothing to be done.
<add> if info.Deleted {
<add> return nil
<add> }
<add>
<add> logrus.Debugf("devmapper: Marking device %s for deferred deletion.", info.Hash)
<add>
<add> info.Deleted = true
<add>
<add> // save device metadata to refelect deleted state.
<add> if err := devices.saveMetadata(info); err != nil {
<add> info.Deleted = false
<add> return err
<add> }
<add> return nil
<add>}
<add>
<ide> // Should be caled with devices.Lock() held.
<del>func (devices *DeviceSet) deleteTransaction(info *devInfo) error {
<add>func (devices *DeviceSet) deleteTransaction(info *devInfo, syncDelete bool) error {
<ide> if err := devices.openTransaction(info.Hash, info.DeviceID); err != nil {
<ide> logrus.Debugf("Error opening transaction hash = %s deviceId = %d", "", info.DeviceID)
<ide> return err
<ide> }
<ide>
<ide> defer devices.closeTransaction()
<ide>
<del> if err := devicemapper.DeleteDevice(devices.getPoolDevName(), info.DeviceID); err != nil {
<del> logrus.Debugf("Error deleting device: %s", err)
<del> return err
<add> err := devicemapper.DeleteDevice(devices.getPoolDevName(), info.DeviceID)
<add> if err != nil {
<add> // If syncDelete is true, we want to return error. If deferred
<add> // deletion is not enabled, we return an error. If error is
<add> // something other then EBUSY, return an error.
<add> if syncDelete || !devices.deferredDelete || err != devicemapper.ErrBusy {
<add> logrus.Debugf("Error deleting device: %s", err)
<add> return err
<add> }
<ide> }
<ide>
<del> if err := devices.unregisterDevice(info.DeviceID, info.Hash); err != nil {
<del> return err
<add> if err == nil {
<add> if err := devices.unregisterDevice(info.DeviceID, info.Hash); err != nil {
<add> return err
<add> }
<add> } else {
<add> if err := devices.markForDeferredDeletion(info); err != nil {
<add> return err
<add> }
<ide> }
<ide>
<ide> return nil
<ide> func (devices *DeviceSet) issueDiscard(info *devInfo) error {
<ide> defer logrus.Debugf("devmapper: issueDiscard(device: %s). END", info.Hash)
<ide> // This is a workaround for the kernel not discarding block so
<ide> // on the thin pool when we remove a thinp device, so we do it
<del> // manually
<del> if err := devices.activateDeviceIfNeeded(info); err != nil {
<add> // manually.
<add> // Even if device is deferred deleted, activate it and isue
<add> // discards.
<add> if err := devices.activateDeviceIfNeeded(info, true); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) issueDiscard(info *devInfo) error {
<ide> }
<ide>
<ide> // Should be called with devices.Lock() held.
<del>func (devices *DeviceSet) deleteDevice(info *devInfo) error {
<add>func (devices *DeviceSet) deleteDevice(info *devInfo, syncDelete bool) error {
<ide> if devices.doBlkDiscard {
<ide> devices.issueDiscard(info)
<ide> }
<ide> func (devices *DeviceSet) deleteDevice(info *devInfo) error {
<ide> return err
<ide> }
<ide>
<del> if err := devices.deleteTransaction(info); err != nil {
<add> if err := devices.deleteTransaction(info, syncDelete); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) deleteDevice(info *devInfo) error {
<ide> return nil
<ide> }
<ide>
<del>// DeleteDevice deletes a device from the hash.
<del>func (devices *DeviceSet) DeleteDevice(hash string) error {
<add>// DeleteDevice will return success if device has been marked for deferred
<add>// removal. If one wants to override that and want DeleteDevice() to fail if
<add>// device was busy and could not be deleted, set syncDelete=true.
<add>func (devices *DeviceSet) DeleteDevice(hash string, syncDelete bool) error {
<add> logrus.Debugf("devmapper: DeleteDevice(hash=%v syncDelete=%v) START", hash, syncDelete)
<add> defer logrus.Debugf("devmapper: DeleteDevice(hash=%v syncDelete=%v) END", hash, syncDelete)
<ide> info, err := devices.lookupDeviceWithLock(hash)
<ide> if err != nil {
<ide> return err
<ide> func (devices *DeviceSet) DeleteDevice(hash string) error {
<ide> return fmt.Errorf("devmapper: Can't delete device %v as it is still mounted. mntCount=%v", info.Hash, info.mountCount)
<ide> }
<ide>
<del> return devices.deleteDevice(info)
<add> return devices.deleteDevice(info, syncDelete)
<ide> }
<ide>
<ide> func (devices *DeviceSet) deactivatePool() error {
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide> return err
<ide> }
<ide>
<add> if info.Deleted {
<add> return fmt.Errorf("devmapper: Can't mount device %v as it has been marked for deferred deletion", info.Hash)
<add> }
<add>
<ide> info.lock.Lock()
<ide> defer info.lock.Unlock()
<ide>
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide> return nil
<ide> }
<ide>
<del> if err := devices.activateDeviceIfNeeded(info); err != nil {
<add> if err := devices.activateDeviceIfNeeded(info, false); err != nil {
<ide> return fmt.Errorf("Error activating devmapper device for '%s': %s", hash, err)
<ide> }
<ide>
<ide> func (devices *DeviceSet) GetDeviceStatus(hash string) (*DevStatus, error) {
<ide> TransactionID: info.TransactionID,
<ide> }
<ide>
<del> if err := devices.activateDeviceIfNeeded(info); err != nil {
<add> if err := devices.activateDeviceIfNeeded(info, false); err != nil {
<ide> return nil, fmt.Errorf("Error activating devmapper device for '%s': %s", hash, err)
<ide> }
<ide>
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // This assumes the device has been properly Get/Put:ed and thus is unmounted
<del> if err := d.DeviceSet.DeleteDevice(id); err != nil {
<add> if err := d.DeviceSet.DeleteDevice(id, false); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>pkg/devicemapper/devmapper.go
<ide> func DeleteDevice(poolName string, deviceID int) error {
<ide> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<add> dmSawBusy = false
<ide> if err := task.run(); err != nil {
<add> if dmSawBusy {
<add> return ErrBusy
<add> }
<ide> return fmt.Errorf("Error running DeleteDevice %s", err)
<ide> }
<ide> return nil | 3 |
Ruby | Ruby | reduce funcalls by using falsey objects | c326969745c38aaca552aebf240af644440afab3 | <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb
<ide> def build(attributes = {})
<ide>
<ide> def replace(record)
<ide> record = record.target if AssociationProxy === record
<del> raise_on_type_mismatch(record) unless record.nil?
<add> raise_on_type_mismatch(record) if record
<ide>
<ide> update_counters(record)
<ide> replace_keys(record)
<ide> def find_target
<ide> end
<ide>
<ide> def foreign_key_present?
<del> !@owner[@reflection.foreign_key].nil?
<add> @owner[@reflection.foreign_key]
<ide> end
<ide>
<ide> # NOTE - for now, we're only supporting inverse setting from belongs_to back onto | 1 |
PHP | PHP | fix remaining tests in error package | 09e14444520c1c6542627bad4e1de44004df708b | <ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> public function setUp()
<ide> parent::setUp();
<ide> Router::reload();
<ide>
<del> $request = new ServerRequest();
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_REFERER' => '/referer'
<add> ]
<add> ]);
<ide> $request->base = '';
<del> $request->env('HTTP_REFERER', '/referer');
<ide>
<ide> Router::setRequestInfo($request);
<ide> Configure::write('debug', true);
<ide> public function testHandleException()
<ide> $errorHandler = new TestErrorHandler();
<ide>
<ide> $errorHandler->handleException($error);
<del> $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
<add> $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
<ide> }
<ide>
<ide> /**
<ide> public function testHandleExceptionLog()
<ide> ));
<ide>
<ide> $errorHandler->handleException($error);
<del> $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
<add> $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
<ide>
<ide> $errorHandler = new TestErrorHandler([
<ide> 'log' => true,
<ide> public function testHandleExceptionLogSkipping()
<ide> ]);
<ide>
<ide> $errorHandler->handleException($notFound);
<del> $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
<add> $this->assertContains('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
<ide>
<ide> $errorHandler->handleException($forbidden);
<del> $this->assertContains('Fooled you!', $errorHandler->response->body(), 'message missing.');
<add> $this->assertContains('Fooled you!', (string)$errorHandler->response->getBody(), 'message missing.');
<ide> }
<ide>
<ide> /**
<ide> public function testHandleFatalErrorPage()
<ide> Configure::write('debug', true);
<ide>
<ide> $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
<del> $result = $errorHandler->response->body();
<add> $result = (string)$errorHandler->response->getBody();
<ide> $this->assertContains('Something wrong', $result, 'message missing.');
<ide> $this->assertContains(__FILE__, $result, 'filename missing.');
<ide> $this->assertContains((string)$line, $result, 'line missing.');
<ide>
<ide> Configure::write('debug', false);
<ide> $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
<del> $result = $errorHandler->response->body();
<add> $result = (string)$errorHandler->response->getBody();
<ide> $this->assertNotContains('Something wrong', $result, 'message must not appear.');
<ide> $this->assertNotContains(__FILE__, $result, 'filename must not appear.');
<ide> $this->assertContains('An Internal Error Has Occurred.', $result);
<ide> public function testHandlePHP7Error()
<ide> $errorHandler = new TestErrorHandler();
<ide>
<ide> $errorHandler->handleException($error);
<del> $this->assertContains('Unexpected variable foo', $errorHandler->response->body(), 'message missing.');
<add> $this->assertContains('Unexpected variable foo', (string)$errorHandler->response->getBody(), 'message missing.');
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | replace some spaces with tabs | dfc6bb040994806f8d56fa995b2818209fd2ad59 | <ide><path>tests/Mail/MailMandrillTransportTest.php
<ide>
<ide> class MailMandrillTransportTest extends PHPUnit_Framework_TestCase {
<ide>
<del> public function testSend()
<del> {
<del> $message = new Swift_Message('Foo subject', 'Bar body');
<del> $message->setTo('me@example.com');
<del> $message->setBcc('you@example.com');
<del>
<del> $transport = new MandrillTransportStub('testkey');
<del> $client = $this->getMock('GuzzleHttp\Client', array('post'));
<del> $transport->setHttpClient($client);
<del>
<del> $client->expects($this->once())
<del> ->method('post')
<del> ->with($this->equalTo('https://mandrillapp.com/api/1.0/messages/send-raw.json'),
<del> $this->equalTo([
<del> 'body' => [
<del> 'key' => 'testkey',
<del> 'raw_message' => $message->toString(),
<del> 'async' => false,
<del> 'to' => ['me@example.com', 'you@example.com']
<del> ]
<del> ])
<del> );
<del>
<del> $transport->send($message);
<del> }
<add> public function testSend()
<add> {
<add> $message = new Swift_Message('Foo subject', 'Bar body');
<add> $message->setTo('me@example.com');
<add> $message->setBcc('you@example.com');
<add>
<add> $transport = new MandrillTransportStub('testkey');
<add> $client = $this->getMock('GuzzleHttp\Client', array('post'));
<add> $transport->setHttpClient($client);
<add>
<add> $client->expects($this->once())
<add> ->method('post')
<add> ->with($this->equalTo('https://mandrillapp.com/api/1.0/messages/send-raw.json'),
<add> $this->equalTo([
<add> 'body' => [
<add> 'key' => 'testkey',
<add> 'raw_message' => $message->toString(),
<add> 'async' => false,
<add> 'to' => ['me@example.com', 'you@example.com']
<add> ]
<add> ])
<add> );
<add>
<add> $transport->send($message);
<add> }
<ide> }
<ide>
<ide> class MandrillTransportStub extends \Illuminate\Mail\Transport\MandrillTransport
<ide> {
<del> protected $client;
<add> protected $client;
<ide>
<del> protected function getHttpClient()
<del> {
<del> return $this->client;
<del> }
<add> protected function getHttpClient()
<add> {
<add> return $this->client;
<add> }
<ide>
<del> public function setHttpClient($client)
<del> {
<del> $this->client = $client;
<del> }
<add> public function setHttpClient($client)
<add> {
<add> $this->client = $client;
<add> }
<ide> } | 1 |
Javascript | Javascript | fix handle delivery | 21bd45676390fd21ffa7c3cca91af4ad37ed3e5c | <ide><path>lib/child_process.js
<ide> function setupChannel(target, channel) {
<ide> var json = jsonBuffer.slice(start, i);
<ide> var message = JSON.parse(json);
<ide>
<del> handleMessage(target, message, recvHandle);
<del> recvHandle = undefined;
<add> // There will be at most one NODE_HANDLE message in every chunk we
<add> // read because SCM_RIGHTS messages don't get coalesced. Make sure
<add> // that we deliver the handle with the right message however.
<add> if (message && message.cmd === 'NODE_HANDLE')
<add> handleMessage(target, message, recvHandle);
<add> else
<add> handleMessage(target, message, undefined);
<ide>
<ide> start = i + 1;
<ide> }
<ide><path>test/simple/test-child-process-recv-handle.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>// Test that a Linux specific quirk in the handle passing protocol is handled
<add>// correctly. See https://github.com/joyent/node/issues/5330 for details.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var net = require('net');
<add>var spawn = require('child_process').spawn;
<add>
<add>if (process.argv[2] === 'worker')
<add> worker();
<add>else
<add> master();
<add>
<add>function master() {
<add> // spawn() can only create one IPC channel so we use stdin/stdout as an
<add> // ad-hoc command channel.
<add> var proc = spawn(process.execPath, [__filename, 'worker'], {
<add> stdio: ['pipe', 'pipe', 'pipe', 'ipc']
<add> });
<add> var handle = null;
<add> proc.on('exit', function() {
<add> handle.close();
<add> });
<add> proc.stdout.on('data', function(data) {
<add> assert.equal(data, 'ok\r\n');
<add> net.createServer(assert.fail).listen(common.PORT, function() {
<add> handle = this._handle;
<add> proc.send('one');
<add> proc.send('two', handle);
<add> proc.send('three');
<add> proc.stdin.write('ok\r\n');
<add> });
<add> });
<add> proc.stderr.pipe(process.stderr);
<add>}
<add>
<add>function worker() {
<add> process._channel.readStop(); // Make messages batch up.
<add> process.stdout.ref();
<add> process.stdout.write('ok\r\n');
<add> process.stdin.once('data', function(data) {
<add> assert.equal(data, 'ok\r\n');
<add> process._channel.readStart();
<add> });
<add> var n = 0;
<add> process.on('message', function(msg, handle) {
<add> n += 1;
<add> if (n === 1) {
<add> assert.equal(msg, 'one');
<add> assert.equal(handle, undefined);
<add> }
<add> else if (n === 2) {
<add> assert.equal(msg, 'two');
<add> assert.equal(typeof handle, 'object'); // Also matches null, therefore...
<add> assert.ok(handle); // also check that it's truthy.
<add> handle.close();
<add> }
<add> else if (n === 3) {
<add> assert.equal(msg, 'three');
<add> assert.equal(handle, undefined);
<add> process.exit();
<add> }
<add> });
<add>} | 2 |
Text | Text | add dataroots to airflow users | 5c79495279c60917843eb8a4c7ffc12716cc88e9 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [DataCamp](https://datacamp.com/) [[@dgrtwo](https://github.com/dgrtwo)]
<ide> 1. [DataFox](https://www.datafox.com/) [[@sudowork](https://github.com/sudowork)]
<ide> 1. [Datamaran](https://www.datamaran.com) [[@valexharo](https://github.com/valexharo)]
<add>1. [dataroots](https://dataroots.io/) [[@datarootsio]](https://github.com/datarootsio)
<ide> 1. [DataSprints](https://datasprints.com/) [[@lopesdiego12](https://github.com/lopesdiego12) & [@rafaelsantanaep](https://github.com/rafaelsantanaep)]
<ide> 1. [Datatonic](https://datatonic.com/) [[@teamdatatonic](https://github.com/teamdatatonic)]
<ide> 1. [Datumo](https://datumo.io) [[@michalmisiewicz](https://github.com/michalmisiewicz)] | 1 |
Javascript | Javascript | terminate cluster worker in infinite loop | 1f7b6a6cc916a8bab942e579ed930e9e2d66c4e0 | <ide><path>test/parallel/test-cluster-kill-infinite-loop.js
<add>'use strict';
<add>const common = require('../common');
<add>const cluster = require('cluster');
<add>const assert = require('assert');
<add>
<add>if (cluster.isMaster) {
<add> const worker = cluster.fork();
<add>
<add> worker.on('online', common.mustCall(() => {
<add> // Use worker.process.kill() instead of worker.kill() because the latter
<add> // waits for a graceful disconnect, which will never happen.
<add> worker.process.kill();
<add> }));
<add>
<add> worker.on('exit', common.mustCall((code, signal) => {
<add> assert.strictEqual(code, null);
<add> assert.strictEqual(signal, 'SIGTERM');
<add> }));
<add>} else {
<add> while (true) {}
<add>} | 1 |
Javascript | Javascript | add getkeyname function to codegen parser class | f849f495250ef446611e6936d587ba0da21b1b76 | <ide><path>packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js
<ide> const {
<ide> } = require('../errors');
<ide>
<ide> import {MockedParser} from '../parserMock';
<add>import {TypeScriptParser} from '../typescript/parser';
<ide>
<ide> const parser = new MockedParser();
<add>const typeScriptParser = new TypeScriptParser();
<ide>
<ide> const flowTranslateTypeAnnotation = require('../flow/modules/index');
<ide> const typeScriptTranslateTypeAnnotation = require('../typescript/modules/index');
<ide> describe('parseObjectProperty', () => {
<ide> aliasMap,
<ide> tryParse,
<ide> cxxOnly,
<del> language,
<ide> nullable,
<ide> flowTranslateTypeAnnotation,
<add> parser,
<ide> ),
<ide> ).toThrow(expected);
<ide> });
<ide> describe('parseObjectProperty', () => {
<ide> aliasMap,
<ide> tryParse,
<ide> cxxOnly,
<del> language,
<ide> nullable,
<ide> typeScriptTranslateTypeAnnotation,
<add> parser,
<ide> ),
<ide> ).toThrow(expected);
<ide> });
<ide> describe('parseObjectProperty', () => {
<ide> aliasMap,
<ide> tryParse,
<ide> cxxOnly,
<del> language,
<ide> nullable,
<ide> typeScriptTranslateTypeAnnotation,
<add> typeScriptParser,
<ide> );
<ide> const expected = {
<ide> name: 'testName',
<ide><path>packages/react-native-codegen/src/parsers/__tests__/parsers-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> * @flow strict-local
<add> * @format
<add> * @oncall react_native
<add> */
<add>
<add>'use-strict';
<add>
<add>const {
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add>} = require('../errors');
<add>
<add>import {TypeScriptParser} from '../typescript/parser';
<add>import {FlowParser} from '../flow/parser';
<add>
<add>const hasteModuleName = 'moduleName';
<add>describe('TypeScriptParser', () => {
<add> const parser = new FlowParser();
<add> describe('getKeyName', () => {
<add> describe('when propertyOrIndex is ObjectTypeProperty', () => {
<add> it('returns property name', () => {
<add> const property = {
<add> type: 'ObjectTypeProperty',
<add> key: {
<add> name: 'propertyName',
<add> },
<add> };
<add>
<add> const expected = 'propertyName';
<add>
<add> expect(parser.getKeyName(property, hasteModuleName)).toEqual(expected);
<add> });
<add> });
<add>
<add> describe('when propertyOrIndex is ObjectTypeIndexer', () => {
<add> it('returns indexer name', () => {
<add> const indexer = {
<add> type: 'ObjectTypeIndexer',
<add> id: {
<add> name: 'indexerName',
<add> },
<add> };
<add>
<add> const expected = 'indexerName';
<add>
<add> expect(parser.getKeyName(indexer, hasteModuleName)).toEqual(expected);
<add> });
<add>
<add> it('returns `key` if indexer has no name', () => {
<add> const indexer = {
<add> type: 'ObjectTypeIndexer',
<add> id: {},
<add> };
<add>
<add> const expected = 'key';
<add>
<add> expect(parser.getKeyName(indexer, hasteModuleName)).toEqual(expected);
<add> });
<add> });
<add>
<add> describe('when propertyOrIndex is not ObjectTypeProperty or ObjectTypeIndexer', () => {
<add> it('throw UnsupportedObjectPropertyTypeAnnotationParserError', () => {
<add> const indexer = {
<add> type: 'EnumDeclaration',
<add> memberType: 'NumberTypeAnnotation',
<add> };
<add>
<add> expect(() => parser.getKeyName(indexer, hasteModuleName)).toThrowError(
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add> );
<add> });
<add> });
<add> });
<add>});
<add>
<add>describe('FlowParser', () => {
<add> const parser = new TypeScriptParser();
<add> describe('getKeyName', () => {
<add> describe('when propertyOrIndex is TSPropertySignature', () => {
<add> it('returns property name', () => {
<add> const property = {
<add> type: 'TSPropertySignature',
<add> key: {
<add> name: 'propertyName',
<add> },
<add> };
<add>
<add> const expected = 'propertyName';
<add>
<add> expect(parser.getKeyName(property, hasteModuleName)).toEqual(expected);
<add> });
<add> });
<add>
<add> describe('when propertyOrIndex is TSIndexSignature', () => {
<add> it('returns indexer name', () => {
<add> const indexer = {
<add> type: 'TSIndexSignature',
<add> parameters: [
<add> {
<add> name: 'indexerName',
<add> },
<add> ],
<add> };
<add>
<add> const expected = 'indexerName';
<add>
<add> expect(parser.getKeyName(indexer, hasteModuleName)).toEqual(expected);
<add> });
<add> });
<add>
<add> describe('when propertyOrIndex is not TSPropertySignature or TSIndexSignature', () => {
<add> it('throw UnsupportedObjectPropertyTypeAnnotationParserError', () => {
<add> const indexer = {
<add> type: 'TSEnumDeclaration',
<add> memberType: 'NumberTypeAnnotation',
<add> };
<add>
<add> expect(() => parser.getKeyName(indexer, hasteModuleName)).toThrowError(
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add> );
<add> });
<add> });
<add> });
<add>});
<ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js
<ide> function translateTypeAnnotation(
<ide> aliasMap,
<ide> tryParse,
<ide> cxxOnly,
<del> language,
<ide> nullable,
<ide> translateTypeAnnotation,
<add> parser,
<ide> );
<ide> });
<ide> },
<ide><path>packages/react-native-codegen/src/parsers/flow/parser.js
<ide> import type {ParserType} from '../errors';
<ide> import type {Parser} from '../parser';
<ide>
<add>const {
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add>} = require('../errors');
<add>
<ide> class FlowParser implements Parser {
<ide> typeParameterInstantiation: string = 'TypeParameterInstantiation';
<ide>
<add> getKeyName(propertyOrIndex: $FlowFixMe, hasteModuleName: string): string {
<add> switch (propertyOrIndex.type) {
<add> case 'ObjectTypeProperty':
<add> return propertyOrIndex.key.name;
<add> case 'ObjectTypeIndexer':
<add> // flow index name is optional
<add> return propertyOrIndex.id?.name ?? 'key';
<add> default:
<add> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<add> hasteModuleName,
<add> propertyOrIndex,
<add> propertyOrIndex.type,
<add> this.language(),
<add> );
<add> }
<add> }
<add>
<ide> getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string {
<ide> return maybeEnumDeclaration.body.type
<ide> .replace('EnumNumberBody', 'NumberTypeAnnotation')
<ide><path>packages/react-native-codegen/src/parsers/parser.js
<ide> export interface Parser {
<ide> */
<ide> typeParameterInstantiation: string;
<ide>
<add> /**
<add> * Given a property or an index declaration, it returns the key name.
<add> * @parameter propertyOrIndex: an object containing a property or an index declaration.
<add> * @parameter hasteModuleName: a string with the native module name.
<add> * @returns: the key name.
<add> * @throws if propertyOrIndex does not contain a property or an index declaration.
<add> */
<add> getKeyName(propertyOrIndex: $FlowFixMe, hasteModuleName: string): string;
<ide> /**
<ide> * Given a type declaration, it possibly returns the name of the Enum type.
<ide> * @parameter maybeEnumDeclaration: an object possibly containing an Enum declaration.
<ide><path>packages/react-native-codegen/src/parsers/parserMock.js
<ide> import type {Parser} from './parser';
<ide> import type {ParserType} from './errors';
<ide>
<add>const {
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add>} = require('./errors');
<add>
<ide> export class MockedParser implements Parser {
<ide> typeParameterInstantiation: string = 'TypeParameterInstantiation';
<ide>
<add> getKeyName(propertyOrIndex: $FlowFixMe, hasteModuleName: string): string {
<add> switch (propertyOrIndex.type) {
<add> case 'ObjectTypeProperty':
<add> return propertyOrIndex.key.name;
<add> case 'ObjectTypeIndexer':
<add> // flow index name is optional
<add> return propertyOrIndex.id?.name ?? 'key';
<add> default:
<add> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<add> hasteModuleName,
<add> propertyOrIndex,
<add> propertyOrIndex.type,
<add> this.language(),
<add> );
<add> }
<add> }
<add>
<ide> getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string {
<ide> return maybeEnumDeclaration.body.type
<ide> .replace('EnumNumberBody', 'NumberTypeAnnotation')
<ide><path>packages/react-native-codegen/src/parsers/parsers-commons.js
<ide> function parseObjectProperty(
<ide> aliasMap: {...NativeModuleAliasMap},
<ide> tryParse: ParserErrorCapturer,
<ide> cxxOnly: boolean,
<del> language: ParserType,
<ide> nullable: boolean,
<ide> translateTypeAnnotation: $FlowFixMe,
<add> parser: Parser,
<ide> ): NamedShape<Nullable<NativeModuleBaseTypeAnnotation>> {
<add> const language = parser.language();
<add>
<ide> if (!isObjectProperty(property, language)) {
<ide> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<ide> hasteModuleName,
<ide> function parseObjectProperty(
<ide> }
<ide>
<ide> const {optional = false} = property;
<del> const name = getKeyName(property, hasteModuleName, language);
<add> const name = parser.getKeyName(property, hasteModuleName);
<ide> const languageTypeAnnotation =
<ide> language === 'TypeScript'
<ide> ? property.typeAnnotation.typeAnnotation
<ide> function translateDefault(
<ide> );
<ide> }
<ide>
<del>function getKeyName(
<del> propertyOrIndex: $FlowFixMe,
<del> hasteModuleName: string,
<del> language: ParserType,
<del>): string {
<del> switch (propertyOrIndex.type) {
<del> case 'ObjectTypeProperty':
<del> case 'TSPropertySignature':
<del> return propertyOrIndex.key.name;
<del> case 'ObjectTypeIndexer':
<del> // flow index name is optional
<del> return propertyOrIndex.id?.name ?? 'key';
<del> case 'TSIndexSignature':
<del> // TypeScript index name is mandatory
<del> return propertyOrIndex.parameters[0].name;
<del> default:
<del> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<del> hasteModuleName,
<del> propertyOrIndex,
<del> propertyOrIndex.type,
<del> language,
<del> );
<del> }
<del>}
<del>
<ide> module.exports = {
<ide> wrapModuleSchema,
<ide> unwrapNullable,
<ide> module.exports = {
<ide> parseObjectProperty,
<ide> emitUnionTypeAnnotation,
<ide> translateDefault,
<del> getKeyName,
<ide> };
<ide><path>packages/react-native-codegen/src/parsers/typescript/modules/index.js
<ide> function translateTypeAnnotation(
<ide> aliasMap,
<ide> tryParse,
<ide> cxxOnly,
<del> language,
<ide> nullable,
<ide> translateTypeAnnotation,
<add> parser,
<ide> );
<ide> });
<ide> },
<ide><path>packages/react-native-codegen/src/parsers/typescript/parser.js
<ide> import type {ParserType} from '../errors';
<ide> import type {Parser} from '../parser';
<ide>
<add>const {
<add> UnsupportedObjectPropertyTypeAnnotationParserError,
<add>} = require('../errors');
<add>
<ide> class TypeScriptParser implements Parser {
<ide> typeParameterInstantiation: string = 'TSTypeParameterInstantiation';
<ide>
<add> getKeyName(propertyOrIndex: $FlowFixMe, hasteModuleName: string): string {
<add> switch (propertyOrIndex.type) {
<add> case 'TSPropertySignature':
<add> return propertyOrIndex.key.name;
<add> case 'TSIndexSignature':
<add> return propertyOrIndex.parameters[0].name;
<add> default:
<add> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<add> hasteModuleName,
<add> propertyOrIndex,
<add> propertyOrIndex.type,
<add> this.language(),
<add> );
<add> }
<add> }
<add>
<ide> getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string {
<ide> if (maybeEnumDeclaration.members[0].initializer) {
<ide> return maybeEnumDeclaration.members[0].initializer.type | 9 |
Python | Python | fix the os check | f4cf6a31ac29d981bd0efcd9e7d2131242214840 | <ide><path>libcloud/test/test_utils.py
<ide> def tearDown(self):
<ide> WARNINGS_BUFFER = []
<ide> warnings.showwarning = original_func
<ide>
<del> @unittest.skipIf(platform.platform().lower() == 'windows', 'Unsupported on Windows')
<add> @unittest.skipIf(platform.system().lower() == 'windows', 'Unsupported on Windows')
<ide> def test_guess_file_mime_type(self):
<ide> file_path = os.path.abspath(__file__)
<ide> mimetype, encoding = libcloud.utils.files.guess_file_mime_type( | 1 |
Javascript | Javascript | add a note about a mouseenter bug in chrome | a5e1c9b44c971fd7046d9a95bd0810e50840b663 | <ide><path>src/event.js
<ide> jQuery.Event.prototype = {
<ide> // Do the same for pointerenter/pointerleave and pointerover/pointerout
<ide> // Support: Safari<7.0
<ide> // Safari doesn't support mouseenter/mouseleave at all.
<add>// Support: Chrome 40+
<add>// Mouseenter doesn't perform while left mouse button is pressed
<add>// (and initiated outside the observed element)
<add>// https://code.google.com/p/chromium/issues/detail?id=333868
<ide> jQuery.each({
<ide> mouseenter: "mouseover",
<ide> mouseleave: "mouseout", | 1 |
Javascript | Javascript | use public getcursorpos() | befff8fa6004d2d1d45bd28674e5f97fa4dbfa16 | <ide><path>lib/internal/repl/utils.js
<ide> function setupPreview(repl, contextSymbol, bufferSymbol, active) {
<ide>
<ide> function getPreviewPos() {
<ide> const displayPos = repl._getDisplayPos(`${repl._prompt}${repl.line}`);
<del> const cursorPos = repl._getCursorPos();
<add> const cursorPos = repl.getCursorPos();
<ide> const rows = 1 + displayPos.rows - cursorPos.rows;
<ide> return { rows, cols: cursorPos.cols };
<ide> }
<ide> function setupReverseSearch(repl) {
<ide> rows = repl._getDisplayPos(`${repl._prompt}${line}`).rows;
<ide> cursorTo(repl.output, promptPos.cols);
<ide> } else if (isInReverseSearch && repl.line !== '') {
<del> rows = repl._getCursorPos().rows;
<add> rows = repl.getCursorPos().rows;
<ide> cursorTo(repl.output, promptPos.cols);
<ide> }
<ide> if (rows !== 0)
<ide> function setupReverseSearch(repl) {
<ide> if (repl.line !== '') {
<ide> repl.output.write(repl.line);
<ide> if (repl.line.length !== repl.cursor) {
<del> const { cols, rows } = repl._getCursorPos();
<add> const { cols, rows } = repl.getCursorPos();
<ide> cursorTo(repl.output, cols);
<ide> if (rows !== 0)
<ide> moveCursor(repl.output, 0, rows); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.